Repository navigation
fix(libc): make _Mtx_timedlock of a plain mutex the caller owns wait for the deadline and time out - #19945
Conversation
… wait for the deadline and time out On a PS5 payload process (firmware 11.60, libSceLibcInternal through dlopen) a thread that already holds a plain mutex and calls _Mtx_timedlock with a deadline 100 ms ahead waits about 100 ms and returns 2 (timed out). AnyPS5 returned 3 (busy) at once. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…for the deadline and time out The console waits until the deadline and returns 2 for a thread that already holds a plain mutex; AnyPS5 returned 3 (busy) at once. Sleep until the deadline and return the timeout, as for a mutex another thread holds. Recursive mutexes still count up. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ex the caller owns 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: _Mtx_timedlock on firmware 11.60 (libc.md). Taken from libSceLibcInternal.sprx (dlopen); prototypes
int _Mtx_init(void**, int), int _Mtx_lock/_Mtx_unlock(void**), int _Mtx_timedlock(void**, const xtime*), void _Mtx_destroy(void**), xtime = int64
sec, int64 nsec (absolute CLOCK_REALTIME, as the sleep probe showed). Group a: plain mutex held by the main thread, a second thread asks with
CLOCK_REALTIME + 100 ms; b: a time in the past; c: free mutex, then the same thread asks again (plain, 100 ms); d: nsec 1e9 and negative
seconds (last, one call each). All waits are 200 ms or less, apart from d, which the 50 s alarm limits. Calls inside the second thread are not
guarded. */
#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 volatile int guard_active = 0;
static volatile int guard_hits = 0;
static void guard_handler(int s) {
static const char msg[] = "FAULT\tprobe guard: fault outside a guarded call or too many faults\n";
if(!guard_active || ++guard_hits > 8) {
(void)!write(1, msg, sizeof msg - 1);
_exit(125);
}
guard_sig = s;
guard_active = 0;
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) { guard_active = 1; rvar = (expr); } guard_active = 0; evar = errno; } while(0)
#include <time.h>
typedef struct { int64_t sec; int64_t nsec; } xt;
typedef int (*mi_fn)(void**, int);
typedef int (*mo_fn)(void**);
typedef int (*tl_fn)(void**, const xt*);
typedef void (*md_fn)(void**);
static mi_fn mi;
static mo_fn mu;
static tl_fn tl;
static void* g_m;
static xt g_x;
static volatile int t_rc = -999;
static volatile long long t_ms = -1;
static long long now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (long long)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
static xt rt_plus(long long ns) {
struct timespec rt;
clock_gettime(CLOCK_REALTIME, &rt);
long long n = rt.tv_nsec + ns;
xt x = {rt.tv_sec + n / 1000000000LL, n % 1000000000LL};
if(x.nsec < 0) { x.sec--; x.nsec += 1000000000LL; }
return x;
}
static void* worker(void* a) {
(void)a;
long long t0 = now_ns();
t_rc = tl(&g_m, &g_x);
t_ms = (now_ns() - t0) / 1000000;
if(t_rc == 0) mu(&g_m);
return 0;
}
static void in_thread(const char* id, const char* what, xt x) {
g_x = x;
t_rc = -999;
t_ms = -1;
pthread_t th;
if(pthread_create(&th, 0, worker, 0) != 0) { probe_case(id, what, -1, errno, "thread create failed"); return; }
pthread_join(th, 0);
char ex[60];
snprintf(ex, sizeof ex, "rc=%d duration_ms=%lld", t_rc, t_ms);
probe_case(id, what, t_rc, 0, ex);
}
int main(void) {
signal(SIGALRM, probe_alarm);
alarm(PROBE_MAX_S);
probe_header();
guard_arm();
void* h = dlopen("libSceLibcInternal.sprx", RTLD_LAZY);
mi = (mi_fn)(h ? dlsym(h, "_Mtx_init") : 0);
mo_fn ml = (mo_fn)(h ? dlsym(h, "_Mtx_lock") : 0);
mu = (mo_fn)(h ? dlsym(h, "_Mtx_unlock") : 0);
tl = (tl_fn)(h ? dlsym(h, "_Mtx_timedlock") : 0);
md_fn md = (md_fn)(h ? dlsym(h, "_Mtx_destroy") : 0);
char line[8];
snprintf(line, sizeof line, "%d%d%d%d%d%d", !!h, !!mi, !!ml, !!mu, !!tl, !!md);
probe_case("0", "dlopen libc, dlsym Init Lock Unlock Timedlock Destroy (1 yes, 0 no)", 0, 0, line);
if(!mi || !ml || !mu || !tl || !md) { probe_end(); return 0; }
g_m = 0;
mi(&g_m, 1);
ml(&g_m);
in_thread("a", "held by main, second thread _Mtx_timedlock(now + 100 ms)", rt_plus(100000000LL));
xt past = rt_plus(-1000000000LL);
in_thread("b", "held by main, second thread _Mtx_timedlock(now - 1 s)", past);
mu(&g_m);
in_thread("c.1", "free mutex, second thread _Mtx_timedlock(now + 100 ms)", rt_plus(100000000LL));
ml(&g_m);
xt again = rt_plus(100000000LL);
long long t0 = now_ns();
int r, e;
CALL(r, e, tl(&g_m, &again));
char ex[80];
snprintf(ex, sizeof ex, "rc=%d duration_ms=%lld signal=%d", r, (now_ns() - t0) / 1000000, (int)guard_sig);
probe_case("c.2", "same thread owns the plain mutex, _Mtx_timedlock(now + 100 ms)", r, e, ex);
mu(&g_m);
xt over = {rt_plus(0).sec, 1000000000LL};
in_thread("d.1", "free mutex, _Mtx_timedlock({now sec, 1e9 nsec})", over);
xt neg = {-1, 0};
in_thread("d.2", "free mutex, _Mtx_timedlock({-1 sec, 0})", neg);
md(&g_m);
probe_end();
return 0;
}raw outputAI-assisted (Claude Code). |
PrivacyOnion
left a comment
There was a problem hiding this comment.
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 2a2771c4f8:
- Conventions:
tools/check_conventions.pypassed;git diff --checkclean. - Build:
guest_libc_threads_testsbuilt cleanly. - CTest (
guest_libc_threads):1/1 Test #1131: guest_libc_threads ............... Passed 0.28 sec 100% tests passed, 0 tests failed out of 1 - Negative control: with
core/libs/prx/libc/src/Threads.cppreverted tomainand the new tests kept, the suite fails:Restoring the change makes it pass again.1/1 Test #1131: guest_libc_threads ...............Subprocess aborted***Exception: 0.35 sec 0% tests passed, 1 tests failed out of 1 - Code reading:
- core/libs/prx/libc/src/Threads.cpp:277-285: Verified self-relock handling for non-recursive mutexes ((mutex->type & mutexRecursive) == 0). Calling std::this_thread::sleep_until(deadline) and returning threadTimedout (2) correctly reproduces the measured PS5 firmware 11.60 behavior where relocking an owned plain mutex waits for the target deadline rather than failing immediately with threadBusy (3).
- core/libs/prx/libc/src/Threads.cpp:273-276: Verified input validation ordering and exception safety. Null target pointers are caught by APS5_INVALID_ARG_EX before dereference, XtimePoint safely converts xtime into time_point, and ResolveMutex guards against null handles and tag corruption.
- core/libs/prx/libc/src/Threads.cpp:280-284: Verified mutex ownership integrity across timeouts. Since the calling thread is already verified as owner under acquire semantics, no race condition exists, no state is mutated during the timeout, and the caller retains valid lock ownership after threadTimedout is returned.
- core/libs/tests/GuestLibcThreads.cpp:149-160: Verified test rigor and resource cleanup. Tests exercise both tryable (0x02) and plain (0x01) non-recursive mutexes owned by the caller, assert elapsed wait times >= 90 ms for 100 ms deadlines, verify return code timedout (2), and properly unlock and destroy all allocated mutexes.
- docs/dev/debt/libc.md:107 and AGENTS.md rules: Confirmed zero comments added in C++ source/test files, debt documentation accurately describes the measured 11.60 behavior and open Windows timing verification, and Conventional Commits formatting is satisfied.
- Minor: please drop the
Generated withfooter from the description; the AI-assisted checkbox can stay.
Looks Good To Me
|
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.
|
What
_Mtx_timedlockreturned_Thrd_busy(3) at once when the calling thread already held a non-recursive mutex (Threads.cpp:279-281onmainb6717527ce). A PS5 on firmware 11.60 (libSceLibcInternalthroughdlopen) waits until the deadline and returns_Thrd_timedout(2): with a plain mutex the thread owned and a deadline 100 ms ahead it returned 2 after 100 ms (case c.2, line 6 of the raw output)._Mtx_timedlocknow sleeps until the deadline and returns the timeout for that case, as it already does for a mutex another thread holds; recursive mutexes still count up. The cases where the mutex is held by another thread (a, b, lines 3 and 4), free (c.1, d.1, d.2, lines 5, 7, 8) and the past deadline (b) already matchedmainand are unchanged. The test commit expects the timeout after at least 90 ms for a plain mutex (type 1) and for the other non-recursive type the test used before; the debt entrydocs/dev/debt/libc.md:107now states the measured result, and what stays open is a title process and Windows timing.Title reference: PPSA12361 imports
_Mtx_timedlockonce (0x112ff72). It passes a static mutex and an xtime computed from a time value, treats 0 as success and 2 as timeout, and takes every other result as an error, so it relies on exactly the two codes.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-14 at 05:55 UTC. A title process may differ. The case is c.2, line 6 of the raw output in the first comment (7 cases,END 7).mainbefore_Mtx_timedlock(plain mutex owned by the caller, now + 100 ms)Threads.cpp:279-281)now + 100 msnow + 100 ms,{now, 1e9 ns}or{-1, 0}Windows (MinGW-w64 from WinLibs, Release),
guest_libc_threads, built onmainatb6717527ceon 2026-11-14 at about 07:38 UTC: the test commit alone aborts (exit code 0xc0000409, aRequirefailure, 1 of 1 test), the fix commit passes (1 of 1) and the docs commit passes (1 of 1).python tools/check_conventions.py --base upstream/mainreports no error and no warning. Not tested: Linux, macOS, the CI runner, a title process, firmware other than 11.60, a past deadline for a mutex the caller owns, and mutex types other than plain on the console.Overlap: the 92 open pull requests that change
core/libs/prx/libc/src/Threads.cpp,core/libs/tests/GuestLibcThreads.cppordocs/dev/debt/libc.md(found by reading the changed files of all 1561 open pull requests at about 08:32 UTC). Four of them changeThreads.cpp(#18347, #18122, #9447 and #1835; #9447 also the test file); they were test-merged on 2026-11-14 at about 08:58 UTC againstmain2cebbe43ee(the branch is based onb6717527ce), and the branch merges intomainwithout a conflict. #18347 (_Mtx_trylock, other function in the same file) and #18122 merge cleanly with and without this change; #9447 and #1835 already conflict withmainwithout it and still do. The other 88 change onlylibc.md: the patch of none of them touches the_Mtx_timedlockentry or a line next to it, so none can conflict with its one-line change. None conflicts only with this change. No open pull request has_Mtx_timedlockin its title or branch name.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