From f8485ce6a63c154b379d7dffe6d799b778a13cd4 Mon Sep 17 00:00:00 2001 From: QDarkRex Date: Sun, 27 Sep 2026 12:24:14 +0700 Subject: [PATCH 1/7] fix(relinker): return unpacked exit status and wait for a single Enter in autorun std::system returns a wait status on POSIX, so returning it from main truncated a guest exit code of 1 (status 256) to 0. The prompt also required pressing Enter twice because cin.get followed cin.ignore. Co-Authored-By: Claude Opus 5.5 --- core/relinker/cli/src/Autorun.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core/relinker/cli/src/Autorun.cpp b/core/relinker/cli/src/Autorun.cpp index 79418f33a..30979a985 100644 --- a/core/relinker/cli/src/Autorun.cpp +++ b/core/relinker/cli/src/Autorun.cpp @@ -19,17 +19,18 @@ int Autorun(const std::string& absPath, bool toWindows) { const std::string cmd = "\"" + absPath + "\""; const int rawCode = std::system(cmd.c_str()); + int exitCode = rawCode; if (toWindows) { std::cout << "\nExit code: " << rawCode << '\n'; } else { - std::cout << "\nRaw exit code: " << rawCode << "; Unpacked: " << (rawCode >> 8) << '\n'; + if (rawCode != -1) exitCode = (rawCode >> 8) & 0xFF; + std::cout << "\nRaw exit code: " << rawCode << "; Unpacked: " << exitCode << '\n'; } std::cout << "\nPress Enter to exit...\n"; std::cin.ignore(std::numeric_limits::max(), '\n'); - std::cin.get(); - return rawCode; + return exitCode; } } From 7ac1198e74973e54872ab3ab4f75c18299af5e06 Mon Sep 17 00:00:00 2001 From: QDarkRex Date: Sun, 27 Sep 2026 12:24:15 +0700 Subject: [PATCH 2/7] fix(audioout): reject zero sample count and frequency in sceAudioOutOpen A zero frequency was stored and later used as a divisor when computing the output block duration. Return SCE_AUDIO_OUT_ERROR_INVALID_SIZE and SCE_AUDIO_OUT_ERROR_INVALID_SAMPLE_FREQ instead. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAudioOut/src/AudioOut.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/core/libs/prx/libSceAudioOut/src/AudioOut.cpp b/core/libs/prx/libSceAudioOut/src/AudioOut.cpp index 64478c4b4..4fd24c497 100644 --- a/core/libs/prx/libSceAudioOut/src/AudioOut.cpp +++ b/core/libs/prx/libSceAudioOut/src/AudioOut.cpp @@ -273,6 +273,12 @@ int APS5_VABI sceAudioOutOpen(int userId, int type, int index, std::uint32_t len if (!portTypeValid(type)) { return -2144993270; } + if (len == 0) { + return -2144993274; + } + if (freq == 0) { + return -2144993272; + } if (index != 0) { throw std::runtime_error("sceAudioOutOpen: index != 0 not supported"); } From 908befe81d06c7d1b7233e830db79bd22a082116 Mon Sep 17 00:00:00 2001 From: QDarkRex Date: Sun, 27 Sep 2026 12:24:15 +0700 Subject: [PATCH 3/7] feat(relinker): add --windows-gui to emit a GUI subsystem executable Generated executables always used the console subsystem and opened a console window on launch. The opt-in flag writes IMAGE_SUBSYSTEM_WINDOWS_GUI. Co-Authored-By: Claude Opus 5.5 --- core/relinker/CMakeLists.txt | 4 +- core/relinker/cli/include/Cli.hpp | 1 + core/relinker/cli/src/CliArgs.cpp | 7 ++- .../elfpatcher/windows/WindowsElfPatcher.hpp | 5 +++ .../elfpatcher/windows/WindowsPeWriter.hpp | 2 +- .../src/windows/WindowsPePatcher.cpp | 5 ++- .../src/windows/WindowsPeWriter.cpp | 4 +- core/relinker/main.cpp | 2 +- .../relinker/tests/test_windows_gui.py | 44 +++++++++++++++++++ 9 files changed, 67 insertions(+), 7 deletions(-) create mode 100644 core/relinker/relinker/tests/test_windows_gui.py diff --git a/core/relinker/CMakeLists.txt b/core/relinker/CMakeLists.txt index a48325819..60005a6f8 100644 --- a/core/relinker/CMakeLists.txt +++ b/core/relinker/CMakeLists.txt @@ -79,8 +79,10 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_optional_plt.py $) add_test(NAME empty_tls COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_empty_tls.py $) + add_test(NAME windows_gui COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_windows_gui.py $) else() - message(STATUS "Python3 interpreter not found; skipping optional_plt and empty_tls tests") + message(STATUS "Python3 interpreter not found; skipping optional_plt, empty_tls and windows_gui tests") endif() add_executable(strict_nid_filter_tests ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/StrictNidFilterTests.cpp diff --git a/core/relinker/cli/include/Cli.hpp b/core/relinker/cli/include/Cli.hpp index 369cb7f60..642d5d809 100644 --- a/core/relinker/cli/include/Cli.hpp +++ b/core/relinker/cli/include/Cli.hpp @@ -14,6 +14,7 @@ struct Args { bool lazyBinding = false; bool autorun = false; bool windowsDiagnostics = false; + bool windowsGui = false; std::uint32_t unusedFilterLevel = 0; std::string inputPath; std::string outputPath; diff --git a/core/relinker/cli/src/CliArgs.cpp b/core/relinker/cli/src/CliArgs.cpp index 12b1631f0..f5be7b56e 100644 --- a/core/relinker/cli/src/CliArgs.cpp +++ b/core/relinker/cli/src/CliArgs.cpp @@ -35,6 +35,8 @@ Args ParseArgs(int argc, char* argv[]) { args.autorun = true; } else if (arg == "--windows-diagnostics") { args.windowsDiagnostics = true; + } else if (arg == "--windows-gui") { + args.windowsGui = true; } else if (arg.rfind("--", 0) == 0 || arg == "unused-filter") { throw std::runtime_error("unknown option: " + arg); } else if (args.inputPath.empty()) { @@ -49,9 +51,12 @@ Args ParseArgs(int argc, char* argv[]) { if (args.windowsDiagnostics && !args.toWindows) throw std::runtime_error("--windows-diagnostics requires --windows"); + if (args.windowsGui && !args.toWindows) + throw std::runtime_error("--windows-gui requires --windows"); + if (args.inputPath.empty() || args.outputPath.empty()) throw std::runtime_error( - "Usage: relinker [--windows] [--windows-diagnostics] [--skip-syscall-check] [--to-intel] [unused-filter=0|1|2] [--registry] [--rpath ] [--lazy-binding] [--autorun] \n" + "Usage: relinker [--windows] [--windows-diagnostics] [--windows-gui] [--skip-syscall-check] [--to-intel] [unused-filter=0|1|2] [--registry] [--rpath ] [--lazy-binding] [--autorun] \n" "Example: relinker input.elf output.elf" ); diff --git a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsElfPatcher.hpp b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsElfPatcher.hpp index 2ee1017a0..409286e46 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsElfPatcher.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsElfPatcher.hpp @@ -7,7 +7,12 @@ namespace Elfpatcher::Windows { class WindowsPePatcher : public IElfPatcher { public: + explicit WindowsPePatcher(bool windowsGui = false); + std::vector Patch(const std::vector& sourceElf, const std::vector& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, std::uint64_t originalPltGotVaddr, const std::string& runPath, bool lazyBinding, bool dependencyDiagnostics) override; + +private: + bool _windowsGui; }; } diff --git a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsPeWriter.hpp b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsPeWriter.hpp index bfcc3d24c..9692b150b 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsPeWriter.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsPeWriter.hpp @@ -7,7 +7,7 @@ namespace Elfpatcher::Windows { class WindowsPeWriter { public: - std::vector Write(const std::vector& sections, std::uint32_t entryRva, const std::array& directories) const; + std::vector Write(const std::vector& sections, std::uint32_t entryRva, const std::array& directories, bool windowsGui = false) const; }; } diff --git a/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp b/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp index 0910e7aad..2b07c6444 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp @@ -39,6 +39,9 @@ void writeGotStub(std::vector& sections, const std::uint32_t targetRv } +WindowsPePatcher::WindowsPePatcher(const bool windowsGui) : _windowsGui(windowsGui) { +} + std::vector WindowsPePatcher::Patch(const std::vector& sourceElf, const std::vector& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, const std::uint64_t originalPltGotVaddr, const std::string& runPath, const bool lazyBinding, const bool dependencyDiagnostics) { WindowsLoadImage image(sourceElf, originalHeaders); if (originalPltGotVaddr != 0) @@ -89,7 +92,7 @@ std::vector WindowsPePatcher::Patch(const std::vector WindowsPeWriter::Write(const std::vector& sections, const std::uint32_t entryRva, const std::array& directories) const { +std::vector WindowsPeWriter::Write(const std::vector& sections, const std::uint32_t entryRva, const std::array& directories, const bool windowsGui) const { constexpr std::size_t peOffset = 0x80; constexpr std::size_t optionalOffset = peOffset + 24; constexpr std::size_t sectionTable = optionalOffset + 240; @@ -29,7 +29,7 @@ std::vector WindowsPeWriter::Write(const std::vector& s Io::WriteU16(result, optionalOffset + 48, 6); Io::WriteU16(result, optionalOffset + 50, 2); Io::WriteU32(result, optionalOffset + 60, LoadRva); - Io::WriteU16(result, optionalOffset + 68, 3); + Io::WriteU16(result, optionalOffset + 68, windowsGui ? 2 : 3); Io::WriteU16(result, optionalOffset + 70, directories[5].Size == 0 ? 0x100 : 0x160); Io::WriteU64(result, optionalOffset + 72, 0x210000); Io::WriteU64(result, optionalOffset + 80, 0x200000); diff --git a/core/relinker/main.cpp b/core/relinker/main.cpp index 90f087e60..86441ebab 100644 --- a/core/relinker/main.cpp +++ b/core/relinker/main.cpp @@ -82,7 +82,7 @@ int main(const int argc, char* argv[]) { std::shared_ptr patcher; if (args.toWindows) { - patcher = std::make_shared(); + patcher = std::make_shared(args.windowsGui); } else { patcher = std::make_shared( std::make_shared(), diff --git a/core/relinker/relinker/tests/test_windows_gui.py b/core/relinker/relinker/tests/test_windows_gui.py new file mode 100644 index 000000000..12698e829 --- /dev/null +++ b/core/relinker/relinker/tests/test_windows_gui.py @@ -0,0 +1,44 @@ +"""Validate the --windows-gui PE subsystem flag through the real ELF-to-PE pipeline.""" + +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from test_optional_plt import fixture + + +def subsystem(pe): + pe_offset = struct.unpack_from(" Date: Sun, 27 Sep 2026 12:38:59 +0700 Subject: [PATCH 4/7] fix(kernel): give every thread a pthread handle and keep mutex ownership consistent - scePthreadSelf returned null on Linux and for threads not created by scePthreadCreate (including the main thread); such threads now get a lazily adopted, non-joinable handle - scePthreadExit on Linux skipped FinishThread, losing the join value - detached threads on Linux were never freed; use the reference count already used on Windows - unlocking a recursive mutex from a non-owner was undefined behaviour; return SCE_KERNEL_ERROR_EPERM - scePthreadCondTimedwait did not restore the mutex owner after waking, so another thread locking during the wait made the waiter's unlock fail with EPERM and left the mutex locked forever - SCE_KERNEL_ERROR_ETIMEDOUT in Cond.cpp was 0x80020062 instead of 0x8002003C Co-Authored-By: Claude Opus 5.5 --- core/libs/CMakeLists.txt | 20 +++++ .../prx/libkernel/Pthread/include/Pthread.hpp | 7 +- core/libs/prx/libkernel/Pthread/src/Cond.cpp | 9 ++- core/libs/prx/libkernel/Pthread/src/Mutex.cpp | 2 + .../libs/prx/libkernel/Pthread/src/Thread.cpp | 45 ++++++++--- core/libs/tests/GuestCondTimedwait.cpp | 52 +++++++++++++ core/libs/tests/GuestThreadSelf.cpp | 75 +++++++++++++++++++ 7 files changed, 197 insertions(+), 13 deletions(-) create mode 100644 core/libs/tests/GuestCondTimedwait.cpp create mode 100644 core/libs/tests/GuestThreadSelf.cpp diff --git a/core/libs/CMakeLists.txt b/core/libs/CMakeLists.txt index 2ad90fd7e..c8abb5269 100644 --- a/core/libs/CMakeLists.txt +++ b/core/libs/CMakeLists.txt @@ -240,6 +240,26 @@ if(BUILD_TESTING) set_tests_properties(guest_once PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_executable(guest_thread_self_tests tests/GuestThreadSelf.cpp) + target_include_directories(guest_thread_self_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(guest_thread_self_tests PRIVATE libkernel libc) + configure_windows_unwind(guest_thread_self_tests) + add_test(NAME guest_thread_self COMMAND guest_thread_self_tests) + set_tests_properties(guest_thread_self PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(guest_thread_self PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() + add_executable(guest_cond_timedwait_tests tests/GuestCondTimedwait.cpp) + target_include_directories(guest_cond_timedwait_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(guest_cond_timedwait_tests PRIVATE libkernel libc) + configure_windows_unwind(guest_cond_timedwait_tests) + add_test(NAME guest_cond_timedwait COMMAND guest_cond_timedwait_tests) + set_tests_properties(guest_cond_timedwait PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(guest_cond_timedwait PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_executable(guest_signal_tests tests/GuestSignals.cpp) target_include_directories(guest_signal_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(guest_signal_tests PRIVATE libkernel libc) diff --git a/core/libs/prx/libkernel/Pthread/include/Pthread.hpp b/core/libs/prx/libkernel/Pthread/include/Pthread.hpp index e0adf92b8..1e4c313f0 100644 --- a/core/libs/prx/libkernel/Pthread/include/Pthread.hpp +++ b/core/libs/prx/libkernel/Pthread/include/Pthread.hpp @@ -51,20 +51,21 @@ struct PthreadAttrPrivate { struct PthreadPrivate { #ifdef _WIN32 void* nativeHandle = nullptr; - std::thread::id threadId; - std::atomic references{2}; #else std::thread _thr; #endif + std::thread::id threadId; + std::atomic references{2}; void* stackAddress = nullptr; std::size_t stackSize = 0; std::atomic _finished; void* _retval; bool _detached; + bool _adopted; std::mutex _join_mtx; std::condition_variable _join_cv; - PthreadPrivate() : _finished(false), _retval(nullptr), _detached(false) {} + PthreadPrivate() : _finished(false), _retval(nullptr), _detached(false), _adopted(false) {} }; #endif diff --git a/core/libs/prx/libkernel/Pthread/src/Cond.cpp b/core/libs/prx/libkernel/Pthread/src/Cond.cpp index 754a076f3..8d7494f26 100644 --- a/core/libs/prx/libkernel/Pthread/src/Cond.cpp +++ b/core/libs/prx/libkernel/Pthread/src/Cond.cpp @@ -5,7 +5,7 @@ static constexpr int SCE_OK = 0; static constexpr int SCE_KERNEL_ERROR_ENOMEM = 0x8002000C; -static constexpr int SCE_KERNEL_ERROR_ETIMEDOUT = 0x80020062; +static constexpr int SCE_KERNEL_ERROR_ETIMEDOUT = 0x8002003C; extern "C" { @@ -58,12 +58,19 @@ int APS5_VABI scePthreadCondTimedwait(PthreadCond* cond, PthreadMutex* mutex, un auto* c = *cond; if (m->_type == MutexType::Recursive) { std::unique_lock lk(m->_rmtx, std::adopt_lock); + const int savedCount = m->_count; + m->_count = 0; + m->_owner.store(std::thread::id{}, std::memory_order_relaxed); auto res = c->_cv.wait_for(lk, std::chrono::microseconds(usec)); + m->_owner.store(std::this_thread::get_id(), std::memory_order_relaxed); + m->_count = savedCount; lk.release(); return res == std::cv_status::timeout ? SCE_KERNEL_ERROR_ETIMEDOUT : SCE_OK; } std::unique_lock lk(m->_mtx, std::adopt_lock); + m->_owner.store(std::thread::id{}, std::memory_order_relaxed); auto res = c->_cv.wait_for(lk, std::chrono::microseconds(usec)); + m->_owner.store(std::this_thread::get_id(), std::memory_order_relaxed); lk.release(); return res == std::cv_status::timeout ? SCE_KERNEL_ERROR_ETIMEDOUT : SCE_OK; } diff --git a/core/libs/prx/libkernel/Pthread/src/Mutex.cpp b/core/libs/prx/libkernel/Pthread/src/Mutex.cpp index cc9ac1881..e586e4060 100644 --- a/core/libs/prx/libkernel/Pthread/src/Mutex.cpp +++ b/core/libs/prx/libkernel/Pthread/src/Mutex.cpp @@ -81,6 +81,8 @@ int APS5_VABI scePthreadMutexUnlock(PthreadMutex* mutex) { return SCE_KERNEL_ERROR_EPERM; } if (m->_type == MutexType::Recursive) { + if (m->_owner.load(std::memory_order_acquire) != std::this_thread::get_id() || m->_count == 0) + return SCE_KERNEL_ERROR_EPERM; if (--m->_count == 0) m->_owner.store(std::thread::id{}, std::memory_order_relaxed); m->_rmtx.unlock(); return SCE_OK; diff --git a/core/libs/prx/libkernel/Pthread/src/Thread.cpp b/core/libs/prx/libkernel/Pthread/src/Thread.cpp index b594ba7a1..aab144818 100644 --- a/core/libs/prx/libkernel/Pthread/src/Thread.cpp +++ b/core/libs/prx/libkernel/Pthread/src/Thread.cpp @@ -47,17 +47,22 @@ static void RunThread(std::unique_ptr args) { FinishThread(self, entry(arg)); } -#ifdef _WIN32 static thread_local PthreadPrivate* currentThread = nullptr; +static thread_local std::unique_ptr adoptedThread; static void ReleaseThread(PthreadPrivate* thread) { + if (thread->_adopted) + return; if (thread->references.fetch_sub(1, std::memory_order_acq_rel) != 1) return; +#ifdef _WIN32 if (!CloseHandle(thread->nativeHandle)) throw std::system_error(GetLastError(), std::system_category(), "Closing guest thread handle"); +#endif delete thread; } +#ifdef _WIN32 struct NativeThreadArgs { std::unique_ptr guest; std::future start; @@ -136,8 +141,19 @@ int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, Pthread if (detached) ReleaseThread(published); #else - p->_thr = std::thread([args = std::move(args), ready = start.get_future()]() mutable { - if (ready.get()) RunThread(std::move(args)); + auto* self = p.get(); + p->_thr = std::thread([self, args = std::move(args), ready = start.get_future()]() mutable { + if (!ready.get()) return; + currentThread = self; + self->threadId = std::this_thread::get_id(); + struct ThreadGuard { + PthreadPrivate* self; + ~ThreadGuard() { + currentThread = nullptr; + ReleaseThread(self); + } + } guard{self}; + RunThread(std::move(args)); }); try { if (detached) p->_thr.detach(); @@ -146,8 +162,11 @@ int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, Pthread p->_thr.join(); throw; } - *thread = p.release(); + auto* published = p.release(); + *thread = published; start.set_value(true); + if (detached) + ReleaseThread(published); #endif return SCE_OK; } @@ -163,9 +182,11 @@ int APS5_VABI scePthreadJoin(Pthread thread, void** retval) { if (retval) *retval = thread->_retval; ReleaseThread(thread); #else + if (thread == currentThread) + throw std::runtime_error("scePthreadJoin: cannot join current thread"); if (thread->_thr.joinable()) thread->_thr.join(); if (retval) *retval = thread->_retval; - delete thread; + ReleaseThread(thread); #endif return SCE_OK; } @@ -178,6 +199,7 @@ int APS5_VABI scePthreadDetach(Pthread thread) { ReleaseThread(thread); #else if (thread->_thr.joinable()) thread->_thr.detach(); + ReleaseThread(thread); #endif return SCE_OK; } @@ -192,17 +214,22 @@ void APS5_VABI scePthreadExit(void* retval) { ReleaseThread(self); _endthreadex(0); #else + if (!currentThread) + throw std::runtime_error("scePthreadExit: current thread is not registered"); + FinishThread(currentThread, retval); pthread_exit(retval); #endif __builtin_unreachable(); } Pthread APS5_VABI scePthreadSelf() { -#ifdef _WIN32 + if (currentThread) return currentThread; + adoptedThread = std::make_unique(); + adoptedThread->_detached = true; + adoptedThread->_adopted = true; + adoptedThread->threadId = std::this_thread::get_id(); + currentThread = adoptedThread.get(); return currentThread; -#else - return nullptr; -#endif } void APS5_VABI scePthreadYield() { diff --git a/core/libs/tests/GuestCondTimedwait.cpp b/core/libs/tests/GuestCondTimedwait.cpp new file mode 100644 index 000000000..52b734e0a --- /dev/null +++ b/core/libs/tests/GuestCondTimedwait.cpp @@ -0,0 +1,52 @@ +#include "SceTypes.hpp" +#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 scePthreadMutexInit(PthreadMutex* mutex, const PthreadMutexattr* attr, const char* name); +int APS5_VABI scePthreadMutexDestroy(PthreadMutex* mutex); +int APS5_VABI scePthreadMutexLock(PthreadMutex* mutex); +int APS5_VABI scePthreadMutexUnlock(PthreadMutex* mutex); +int APS5_VABI scePthreadCondInit(PthreadCond* cond, const PthreadCondattr* attr, const char* name); +int APS5_VABI scePthreadCondDestroy(PthreadCond* cond); +int APS5_VABI scePthreadCondTimedwait(PthreadCond* cond, PthreadMutex* mutex, unsigned int usec); +} + +static constexpr int SCE_OK = 0; +static constexpr int SCE_KERNEL_ERROR_ETIMEDOUT = static_cast(0x8002003C); + +static void Require(bool value) { if (!value) std::abort(); } + +struct Context { + PthreadMutex mutex = nullptr; + std::atomic acquired{false}; +}; + +static void* APS5_VABI Contender(void* arg) { + auto& context = *static_cast(arg); + Require(scePthreadMutexLock(&context.mutex) == SCE_OK); + context.acquired.store(true); + Require(scePthreadMutexUnlock(&context.mutex) == SCE_OK); + return nullptr; +} + +int main() { + Context context; + PthreadCond cond = nullptr; + Require(scePthreadMutexInit(&context.mutex, nullptr, nullptr) == SCE_OK); + Require(scePthreadCondInit(&cond, nullptr, nullptr) == SCE_OK); + + Require(scePthreadMutexLock(&context.mutex) == SCE_OK); + Pthread thread = nullptr; + Require(scePthreadCreate(&thread, nullptr, Contender, &context, nullptr) == SCE_OK); + while (!context.acquired.load()) + Require(scePthreadCondTimedwait(&cond, &context.mutex, 1000) == SCE_KERNEL_ERROR_ETIMEDOUT); + Require(scePthreadMutexUnlock(&context.mutex) == SCE_OK); + Require(scePthreadJoin(thread, nullptr) == SCE_OK); + + Require(scePthreadCondDestroy(&cond) == SCE_OK); + Require(scePthreadMutexDestroy(&context.mutex) == SCE_OK); +} diff --git a/core/libs/tests/GuestThreadSelf.cpp b/core/libs/tests/GuestThreadSelf.cpp new file mode 100644 index 000000000..585745cbd --- /dev/null +++ b/core/libs/tests/GuestThreadSelf.cpp @@ -0,0 +1,75 @@ +#include "SceTypes.hpp" +#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 scePthreadDetach(Pthread thread); +void APS5_VABI scePthreadExit(void* retval); +Pthread APS5_VABI scePthreadSelf(); +int APS5_VABI scePthreadMutexattrInit(PthreadMutexattr* attr); +int APS5_VABI scePthreadMutexattrDestroy(PthreadMutexattr* attr); +int APS5_VABI scePthreadMutexattrSettype(PthreadMutexattr* attr, int type); +int APS5_VABI scePthreadMutexInit(PthreadMutex* mutex, const PthreadMutexattr* attr, const char* name); +int APS5_VABI scePthreadMutexDestroy(PthreadMutex* mutex); +int APS5_VABI scePthreadMutexLock(PthreadMutex* mutex); +int APS5_VABI scePthreadMutexUnlock(PthreadMutex* mutex); +} + +static constexpr int SCE_OK = 0; +static constexpr int SCE_KERNEL_ERROR_EINVAL = 0x80020016; +static constexpr int SCE_KERNEL_ERROR_EPERM = 0x80020001; +static constexpr int MUTEX_TYPE_RECURSIVE = 2; +static constexpr std::intptr_t WorkerRetval = 0x1234; + +static void Require(bool value) { if (!value) std::abort(); } + +struct WorkerContext { + Pthread thread = nullptr; + Pthread selfFromWorker = nullptr; + PthreadMutex* mutex = nullptr; + int unlockResult = 0; +}; + +static void* APS5_VABI Worker(void* arg) { + auto& context = *static_cast(arg); + context.selfFromWorker = scePthreadSelf(); + context.unlockResult = scePthreadMutexUnlock(context.mutex); + scePthreadExit(reinterpret_cast(WorkerRetval)); + return nullptr; +} + +int main() { + const Pthread mainSelf = scePthreadSelf(); + Require(mainSelf != nullptr); + Require(scePthreadSelf() == mainSelf); + Require(scePthreadJoin(mainSelf, nullptr) == SCE_KERNEL_ERROR_EINVAL); + Require(scePthreadDetach(mainSelf) == SCE_KERNEL_ERROR_EINVAL); + + PthreadMutexattr attr = nullptr; + Require(scePthreadMutexattrInit(&attr) == SCE_OK); + Require(scePthreadMutexattrSettype(&attr, MUTEX_TYPE_RECURSIVE) == SCE_OK); + PthreadMutex mutex = nullptr; + Require(scePthreadMutexInit(&mutex, &attr, nullptr) == SCE_OK); + Require(scePthreadMutexattrDestroy(&attr) == SCE_OK); + + Require(scePthreadMutexLock(&mutex) == SCE_OK); + + WorkerContext context; + context.mutex = &mutex; + Require(scePthreadCreate(&context.thread, nullptr, Worker, &context, nullptr) == SCE_OK); + Require(context.thread != nullptr); + Require(context.thread != mainSelf); + + void* result = nullptr; + Require(scePthreadJoin(context.thread, &result) == SCE_OK); + Require(reinterpret_cast(result) == WorkerRetval); + Require(context.selfFromWorker != nullptr); + Require(context.selfFromWorker == context.thread); + Require(context.selfFromWorker != mainSelf); + Require(context.unlockResult == SCE_KERNEL_ERROR_EPERM); + + Require(scePthreadMutexUnlock(&mutex) == SCE_OK); + Require(scePthreadMutexDestroy(&mutex) == SCE_OK); +} From 15b749c2baaa2f4ea4cca6cc0b5e1cb31f8aec67 Mon Sep 17 00:00:00 2001 From: QDarkRex Date: Sun, 27 Sep 2026 12:38:59 +0700 Subject: [PATCH 5/7] fix(kernel): return 64-bit offsets from sceKernelLseek The SCE ABI returns off_t; offsets above INT_MAX threw instead of being returned. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libkernel/File/include/File.hpp | 2 +- core/libs/prx/libkernel/File/src/Open.cpp | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libkernel/File/include/File.hpp b/core/libs/prx/libkernel/File/include/File.hpp index 0037b90dd..cb3f099ff 100644 --- a/core/libs/prx/libkernel/File/include/File.hpp +++ b/core/libs/prx/libkernel/File/include/File.hpp @@ -13,7 +13,7 @@ int APS5_VABI sceKernelOpen(const char* path, int flags, std::uint16_t mode); int APS5_VABI sceKernelClose(int d); std::int64_t APS5_VABI sceKernelRead(int d, void* buf, std::size_t nbytes); std::int64_t APS5_VABI sceKernelWrite(int d, const void* buf, std::size_t nbytes); -int APS5_VABI sceKernelLseek(int d, std::int64_t offset, int whence); +std::int64_t APS5_VABI sceKernelLseek(int d, std::int64_t offset, int whence); int APS5_VABI sceKernelStat(const char* path, FileStat* sb); int APS5_VABI sceKernelUnlink(const char* path); diff --git a/core/libs/prx/libkernel/File/src/Open.cpp b/core/libs/prx/libkernel/File/src/Open.cpp index d1f3a9cbe..d22122583 100644 --- a/core/libs/prx/libkernel/File/src/Open.cpp +++ b/core/libs/prx/libkernel/File/src/Open.cpp @@ -132,7 +132,7 @@ std::int64_t APS5_VABI sceKernelWrite(int d, const void* buf, std::size_t nbytes return static_cast(n); } -int APS5_VABI sceKernelLseek(int d, std::int64_t offset, int whence) { +std::int64_t APS5_VABI sceKernelLseek(int d, std::int64_t offset, int whence) { if (whence < 0 || whence > 2) { throw std::invalid_argument(std::string(__func__) + ": invalid whence=" + std::to_string(whence)); } @@ -140,10 +140,7 @@ int APS5_VABI sceKernelLseek(int d, std::int64_t offset, int whence) { if (result < 0) { throw std::runtime_error(std::string(__func__) + ": lseek failed, fd=" + std::to_string(d) + ", errno=" + std::to_string(errno)); } - if (result > static_cast(std::numeric_limits::max())) { - throw std::overflow_error(std::string(__func__) + ": result " + std::to_string(result) + " overflows int return type"); - } - return static_cast(result); + return result; } int APS5_VABI sceKernelStat(const char* path, FileStat* sb) { From be127fd0f1c58af21b925d023711edec2f3ed46b Mon Sep 17 00:00:00 2001 From: QDarkRex Date: Sun, 27 Sep 2026 12:38:59 +0700 Subject: [PATCH 6/7] feat(kernel): implement sceKernelDeleteSema Waiters are woken with SCE_KERNEL_ERROR_EACCES and the semaphore is freed once they have left. Co-Authored-By: Claude Opus 5.5 --- .../libkernel/Semaphore/include/Semaphore.hpp | 4 ++ .../prx/libkernel/Semaphore/src/Semaphore.cpp | 39 ++++++++++++++----- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/core/libs/prx/libkernel/Semaphore/include/Semaphore.hpp b/core/libs/prx/libkernel/Semaphore/include/Semaphore.hpp index e7c6e49d2..2ec36278e 100644 --- a/core/libs/prx/libkernel/Semaphore/include/Semaphore.hpp +++ b/core/libs/prx/libkernel/Semaphore/include/Semaphore.hpp @@ -12,6 +12,7 @@ constexpr int KERNEL_SEMA_OK = 0; constexpr int KERNEL_SEMA_ERROR_EINVAL = static_cast(0x80020016); +constexpr int KERNEL_SEMA_ERROR_EACCES = static_cast(0x8002000D); constexpr int KERNEL_SEMA_ERROR_EBUSY = static_cast(0x80020010); constexpr int KERNEL_SEMA_ERROR_ETIMEDOUT = static_cast(0x8002003C); @@ -24,11 +25,14 @@ struct KernelSemaPrivate { std::int32_t tokenCount; std::int32_t maxCount; bool isFifo; + bool deleted = false; + std::int32_t waiterCount = 0; }; extern "C" { int APS5_VABI sceKernelCreateSema(KernelSema* sem, const char* name, uint32_t attr, int init, int max, void* opt); +int APS5_VABI sceKernelDeleteSema(KernelSema sem); int APS5_VABI sceKernelPollSema(KernelSema sem, int need); int APS5_VABI sceKernelSignalSema(KernelSema sem, int count); int APS5_VABI sceKernelWaitSema(KernelSema sem, int need, KernelUseconds* time); diff --git a/core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp b/core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp index ac822495f..de7bb4808 100644 --- a/core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp +++ b/core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp @@ -53,14 +53,29 @@ int APS5_VABI sceKernelWaitSema(KernelSema sem, int need, KernelUseconds* time) } std::unique_lock lock(sem->mutex); + ++sem->waiterCount; + struct WaiterGuard { + KernelSemaPrivate* sem; + ~WaiterGuard() { + --sem->waiterCount; + sem->condition.notify_all(); + } + } waiterGuard{sem}; + if (time == nullptr) { - sem->condition.wait(lock, [&] { return sem->tokenCount >= need; }); + sem->condition.wait(lock, [&] { return sem->tokenCount >= need || sem->deleted; }); + if (sem->deleted) { + return KERNEL_SEMA_ERROR_EACCES; + } sem->tokenCount -= need; return KERNEL_SEMA_OK; } auto timeout = std::chrono::microseconds(*time); - bool acquired = sem->condition.wait_for(lock, timeout, [&] { return sem->tokenCount >= need; }); + bool acquired = sem->condition.wait_for(lock, timeout, [&] { return sem->tokenCount >= need || sem->deleted; }); + if (sem->deleted) { + return KERNEL_SEMA_ERROR_EACCES; + } if (!acquired) { return KERNEL_SEMA_ERROR_ETIMEDOUT; } @@ -68,10 +83,6 @@ int APS5_VABI sceKernelWaitSema(KernelSema sem, int need, KernelUseconds* time) return KERNEL_SEMA_OK; } -// --------------------------------------------------------------------------- -// Moved as-is (not yet implemented) from the monolithic libkernel/Export.cpp. -// --------------------------------------------------------------------------- - int APS5_VABI sceKernelCancelSema(KernelSema sem, int count, int* threads) { (void)sem; (void)count; @@ -81,9 +92,19 @@ int APS5_VABI sceKernelCancelSema(KernelSema sem, int count, int* threads) { } int APS5_VABI sceKernelDeleteSema(KernelSema sem) { - (void)sem; - NotImplemented_nid_no_patch(__func__); - return 0; + if (sem == nullptr) { + APS5_INVALID_ARG_EX; + } + + std::unique_lock lock(sem->mutex); + sem->deleted = true; + sem->condition.notify_all(); + while (sem->waiterCount > 0) { + sem->condition.wait(lock); + } + lock.unlock(); + delete sem; + return KERNEL_SEMA_OK; } } From a60256ea4d1a3b25b246b432b32e538bfad6c152 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 07:47:12 +0000 Subject: [PATCH 7/7] fix(kernel): exit POSIX guest threads without forced unwinding On Linux scePthreadExit called pthread_exit, whose forced unwind runs the personality routine of every guest frame. Those resolve to libc.prx's __gxx_personality_v0, which cannot read libgcc's unwind context and aborts, so guest_thread_self crashed on Linux. Record a jump target in the thread start routine and longjmp back to it from scePthreadExit instead. Like _endthreadex on Windows, this skips the guest frames without unwinding them; the start routine still releases the thread normally. Threads not created by scePthreadCreate keep the pthread_exit fallback. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018emyZ4Rk8yoSJvxTFBe4DL --- core/libs/prx/libkernel/Pthread/src/Thread.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libkernel/Pthread/src/Thread.cpp b/core/libs/prx/libkernel/Pthread/src/Thread.cpp index 49378013e..bb6ea5acf 100644 --- a/core/libs/prx/libkernel/Pthread/src/Thread.cpp +++ b/core/libs/prx/libkernel/Pthread/src/Thread.cpp @@ -14,6 +14,7 @@ #include #ifndef _WIN32 +#include #include #endif @@ -43,6 +44,11 @@ static thread_local PthreadPrivate* currentThread = nullptr; static thread_local bool threadFinishing = false; #ifndef _WIN32 static thread_local std::unique_ptr adoptedThread; +// pthread_exit force-unwinds through guest frames, whose personality resolves to +// libc.prx's __gxx_personality_v0; that routine cannot read libgcc's unwind context +// and aborts. scePthreadExit instead jumps back to the thread start routine, which, +// like _endthreadex on Windows, skips the guest frames without unwinding them. +static thread_local std::jmp_buf* threadExitJump = nullptr; #endif void ThreadLifecycle::SetThreadDtors(thread_dtors_func_t callback) { @@ -238,7 +244,12 @@ int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, Pthread ReleaseThread(self); } } guard{self}; - RunThread(std::move(args)); + std::jmp_buf exitJump; + if (setjmp(exitJump) == 0) { + threadExitJump = &exitJump; + RunThread(std::move(args)); + } + threadExitJump = nullptr; }); try { if (detached) p->_thr.detach(); @@ -297,6 +308,8 @@ void APS5_VABI scePthreadExit(void* retval) { ReleaseThread(self); _endthreadex(0); #else + if (threadExitJump) + std::longjmp(*threadExitJump, 1); pthread_exit(retval); #endif throw std::runtime_error("Native thread exit returned");