mirror of
https://github.com/boykopovar/AnyPS5.git
synced 2026-10-10 01:28:44 +02:00
Merge pull request #25 from QDarkRex/fix/audit-2026-09
fix(kernel,audioout,relinker): thread/mutex correctness fixes and --windows-gui ### libkernel (threads, mutexes, condition variables) - **Deadlock in `scePthreadCondTimedwait` (normal/error-check mutexes):** `_owner` was not restored after the wait. If another thread locked and unlocked the mutex during the wait, the waiter woke up owning the mutex while `_owner` was empty. Its next `scePthreadMutexUnlock` returned `EPERM`, leaving the mutex locked forever (`lock → timedwait → unlock` pattern). - **Wrong timeout code:** `SCE_KERNEL_ERROR_ETIMEDOUT` in `Cond.cpp` was `0x80020062`; it is `0x8002003C` (FreeBSD `ETIMEDOUT` = 60, matching `Semaphore.hpp`). - **`scePthreadSelf()`** returned `nullptr` on Linux, and on both platforms for threads not created by `scePthreadCreate` (including the main thread). Such threads now get a lazily adopted, non-joinable handle (`scePthreadJoin`/`Detach` on it return `EINVAL`). - **Linux `scePthreadExit`** skipped `FinishThread`, so `scePthreadJoin` got a garbage return value. Cleanup now runs from an RAII guard, so it survives glibc forced unwinding. - **Linux detached threads** were never freed. They now use the same reference count as on Windows. - **Recursive mutex unlock** by a non-owner, or with a zero count, was UB (`std::recursive_timed_mutex::unlock`). It now returns `SCE_KERNEL_ERROR_EPERM`, and `_owner`/`_count` are also saved and restored around a recursive cond wait. - **`sceKernelLseek`** returned `int` instead of `off_t`; offsets above `INT_MAX` threw. - **`sceKernelDeleteSema`** implemented: waiters are woken with `SCE_KERNEL_ERROR_EACCES` and the object is freed once they leave. - `sceAudioOutOpen` accepted `freq == 0` / `len == 0`; the frequency was later used as a divisor. It now returns `SCE_AUDIO_OUT_ERROR_INVALID_SAMPLE_FREQ` / `INVALID_SIZE`.
This commit is contained in:
@@ -285,6 +285,26 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(guest_once PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
|
||||
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:$<TARGET_FILE_DIR:libkernel>")
|
||||
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:$<TARGET_FILE_DIR:libkernel>")
|
||||
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)
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ std::int64_t APS5_VABI sceKernelWrite(int d, const void* buf, std::size_t nbytes
|
||||
return static_cast<std::int64_t>(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::int64_t>(std::numeric_limits<int>::max())) {
|
||||
throw std::overflow_error(std::string(__func__) + ": result " + std::to_string(result) + " overflows int return type");
|
||||
}
|
||||
return static_cast<int>(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
int APS5_VABI sceKernelStat(const char* path, FileStat* sb) {
|
||||
|
||||
@@ -69,11 +69,11 @@ struct PthreadAttrPrivate {
|
||||
struct PthreadPrivate {
|
||||
#ifdef _WIN32
|
||||
void* nativeHandle = nullptr;
|
||||
std::thread::id threadId;
|
||||
std::atomic<unsigned> references{2};
|
||||
#else
|
||||
std::thread _thr;
|
||||
#endif
|
||||
std::thread::id threadId;
|
||||
std::atomic<unsigned> references{2};
|
||||
void* stackAddress = nullptr;
|
||||
std::size_t stackSize = 0;
|
||||
std::atomic<KernelCpumask> affinity{DEFAULT_THREAD_AFFINITY};
|
||||
@@ -83,10 +83,11 @@ struct PthreadPrivate {
|
||||
std::atomic<bool> _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
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <system_error>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <csetjmp>
|
||||
#include <pthread.h>
|
||||
#endif
|
||||
|
||||
@@ -41,6 +42,14 @@ static std::atomic<get_thread_atexit_count_func_t> threadAtexitCount{nullptr};
|
||||
static std::atomic<thread_atexit_report_func_t> threadAtexitReport{nullptr};
|
||||
static thread_local PthreadPrivate* currentThread = nullptr;
|
||||
static thread_local bool threadFinishing = false;
|
||||
#ifndef _WIN32
|
||||
static thread_local std::unique_ptr<PthreadPrivate> 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<ThreadArgs> 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<PthreadPrivate>();
|
||||
adoptedThread->_detached = true;
|
||||
adoptedThread->_adopted = true;
|
||||
adoptedThread->threadId = std::this_thread::get_id();
|
||||
currentThread = adoptedThread.get();
|
||||
}
|
||||
#endif
|
||||
return currentThread;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
constexpr int KERNEL_SEMA_OK = 0;
|
||||
constexpr int KERNEL_SEMA_ERROR_EINVAL = static_cast<int>(0x80020016);
|
||||
constexpr int KERNEL_SEMA_ERROR_EACCES = static_cast<int>(0x8002000D);
|
||||
constexpr int KERNEL_SEMA_ERROR_EBUSY = static_cast<int>(0x80020010);
|
||||
constexpr int KERNEL_SEMA_ERROR_ETIMEDOUT = static_cast<int>(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);
|
||||
|
||||
@@ -55,19 +55,34 @@ int APS5_VABI sceKernelWaitSema(KernelSema sem, int need, KernelUseconds* time)
|
||||
}
|
||||
|
||||
std::unique_lock<std::mutex> 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::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(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<std::mutex> 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#include "SceTypes.hpp"
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
|
||||
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<int>(0x8002003C);
|
||||
|
||||
static void Require(bool value) { if (!value) std::abort(); }
|
||||
|
||||
struct Context {
|
||||
PthreadMutex mutex = nullptr;
|
||||
std::atomic<bool> acquired{false};
|
||||
};
|
||||
|
||||
static void* APS5_VABI Contender(void* arg) {
|
||||
auto& context = *static_cast<Context*>(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);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#include "SceTypes.hpp"
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
|
||||
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<WorkerContext*>(arg);
|
||||
context.selfFromWorker = scePthreadSelf();
|
||||
context.unlockResult = scePthreadMutexUnlock(context.mutex);
|
||||
scePthreadExit(reinterpret_cast<void*>(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<std::intptr_t>(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);
|
||||
}
|
||||
@@ -155,6 +155,8 @@ if(BUILD_TESTING)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_tls_function_coverage.py $<TARGET_FILE:relinker>)
|
||||
add_test(NAME linux_load_alignment COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_linux_load_alignment.py $<TARGET_FILE:relinker>)
|
||||
add_test(NAME windows_gui COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_windows_gui.py $<TARGET_FILE:relinker>)
|
||||
else()
|
||||
message(STATUS "Python3 interpreter not found; skipping Python relinker tests")
|
||||
endif()
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<std::streamsize>::max(), '\n');
|
||||
std::cin.get();
|
||||
|
||||
return rawCode;
|
||||
return exitCode;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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 <path>] [--lazy-binding] [--autorun] <input.elf> <output.elf>\n"
|
||||
"Usage: relinker [--windows] [--windows-diagnostics] [--windows-gui] [--skip-syscall-check] [--skip-sce-module] [--to-intel] [unused-filter=0|1|2] [--registry] [--rpath <path>] [--lazy-binding] [--autorun] <input.elf> <output.elf>\n"
|
||||
"Example: relinker input.elf output.elf"
|
||||
);
|
||||
|
||||
|
||||
@@ -7,7 +7,12 @@ namespace Elfpatcher::Windows {
|
||||
|
||||
class WindowsPePatcher : public IElfPatcher {
|
||||
public:
|
||||
explicit WindowsPePatcher(bool windowsGui = false);
|
||||
|
||||
std::vector<std::uint8_t> Patch(const std::vector<std::uint8_t>& sourceElf, const std::vector<Domain::ProgramHeader>& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, std::uint64_t originalPltGotVaddr, const std::string& runPath, bool lazyBinding, bool dependencyDiagnostics, const std::vector<Codegen::TrampolineSite>& trampolines) override;
|
||||
|
||||
private:
|
||||
bool _windowsGui;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace Elfpatcher::Windows {
|
||||
|
||||
class WindowsPeWriter {
|
||||
public:
|
||||
std::vector<std::uint8_t> Write(const std::vector<PeSection>& sections, std::uint32_t entryRva, const std::array<PeDirectory, 16>& directories) const;
|
||||
std::vector<std::uint8_t> Write(const std::vector<PeSection>& sections, std::uint32_t entryRva, const std::array<PeDirectory, 16>& directories, bool windowsGui = false) const;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -40,6 +40,9 @@ void writeGotStub(std::vector<PeSection>& sections, const std::uint32_t targetRv
|
||||
|
||||
}
|
||||
|
||||
WindowsPePatcher::WindowsPePatcher(const bool windowsGui) : _windowsGui(windowsGui) {
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> WindowsPePatcher::Patch(const std::vector<std::uint8_t>& sourceElf, const std::vector<Domain::ProgramHeader>& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, const std::uint64_t originalPltGotVaddr, const std::string& runPath, const bool lazyBinding, const bool dependencyDiagnostics, const std::vector<Codegen::TrampolineSite>& trampolines) {
|
||||
WindowsLoadImage image(sourceElf, originalHeaders);
|
||||
if (originalPltGotVaddr != 0)
|
||||
@@ -98,7 +101,7 @@ std::vector<std::uint8_t> WindowsPePatcher::Patch(const std::vector<std::uint8_t
|
||||
sections.push_back(std::move(entry.Code));
|
||||
for (const auto& lazyStub : entry.LazyStubs)
|
||||
writeGotStub(sections, lazyStub.TargetRva, lazyStub.StubRva);
|
||||
return WindowsPeWriter().Write(sections, entryRva, directories);
|
||||
return WindowsPeWriter().Write(sections, entryRva, directories, _windowsGui);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
namespace Elfpatcher::Windows {
|
||||
|
||||
std::vector<std::uint8_t> WindowsPeWriter::Write(const std::vector<PeSection>& sections, const std::uint32_t entryRva, const std::array<PeDirectory, 16>& directories) const {
|
||||
std::vector<std::uint8_t> WindowsPeWriter::Write(const std::vector<PeSection>& sections, const std::uint32_t entryRva, const std::array<PeDirectory, 16>& 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<std::uint8_t> WindowsPeWriter::Write(const std::vector<PeSection>& 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);
|
||||
|
||||
@@ -90,7 +90,7 @@ int main(const int argc, char* argv[]) {
|
||||
|
||||
std::shared_ptr<Elfpatcher::IElfPatcher> patcher;
|
||||
if (args.toWindows) {
|
||||
patcher = std::make_shared<Elfpatcher::Windows::WindowsPePatcher>();
|
||||
patcher = std::make_shared<Elfpatcher::Windows::WindowsPePatcher>(args.windowsGui);
|
||||
} else {
|
||||
patcher = std::make_shared<Elfpatcher::Linux::LinuxElfPatcher>(
|
||||
std::make_shared<Elfpatcher::EntryStubBuilder>(),
|
||||
|
||||
@@ -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("<I", pe, 0x3c)[0]
|
||||
return struct.unpack_from("<H", pe, pe_offset + 24 + 68)[0]
|
||||
|
||||
|
||||
def main():
|
||||
relinker = Path(sys.argv[1]).resolve()
|
||||
with tempfile.TemporaryDirectory(prefix="anyps5-gui-") as directory:
|
||||
work = Path(directory)
|
||||
source = work / "input.elf"
|
||||
source.write_bytes(fixture())
|
||||
|
||||
cui_output = work / "cui.exe"
|
||||
result = subprocess.run([str(relinker), "--windows", str(source), str(cui_output)],
|
||||
capture_output=True, text=True, timeout=20)
|
||||
assert result.returncode == 0, (result.stdout, result.stderr)
|
||||
assert subsystem(cui_output.read_bytes()) == 3, "expected IMAGE_SUBSYSTEM_WINDOWS_CUI by default"
|
||||
|
||||
gui_output = work / "gui.exe"
|
||||
result = subprocess.run([str(relinker), "--windows", "--windows-gui", str(source), str(gui_output)],
|
||||
capture_output=True, text=True, timeout=20)
|
||||
assert result.returncode == 0, (result.stdout, result.stderr)
|
||||
assert subsystem(gui_output.read_bytes()) == 2, "expected IMAGE_SUBSYSTEM_WINDOWS_GUI with --windows-gui"
|
||||
|
||||
bad_output = work / "bad.exe"
|
||||
result = subprocess.run([str(relinker), "--windows-gui", str(source), str(bad_output)],
|
||||
capture_output=True, text=True, timeout=20)
|
||||
assert result.returncode != 0 and not bad_output.exists(), result
|
||||
print("Windows GUI subsystem integration tests passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user