Repository navigation
fix(kernel): scePthreadSemTimedwait returns ETIMEDOUT when its semaphore is destroyed under the wait - #19657
Conversation
…er the wait Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ore destroyed under the wait Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ed wait Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Probe source (built with ps5-payload-sdk v0.45; probe.c#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <ps5/kernel.h> /* only for kernel_get_fw_version() */
#ifndef PROBE_NAME
#define PROBE_NAME "unnamed"
#endif
#ifndef PROBE_BUILD
#define PROBE_BUILD "unbuilt"
#endif
/* Self limit: on timeout the runner can only close the connection, not end the process on the console.
The probe ends itself after at most PROBE_MAX_S seconds (the build script sets timeout - 10 s). */
#ifndef PROBE_MAX_S
#define PROBE_MAX_S 50
#endif
static void probe_alarm(int sig) {
static const char msg[] = "TIMEOUT\tprobe self limit\n";
(void)sig;
(void)!write(1, msg, sizeof msg - 1);
_exit(124);
}
static int cases = 0;
static void probe_header(void) {
char utc[32];
time_t now = time(0);
struct tm tmv;
gmtime_r(&now, &tmv);
strftime(utc, sizeof utc, "%Y-%m-%dT%H:%M:%SZ", &tmv);
printf("PROBE\t%s\tfw=0x%08x\tbuild=%s\tpid=%d\tutc=%s\n", PROBE_NAME, kernel_get_fw_version(), PROBE_BUILD,
getpid(), utc);
fflush(stdout);
}
/* CASE: id, description of the call, return value as long, errno (0 if not set), extra (hex/bytes). */
static void probe_case(const char* id, const char* call, long ret, int err, const char* extra) {
printf("CASE\t%s\t%s\t%ld\t%d\t%s\n", id, call, ret, err, extra ? extra : "-");
fflush(stdout);
cases++;
}
static void probe_end(void) {
printf("END\t%d\n", cases);
fflush(stdout);
}
/* Probe R1: sceKernelCancelSema and scePthreadSemDestroy on firmware 11.60 ( libkernel.md:106 ESRCH for a null
handle 'unverified on PS5', libkernel.md:107 destroy with a waiting thread). Prototypes follow the repo implementation:
int sceKernelCreateSema(void** sem, const char* name, uint32 attr, int init, int max, void* opt), int sceKernelCancelSema(void* sem,
int count, int* threads), int sceKernelPollSema(void* sem, int need), int sceKernelWaitSema(void* sem, int need, uint32* usec),
int sceKernelDeleteSema(void* sem), int scePthreadSemInit(void** sem, int flag, unsigned value, const char* name),
int scePthreadSemTimedwait(void** sem, uint32 usec), scePthreadSemPost, scePthreadSemDestroy(void** sem). Waits have a 2 s timeout.
The invalid handle calls (null, 0x12345) are last and guarded against SIGSEGV/SIGBUS; a fault shows as signal=N. */
#include <dlfcn.h>
#include <setjmp.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/types.h>
static sigjmp_buf guard_env;
static volatile int guard_sig = 0;
static void guard_handler(int s) {
guard_sig = s;
siglongjmp(guard_env, 1);
}
static void guard_arm(void) {
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = guard_handler;
sigaction(SIGSEGV, &sa, 0);
sigaction(SIGBUS, &sa, 0);
sigaction(SIGABRT, &sa, 0);
}
#define CALL(rvar, evar, expr) do { errno = 0; guard_sig = 0; rvar = -1; if(sigsetjmp(guard_env, 1) == 0) rvar = (expr); evar = errno; } while(0)
typedef int (*create_fn)(void**, const char*, uint32_t, int, int, void*);
typedef int (*cancel_fn)(void*, int, int*);
typedef int (*poll_fn)(void*, int);
typedef int (*wait_fn)(void*, int, uint32_t*);
typedef int (*del_fn)(void*);
typedef int (*pinit_fn)(void**, int, unsigned, const char*);
typedef int (*ptimed_fn)(void**, uint32_t);
typedef int (*ppost_fn)(void**);
typedef int (*pdel_fn)(void**);
static create_fn mk;
static cancel_fn cancel;
static poll_fn poll_s;
static wait_fn wait_s;
static del_fn del;
static pinit_fn pinit;
static ptimed_fn ptimed;
static ppost_fn ppost;
static pdel_fn pdestroy;
static void rcline(const char* id, const char* what, int r, int e, const char* extra) {
char ex[96];
snprintf(ex, sizeof ex, "rc_hex=0x%x signal=%d %s", (unsigned)r, (int)guard_sig, extra);
probe_case(id, what, guard_sig ? -1 : r, e, ex);
}
static void* fresh(int init, int max) {
void* s = 0;
int r = mk(&s, "r1sema", 1, init, max, 0);
if(r != 0) return 0;
return s;
}
static void cancel_case(const char* id, int count, int init, int max) {
void* s = fresh(init, max);
char what[64];
snprintf(what, sizeof what, "CancelSema(sem init=%d max=%d, count=%d, &n)", init, max, count);
if(!s) { probe_case(id, what, -1, 0, "create failed"); return; }
int n = -7, r, e;
CALL(r, e, cancel(s, count, &n));
char ex[40];
snprintf(ex, sizeof ex, "n=%d", n);
rcline(id, what, r, e, ex);
int p1, e1;
CALL(p1, e1, poll_s(s, 1));
rcline(id, "PollSema(1) after cancel", p1, e1, "-");
int p5, e5;
CALL(p5, e5, poll_s(s, 5));
rcline(id, "PollSema(5) after that", p5, e5, "-");
del(s);
}
static void* waiter_sema(void* arg) {
uint32_t usec = 2000000;
int r = wait_s(arg, 1, &usec);
char ex[40];
snprintf(ex, sizeof ex, "usec_left=%u", (unsigned)usec);
rcline("a.4", "waiter WaitSema(1, 2 s) returned", r, errno, ex);
return 0;
}
static void* waiter_posix(void* arg) {
int r = ptimed((void**)arg, 2000000);
rcline("c.2", "waiter SemTimedwait(2 s) returned", r, errno, "-");
return 0;
}
int main(void) {
signal(SIGALRM, probe_alarm);
alarm(PROBE_MAX_S);
probe_header();
guard_arm();
mk = (create_fn)dlsym(RTLD_DEFAULT, "sceKernelCreateSema");
cancel = (cancel_fn)dlsym(RTLD_DEFAULT, "sceKernelCancelSema");
poll_s = (poll_fn)dlsym(RTLD_DEFAULT, "sceKernelPollSema");
wait_s = (wait_fn)dlsym(RTLD_DEFAULT, "sceKernelWaitSema");
del = (del_fn)dlsym(RTLD_DEFAULT, "sceKernelDeleteSema");
pinit = (pinit_fn)dlsym(RTLD_DEFAULT, "scePthreadSemInit");
ptimed = (ptimed_fn)dlsym(RTLD_DEFAULT, "scePthreadSemTimedwait");
ppost = (ppost_fn)dlsym(RTLD_DEFAULT, "scePthreadSemPost");
pdestroy = (pdel_fn)dlsym(RTLD_DEFAULT, "scePthreadSemDestroy");
char line[16];
snprintf(line, sizeof line, "%d%d%d%d%d%d%d%d%d", !!mk, !!cancel, !!poll_s, !!wait_s, !!del, !!pinit, !!ptimed, !!ppost, !!pdestroy);
probe_case("0", "dlsym exported Create Cancel Poll Wait Delete SemInit SemTimedwait SemPost SemDestroy (1 yes, 0 no)", 0, 0, line);
if(mk && cancel && poll_s && del) {
cancel_case("a.1", 0, 0, 10);
cancel_case("a.2", 5, 0, 10);
cancel_case("a.3", -1, 2, 10);
cancel_case("a.3b", 11, 0, 10);
}
if(mk && cancel && wait_s && del) {
void* s = fresh(0, 10);
pthread_t th;
if(s && pthread_create(&th, 0, waiter_sema, s) == 0) {
usleep(300000);
int n = -7, r, e;
CALL(r, e, cancel(s, 0, &n));
char ex[24];
snprintf(ex, sizeof ex, "n=%d", n);
rcline("a.4", "CancelSema(count 0, &n) with one waiting thread", r, e, ex);
pthread_join(th, 0);
del(s);
} else {
probe_case("a.4", "waiter thread or sema create", -1, errno, "failed");
}
}
if(pinit && pdestroy && ptimed) {
void* ps = 0;
int r, e;
CALL(r, e, pinit(&ps, 0, 0, "r1psem"));
rcline("c.1", "SemInit(&sem, 0, 0)", r, e, "-");
pthread_t th;
if(r == 0 && pthread_create(&th, 0, waiter_posix, &ps) == 0) {
usleep(300000);
CALL(r, e, pdestroy(&ps));
rcline("c.3", "SemDestroy while one thread waits", r, e, "-");
pthread_join(th, 0);
if(ppost) {
CALL(r, e, ppost(&ps));
rcline("c.4", "SemPost after destroy", r, e, "-");
}
CALL(r, e, pdestroy(&ps));
rcline("c.5", "SemDestroy again", r, e, "-");
} else {
probe_case("c.2", "SemInit failed or thread create failed", r, e, "-");
}
}
if(cancel) {
int n = -7, r, e;
CALL(r, e, cancel(0, 0, &n));
rcline("b.1", "CancelSema(NULL, 0, &n)", r, e, "-");
CALL(r, e, cancel((void*)0x12345, 0, &n));
rcline("b.2", "CancelSema(0x12345, 0, &n)", r, e, "-");
}
probe_end();
return 0;
}stdoutAI-assisted (Claude Code). |
|
Windows check of head Setup: Windows 11 Enterprise 22621, WinLibs GCC 15.2 UCRT, Release. The hosted Windows check does not run these tests on pull requests.
AI-assisted: yes. |
|
Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.
|
PrivacyOnion
left a comment
There was a problem hiding this comment.
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 3671a71602:
- Conventions:
tools/check_conventions.pypassed;git diff --checkclean. - Build:
guest_pthread_sem_testsbuilt cleanly. - CTest (
guest_pthread_sem):1/1 Test #4672: guest_pthread_sem ................ Passed 0.24 sec 100% tests passed, 0 tests failed out of 1 - Negative control: with
core/libs/prx/libkernel/Pthread/src/Sem.cppreverted tomainand the new tests kept, the suite fails:Restoring the change makes it pass again.1/1 Test #4672: guest_pthread_sem ................Subprocess aborted***Exception: 0.84 sec 0% tests passed, 1 tests failed out of 1 - Code reading:
- Verified in core/libs/prx/libkernel/Pthread/src/Sem.cpp that scePthreadSemTimedwait returns sceTimedOut (0x8002003c / SCE_KERNEL_ERROR_ETIMEDOUT) when current->_destroyed is true upon waking from ThreadCancel::WaitUntil, correctly implementing measured PS5 hardware behavior.
- Verified waiter tracking and cancellation cleanup in core/libs/prx/libkernel/Pthread/src/Sem.cpp: finishSemaphoreWait(current, cleanupContext, cleanupMark) is invoked before returning sceTimedOut, ensuring current->_waiters is decremented and ThreadCancel::CleanupRestore restores the cleanup mark.
- Verified concurrency and object lifetime management across scePthreadSemDestroy and scePthreadSemTimedwait: owner->_mutex is held while evaluating current->_destroyed, and PthreadSemPrivate lifetime is preserved by std::shared_ptr in SemaphoreWaitCleanupContext despite erase from semRegistry.
- Verified that the added unit test in core/libs/tests/GuestPthreadSem.cpp directly exercises the change by executing a 2 s scePthreadSemTimedwait, destroying the semaphore after 50 ms via scePthreadSemDestroy, joining the waiter thread, and asserting timedResult == SCE_KERNEL_ERROR_ETIMEDOUT.
- Verified full compliance with AGENTS.md rules across the changeset: no forbidden comments were added in code, docs/dev/debt/libkernel.md accurately documents the hardware measurement and unmeasured boundaries, and no unauthorized files were introduced.
- Minor: please drop the
Generated withfooter from the description; the AI-assisted checkbox can stay.
Looks Good To Me
The union merge driver of the debt files kept the scePthreadSemDestroy and the scePthreadAttr setters and getters entries twice, main's text next to an older one. The branch's measured SemDestroy text and main's Attr text remain; the other two are dropped. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Merged AI-assisted (Claude Code). |
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — no blocking findings
Nothing blocks this change; the test’s startup signal does not guarantee the waiter has entered the timed wait before the destroy call.
What I ran
Reviewed head 67479ab3eb10e97daef9850a127a8f93e7226384 against the prepared diff and read all three changed files through the pinned repository reader. No tests or builds were run.
Results
| Check | Result | Note |
|---|---|---|
| Changed source review | passed | All three changed files read |
| Build and tests | not run | No commands run |
| Negative control | not run | No test modified to verify failure |
Findings
Blocking
None.
Non-blocking
- The new timed-wait test sets
timedWaitingimmediately before callingscePthreadSemTimedwait. The main thread waits for that flag, then sleeps 50 ms and destroys the semaphore. If the waiter is descheduled after setting the flag and does not enter the timed wait until after the destroy, the test can pass without exercising destruction during a wait. Consider adding a synchronization point that confirms the waiter has registered as a waiter before destroying the semaphore. Changed lines:core/libs/tests/GuestPthreadSem.cpp:174-184.
Sources
- Semaphore timed-wait implementation at the reviewed head
- Timed-wait regression test at the reviewed head
- Semaphore technical-debt entry at the reviewed head
Not verified
No build or tests were run. The PS5 measurements, title-process behavior, other firmware, and platforms described in the PR were author-reported and not independently verified. All files listed as reviewed in manifest.json were read; files.json was not provided in the prepared review artifacts.
To get this to a good state
Nothing is required. Optional: make the timed-wait test synchronize on confirmed waiter registration so it reliably covers destruction during the wait.
|
Tested head Setup: Windows 11 Pro 10.0.26200, Ryzen 7 9800X3D, WinLibs GCC 15.2.0 r7, Release,
Whole batch: the full This is one combined tree, not a run of this PR alone. AI-assisted: yes (Claude Code) |
What
scePthreadSemDestroyreturns 0 on a PS5 (firmware 11.60, payload process) while a thread waits inscePthreadSemTimedwaitwith a 2 s timeout, and that thread then getsETIMEDOUT(0x8002003c) (cases c.3 and c.2, lines 18 and 19 of the raw output). Here the waiting thread gotEINVAL. AscePthreadSemPostto the destroyed semaphore and a secondscePthreadSemDestroyreturnEINVAL(cases c.4 and c.5, lines 20 and 21), as here. This returnsETIMEDOUTfromscePthreadSemTimedwaiton a semaphore that was destroyed under the wait. The test pins it (a 2 s timed wait, a destroy after 50 ms, the resultETIMEDOUT), and the entry forscePthreadSemDestroyindocs/dev/debt/libkernel.mdstates the measurement and what is not measured.Not measured: when the console wakes the waiting thread after the destroy (here at once, and the probe did not record the time), and what an untimed wait on a destroyed semaphore returns (it still returns
EINVALhere). Only the return value of the waiting thread was read. 1 of the titles checked, PPSA24423, callsscePthreadSemTimedwaitand compares the result withETIMEDOUTas the not-an-error case, so the changed result is the one it tests for; the same title callsscePthreadSemDestroyat 2 sites without checking the result, 3 titles callsem_destroyand test only for zero, and 2 other titles callsem_timedwaitand only repeat onEINTR. This is a read of the call sites, not a run. A title process was not measured.Tested
Measured on a PS5 with firmware 11.60 (
kernel_get_fw_version0x11600005), from a homebrew payload process (ps5-payload-sdk v0.45, elfldr), on 2026-11-13 at 13:27 UTC. A title process may differ. The cases are c.2 to c.5, lines 18 to 21 of the raw output in the first comment; the probe also ransceKernelCancelSemaand poll cases that this pull request does not use.mainbeforescePthreadSemDestroywhile a thread waitsscePthreadSemTimedwait(2 s)ETIMEDOUT(line 19)EINVALETIMEDOUTscePthreadSemPostafter the destroy, a second destroyEINVAL(lines 20 and 21)EINVALEINVAL, unchangedscePthreadSemWaiton a semaphore destroyed under itEINVALEINVAL, unchangedOn
main667dbde5131, Linux (WSL, Release), built for the targetguest_pthread_semwithninjareturning 0 for each commit: with only the test commitguest_pthread_semaborts in 1 run, and with the fix and with the documentation commit it passes in 3 of 3 runs each.tools/check_conventions.pypasses with no error and no warning on each of the three commits (the changed entry is 658 characters, up from 337). The probe source and its raw output are in the first comment. Not tested: Windows, macOS, the CI runner, a title process, any other firmware, and the cases listed above as not measured.Overlap: the 96 other open pull requests that change
Pthread/src/Sem.cpp,GuestPthreadSem.cppordocs/dev/debt/libkernel.md(found by reading the changed files of all 1519 open pull requests at about 17:57 UTC) were merged on 2026-11-13 at about 18:05 UTC againstmainb4a82720a8(the branch is based on667dbde513); the branch merges into it without a conflict. 30 of them already conflict withmainwithout this change and still conflict with it; 66 merge cleanly with and without it. None conflicts only with this change. #10558 (sceKernelCancelSemaand the other kernel semaphore calls with a handle that is not live) sharesdocs/dev/debt/libkernel.mdwith this change but edits other entries and other files (Semaphore.cpp), and merges with it without a conflict; this change touches the POSIX semaphore callscePthreadSemTimedwaitinPthread/src/Sem.cpp, which #10558 does not change.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)AI-assisted (Claude Code).
🤖 Generated with Claude Code