Skip to content

fix(libc): make _Mtx_timedlock of a plain mutex the caller owns wait for the deadline and time out - #19945

Merged
oneandonlydean merged 3 commits into
boykopovar:mainfrom
xXPBSXx:n3/libc-mtx-timedlock-owner-timeout
Nov 14, 2026
Merged

oneandonlydean merged 3 commits into
boykopovar:mainfrom
xXPBSXx:n3/libc-mtx-timedlock-owner-timeout

Conversation

@xXPBSXx

@xXPBSXx xXPBSXx commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

What

_Mtx_timedlock returned _Thrd_busy (3) at once when the calling thread already held a non-recursive mutex (Threads.cpp:279-281 on main b6717527ce). A PS5 on firmware 11.60 (libSceLibcInternal through dlopen) 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_timedlock now 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 matched main and 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 entry docs/dev/debt/libc.md:107 now states the measured result, and what stays open is a title process and Windows timing.

Title reference: PPSA12361 imports _Mtx_timedlock once (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_version 0x11600005), 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).

Call PS5, payload process, firmware 11.60 AnyPS5 main before here now
_Mtx_timedlock(plain mutex owned by the caller, now + 100 ms) 2 after 100 ms (line 6) 3 at once (code, Threads.cpp:279-281) 2 after the deadline
held by another thread, now + 100 ms 2 after 99 ms (line 3) 2 2
held by another thread, deadline in the past 2 at once (line 4) 2 2
free mutex, deadline now + 100 ms, {now, 1e9 ns} or {-1, 0} 0 (lines 5, 7, 8) 0 0

Windows (MinGW-w64 from WinLibs, Release), guest_libc_threads, built on main at b6717527ce on 2026-11-14 at about 07:38 UTC: the test commit alone aborts (exit code 0xc0000409, a Require failure, 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/main reports 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.cpp or docs/dev/debt/libc.md (found by reading the changed files of all 1561 open pull requests at about 08:32 UTC). Four of them change Threads.cpp (#18347, #18122, #9447 and #1835; #9447 also the test file); they were test-merged on 2026-11-14 at about 08:58 UTC against main 2cebbe43ee (the branch is based on b6717527ce), and the branch merges into main without 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 with main without it and still do. The other 88 change only libc.md: the patch of none of them touches the _Mtx_timedlock entry 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_timedlock in its title or branch name.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a (no graphics change)
  • AI-assisted: yes

AI-assisted (Claude Code).

🤖 Generated with Claude Code

xXPBSXx and others added 3 commits November 14, 2026 08:33
… 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>
@xXPBSXx

xXPBSXx commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Probe source (built with ps5-payload-sdk v0.45; PROBE_BUILD is the first 12 hex digits of the source's SHA-256, 5e6c21f2e212) and its raw output from the run on 2026-11-14 at 05:55 UTC. The clock in the PROBE line is the console's own clock. The probe takes _Mtx_init, _Mtx_lock, _Mtx_unlock, _Mtx_timedlock and _Mtx_destroy from libSceLibcInternal.sprx (dlopen), asks for a plain mutex held by the main thread from a second thread (deadline 100 ms ahead and in the past), for a free mutex, for a mutex the calling thread owns (plain, 100 ms) and for an xtime with 1e9 nanoseconds and negative seconds, prints a line for every case and ends itself after 50 seconds; it ran to its END line. An internal case reference in one header comment was removed; the code is unchanged, and the build ID is the hash of the original file.

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 output
PROBE	libc_mtx_timedlock	fw=0x11600005	build=5e6c21f2e212	pid=126	utc=2026-11-14T07:37:18Z
CASE	0	dlopen libc, dlsym Init Lock Unlock Timedlock Destroy (1 yes, 0 no)	0	0	111111
CASE	a	held by main, second thread _Mtx_timedlock(now + 100 ms)	2	0	rc=2 duration_ms=99
CASE	b	held by main, second thread _Mtx_timedlock(now - 1 s)	2	0	rc=2 duration_ms=0
CASE	c.1	free mutex, second thread _Mtx_timedlock(now + 100 ms)	0	0	rc=0 duration_ms=0
CASE	c.2	same thread owns the plain mutex, _Mtx_timedlock(now + 100 ms)	2	0	rc=2 duration_ms=100 signal=0
CASE	d.1	free mutex, _Mtx_timedlock({now sec, 1e9 nsec})	0	0	rc=0 duration_ms=0
CASE	d.2	free mutex, _Mtx_timedlock({-1 sec, 0})	0	0	rc=0 duration_ms=0
END	7

AI-assisted (Claude Code).

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 2a2771c4f8:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_libc_threads_tests built 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.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #1131: guest_libc_threads ...............Subprocess aborted***Exception:   0.35 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • 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 with footer from the description; the AI-assisted checkbox can stay.

Looks Good To Me

@JJenkx

JJenkx commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Windows check of head 2a2771c4f8, merged onto main 2cebbe43ee (8c46f8ffac, clean merge).

Setup: Windows 11 Enterprise 22621, WinLibs GCC 15.2 UCRT, Release. The hosted Windows check does not run these tests on pull requests.

  • guest_libc_threads passes in 3 of 3 runs, none skipped.

AI-assisted: yes.

@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

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.

Pull request Shared files not compared
PR 1835 core/libs/prx/libc/src/Threads.cpp
PR 7447 docs/dev/debt/libc.md
PR 7544 docs/dev/debt/libc.md
PR 7715 docs/dev/debt/libc.md
PR 8150 docs/dev/debt/libc.md
PR 8965 docs/dev/debt/libc.md
PR 9087 docs/dev/debt/libc.md
PR 9340 docs/dev/debt/libc.md
PR 9447 core/libs/prx/libc/src/Threads.cpp
core/libs/tests/GuestLibcThreads.cpp
docs/dev/debt/libc.md
PR 9466 docs/dev/debt/libc.md
PR 9526 docs/dev/debt/libc.md
PR 10409 docs/dev/debt/libc.md
PR 11172 docs/dev/debt/libc.md
PR 11332 docs/dev/debt/libc.md
PR 11661 docs/dev/debt/libc.md
PR 11689 docs/dev/debt/libc.md
PR 11698 docs/dev/debt/libc.md
PR 12184 docs/dev/debt/libc.md
PR 12682 docs/dev/debt/libc.md
PR 12688 docs/dev/debt/libc.md
PR 12700 docs/dev/debt/libc.md
PR 12849 docs/dev/debt/libc.md
PR 12965 docs/dev/debt/libc.md
PR 15973 docs/dev/debt/libc.md
PR 16791 docs/dev/debt/libc.md
PR 17557 docs/dev/debt/libc.md
PR 17558 docs/dev/debt/libc.md
PR 18380 docs/dev/debt/libc.md
PR 18405 docs/dev/debt/libc.md
PR 18787 docs/dev/debt/libc.md

@oneandonlydean
oneandonlydean merged commit ff6b598 into boykopovar:main Nov 14, 2026
22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants