diff --git a/core/libs/CMakeLists.txt b/core/libs/CMakeLists.txt index b86ddf5c5..68e441814 100644 --- a/core/libs/CMakeLists.txt +++ b/core/libs/CMakeLists.txt @@ -285,6 +285,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/libSceAudioOut/src/AudioOut.cpp b/core/libs/prx/libSceAudioOut/src/AudioOut.cpp index b9ecce49e..16d7901f5 100644 --- a/core/libs/prx/libSceAudioOut/src/AudioOut.cpp +++ b/core/libs/prx/libSceAudioOut/src/AudioOut.cpp @@ -288,6 +288,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"); } 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 0ddf0be89..cd71e7fa0 100644 --- a/core/libs/prx/libkernel/File/src/Open.cpp +++ b/core/libs/prx/libkernel/File/src/Open.cpp @@ -134,7 +134,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)); } @@ -142,10 +142,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) { diff --git a/core/libs/prx/libkernel/Pthread/include/Pthread.hpp b/core/libs/prx/libkernel/Pthread/include/Pthread.hpp index cd3946ffd..7d3508525 100644 --- a/core/libs/prx/libkernel/Pthread/include/Pthread.hpp +++ b/core/libs/prx/libkernel/Pthread/include/Pthread.hpp @@ -69,11 +69,11 @@ 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 affinity{DEFAULT_THREAD_AFFINITY}; @@ -83,10 +83,11 @@ struct PthreadPrivate { 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/Thread.cpp b/core/libs/prx/libkernel/Pthread/src/Thread.cpp index b2a884a47..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 @@ -41,6 +42,14 @@ static std::atomic threadAtexitCount{nullptr}; static std::atomic threadAtexitReport{nullptr}; 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) { if (!callback) @@ -93,15 +102,19 @@ static void RunThread(std::unique_ptr args) { currentThread = nullptr; } -#ifdef _WIN32 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 // The title's job workers ("BPE JobWorkerThread CPU0".."CPU12") spin at full load on one core each. // Pinning them to the efficiency cores of a hybrid CPU (APS5_JOB_AFFINITY=1, with the driver's // worker pinning) measured 0 to -9 % at the video stage, so the default leaves them free; @@ -220,8 +233,23 @@ 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; + self->threadId = std::this_thread::get_id(); + struct ThreadGuard { + PthreadPrivate* self; + ~ThreadGuard() { + currentThread = nullptr; + ReleaseThread(self); + } + } guard{self}; + std::jmp_buf exitJump; + if (setjmp(exitJump) == 0) { + threadExitJump = &exitJump; + RunThread(std::move(args)); + } + threadExitJump = nullptr; }); try { if (detached) p->_thr.detach(); @@ -230,8 +258,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; } @@ -239,9 +270,9 @@ int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, Pthread int APS5_VABI scePthreadJoin(Pthread thread, void** retval) { if (!thread) throw std::runtime_error("scePthreadJoin: null thread"); if (thread->_detached) return SCE_KERNEL_ERROR_EINVAL; -#ifdef _WIN32 if (thread == currentThread) throw std::runtime_error("scePthreadJoin: cannot join current thread"); +#ifdef _WIN32 if (WaitForSingleObject(thread->nativeHandle, INFINITE) != WAIT_OBJECT_0) throw std::system_error(GetLastError(), std::system_category(), "Joining guest thread"); if (retval) *retval = thread->_retval; @@ -249,7 +280,7 @@ int APS5_VABI scePthreadJoin(Pthread thread, void** retval) { #else if (thread->_thr.joinable()) thread->_thr.join(); if (retval) *retval = thread->_retval; - delete thread; + ReleaseThread(thread); #endif return SCE_OK; } @@ -262,6 +293,7 @@ int APS5_VABI scePthreadDetach(Pthread thread) { ReleaseThread(thread); #else if (thread->_thr.joinable()) thread->_thr.detach(); + ReleaseThread(thread); #endif return SCE_OK; } @@ -276,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"); @@ -294,6 +328,14 @@ Pthread APS5_VABI scePthreadSelf() { adopted->references.store(1, std::memory_order_relaxed); currentThread = adopted.release(); } +#else + if (!currentThread) { + adoptedThread = std::make_unique(); + adoptedThread->_detached = true; + adoptedThread->_adopted = true; + adoptedThread->threadId = std::this_thread::get_id(); + currentThread = adoptedThread.get(); + } #endif return currentThread; } diff --git a/core/libs/prx/libkernel/Semaphore/include/Semaphore.hpp b/core/libs/prx/libkernel/Semaphore/include/Semaphore.hpp index 631fe181d..ff29d1779 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 993ccdde2..5597fe2c6 100644 --- a/core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp +++ b/core/libs/prx/libkernel/Semaphore/src/Semaphore.cpp @@ -55,19 +55,34 @@ 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.NotifyAll(); + } + } waiterGuard{sem}; + const auto waitStart = std::chrono::steady_clock::now(); const auto traceWait = [&](bool timedOut) { KernelTraceWait_nid_postfix("sema", __builtin_return_address(0), static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - waitStart).count()), timedOut); }; if (time == nullptr) { - sem->condition.Wait(lock, [&] { return sem->tokenCount >= need; }); + sem->condition.Wait(lock, [&] { return sem->tokenCount >= need || sem->deleted; }); traceWait(false); + if (sem->deleted) { + return KERNEL_SEMA_ERROR_EACCES; + } sem->tokenCount -= need; return KERNEL_SEMA_OK; } - const bool acquired = sem->condition.WaitUntil(lock, TimedWait::DeadlineNanos(*time), [&] { return sem->tokenCount >= need; }); + const bool acquired = sem->condition.WaitUntil(lock, TimedWait::DeadlineNanos(*time), [&] { return sem->tokenCount >= need || sem->deleted; }); traceWait(!acquired); + if (sem->deleted) { + return KERNEL_SEMA_ERROR_EACCES; + } if (!acquired) { return KERNEL_SEMA_ERROR_ETIMEDOUT; } @@ -75,10 +90,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; @@ -88,9 +99,17 @@ 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.NotifyAll(); + sem->condition.Wait(lock, [&] { return sem->waiterCount == 0; }); + lock.unlock(); + delete sem; + return KERNEL_SEMA_OK; } } 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); +} diff --git a/core/relinker/CMakeLists.txt b/core/relinker/CMakeLists.txt index 225ab6a3f..8328500ae 100644 --- a/core/relinker/CMakeLists.txt +++ b/core/relinker/CMakeLists.txt @@ -155,6 +155,8 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_tls_function_coverage.py $) add_test(NAME linux_load_alignment COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_linux_load_alignment.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 Python relinker tests") endif() diff --git a/core/relinker/cli/include/Cli.hpp b/core/relinker/cli/include/Cli.hpp index 63c1bd38b..7d5dc0db3 100644 --- a/core/relinker/cli/include/Cli.hpp +++ b/core/relinker/cli/include/Cli.hpp @@ -15,6 +15,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/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; } } diff --git a/core/relinker/cli/src/CliArgs.cpp b/core/relinker/cli/src/CliArgs.cpp index 7629f6802..2514a24c7 100644 --- a/core/relinker/cli/src/CliArgs.cpp +++ b/core/relinker/cli/src/CliArgs.cpp @@ -37,6 +37,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()) { @@ -51,9 +53,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] [--skip-sce-module] [--to-intel] [unused-filter=0|1|2] [--registry] [--rpath ] [--lazy-binding] [--autorun] \n" + "Usage: relinker [--windows] [--windows-diagnostics] [--windows-gui] [--skip-syscall-check] [--skip-sce-module] [--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 2552cba55..ffb77f948 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, const std::vector& trampolines) 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 3097d3a55..f7e1cf110 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp @@ -40,6 +40,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, const std::vector& trampolines) { WindowsLoadImage image(sourceElf, originalHeaders); if (originalPltGotVaddr != 0) @@ -98,7 +101,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 7904d6b6b..f36f383c3 100644 --- a/core/relinker/main.cpp +++ b/core/relinker/main.cpp @@ -90,7 +90,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("