feat(libSceNpCommon): implement sce::np::Mutex and sce::np::Cond #13130

Merged
hypermoist merged 7 commits from upstream-pr/13130 into main 2026-11-05 17:59:32 +00:00
hypermoist commented 2026-10-30 03:44:44 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hypermoist on 2026-10-30T03:44:44Z.


What

Implements 26 sce::np::Mutex and sce::np::Cond exports from libSceNpCommon.sprx of firmware 13.60 (read from disassembly, not measured on a console). Five of them were NotImplemented stubs with placeholder int (void) declarations: Cond::ctor, Cond::Init, Cond::D0, Cond::D1 and Mutex::Destroy. The other 21 are exported by the module but were missing from AnyPS5. Mutex::IsInit stays a stub, because open #12823 implements it.

Both objects are 24 bytes and are declared in Api.hpp. Each vtable is {0, 0, D1, D0}.

NpMutexObject (vtable, PthreadMutex mutex, bool isInit at +0x10):

  • C1/C2: set the vtable, a null mutex and isInit = false.
  • ctor: clears only isInit.
  • D1/D2 and dtor: call scePthreadMutexDestroy when initialized. D1/D2 also reset the vtable. D0 uses sceNpMutexDestroy and then frees through sce::np::Object::operator delete(void*), so it is stacked on #12836.
  • Init(const char* name, uint32_t flags):
    • returns 0x80559E03 when already initialized;
    • otherwise calls sceNpMutexInit(&mutex, name, flags & 1), returns its error, or sets isInit.
  • Destroy: destroys when initialized and always clears isInit.
  • Lock / Unlock: forward to sceNpMutexLock / sceNpMutexUnlock.
  • TryLock: returns false on 0x8055800F (busy) and true on success.

NpCondObject (vtable, PthreadCond cond, PthreadMutex* mutex):

  • C1/C2 and ctor: clear both members. IsInit is mutex != nullptr.
  • Init(const char* name, Mutex* mutex):
    • returns 0x80559E03 when already initialized;
    • otherwise calls sceNpCondInit(&cond, name, 0) and stores the address of the Mutex's kernel mutex (the object plus 8).
  • Destroy: destroys when initialized and clears both members.
  • D1/D2, dtor and D0: work as for Mutex, using scePthreadCondDestroy / sceNpCondDestroy.
  • Wait(uint32_t usec), Signal, SignalAll, SignalTo(pthread*): forward to sceNpCondTimedwait(&cond, mutex, usec) / sceNpCondSignal / sceNpCondSignalAll / sceNpCondSignalTo and return only negative results (result & (result >> 31) in the module).

Where the module halts:

  • Before Init: Lock, Unlock and TryLock assert IsInit() and panic. AnyPS5 throws std::invalid_argument.
  • Kernel failure: these three HALT_ASSERT(ret == 0) after the kernel call (other than busy for TryLock), and Lock/Unlock call abort. AnyPS5 throws std::runtime_error, following the libSceJson2 exports.

The debt file records both, together with two module behaviours this PR keeps:

  • Cond::Wait does not check IsInit;
  • Cond::Init with a null Mutex stores the address 8 and then counts as initialized.

Tested

Linux (CachyOS, GCC 16.2, Release): ctest --test-dir build -R 'np_common|public_headers' --output-on-failure, 70/70 passed. guest_np_common_runtime passed 3 of 3 runs, in 0.03 s each. TestMutexAndCondObjects in GuestNpCommonRuntime.cpp uses real kernel mutexes, condition variables and threads to check:

  • the init state and the 0x80559E03 second Init;
  • the throw before Init;
  • that a held plain mutex cannot be taken again with TryLock, while flags 3 make it recursive;
  • that Destroy may be repeated;
  • that Cond::Init keeps &mutex.mutex;
  • a timed-out Wait returning 0x8055800B;
  • Signal and SignalTo each waking a waiting thread;
  • Init with a null mutex;
  • both deleting destructors freeing through the allocator stored by Object::operator new.

Mutation check: I changed 8 single lines of the new functions, one at a time; the test fails for all 8. The changes were:

  • the recursive flag dropped;
  • TryLock reporting busy as success;
  • the stored mutex address off by 8;
  • Wait hiding its error;
  • SignalTo ignoring the thread;
  • Mutex::Destroy and Cond::Destroy not clearing their state;
  • a missing double-Init check.

No firmware differential: these methods wrap kernel objects. A unicorn run would only exercise the glue against a fake kernel, and I can't swap the kernel under AnyPS5. The contract above comes from the disassembly, including the vtable relocations and the C1/C2 and D1/D2 aliases (one address each).

Windows not built. Not run on a console.

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. D0 uses sce::np::Object::operator delete from #12836, which is merged; main is merged in.
    • #13120 adds NotImplemented declarations for 21 of these exports, the ones missing from main, so whichever lands second must drop them from InventoryExports.cpp; if #13120 lands first, I will do it here.
    • This PR lands first, then #13270, then #13277 (all mine). They add the same NP_ERROR_OBJECT_ALREADY_INITIALIZED constant in the same place; #13270 and #13277 declare Depends on this one and keep its copy.
    • #11601, #12818, #12825, #12829, #12830 and #12859 touch neighbouring stub, declaration or include lines; whichever lands second needs a trivial merge, and I will do it.
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

Assisted With AI: Yes. All tests were run locally on computer hardware (AMD Ryzen 5 5600G, 32 GB RAM, NVIDIA GeForce RTX 3060, CachyOS Linux 7.3, GCC 16.2), not on an actual console.

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5079134668 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13130). Originally posted by [hypermoist](https://github.com/hypermoist) on 2026-10-30T03:44:44Z. --- ### What Implements 26 `sce::np::Mutex` and `sce::np::Cond` exports from `libSceNpCommon.sprx` of firmware 13.60 (read from disassembly, not measured on a console). Five of them were `NotImplemented` stubs with placeholder `int (void)` declarations: `Cond::ctor`, `Cond::Init`, `Cond::D0`, `Cond::D1` and `Mutex::Destroy`. The other 21 are exported by the module but were missing from AnyPS5. `Mutex::IsInit` stays a stub, because open #12823 implements it. Both objects are 24 bytes and are declared in `Api.hpp`. Each vtable is `{0, 0, D1, D0}`. **`NpMutexObject` (vtable, `PthreadMutex mutex`, `bool isInit` at +0x10):** - **C1/C2:** set the vtable, a null mutex and `isInit = false`. - **`ctor`:** clears only `isInit`. - **D1/D2 and `dtor`:** call `scePthreadMutexDestroy` when initialized. D1/D2 also reset the vtable. `D0` uses `sceNpMutexDestroy` and then frees through `sce::np::Object::operator delete(void*)`, so it is stacked on #12836. - **`Init(const char* name, uint32_t flags)`:** - returns `0x80559E03` when already initialized; - otherwise calls `sceNpMutexInit(&mutex, name, flags & 1)`, returns its error, or sets `isInit`. - **`Destroy`:** destroys when initialized and always clears `isInit`. - **`Lock` / `Unlock`:** forward to `sceNpMutexLock` / `sceNpMutexUnlock`. - **`TryLock`:** returns false on `0x8055800F` (busy) and true on success. **`NpCondObject` (vtable, `PthreadCond cond`, `PthreadMutex* mutex`):** - **C1/C2 and `ctor`:** clear both members. `IsInit` is `mutex != nullptr`. - **`Init(const char* name, Mutex* mutex)`:** - returns `0x80559E03` when already initialized; - otherwise calls `sceNpCondInit(&cond, name, 0)` and stores the address of the `Mutex`'s kernel mutex (the object plus 8). - **`Destroy`:** destroys when initialized and clears both members. - **D1/D2, `dtor` and `D0`:** work as for `Mutex`, using `scePthreadCondDestroy` / `sceNpCondDestroy`. - **`Wait(uint32_t usec)`, `Signal`, `SignalAll`, `SignalTo(pthread*)`:** forward to `sceNpCondTimedwait(&cond, mutex, usec)` / `sceNpCondSignal` / `sceNpCondSignalAll` / `sceNpCondSignalTo` and return only negative results (`result & (result >> 31)` in the module). **Where the module halts:** - **Before `Init`:** `Lock`, `Unlock` and `TryLock` assert `IsInit()` and panic. AnyPS5 throws `std::invalid_argument`. - **Kernel failure:** these three `HALT_ASSERT(ret == 0)` after the kernel call (other than busy for `TryLock`), and `Lock`/`Unlock` call `abort`. AnyPS5 throws `std::runtime_error`, following the libSceJson2 exports. The debt file records both, together with two module behaviours this PR keeps: - `Cond::Wait` does not check `IsInit`; - `Cond::Init` with a null `Mutex` stores the address 8 and then counts as initialized. ### Tested Linux (CachyOS, GCC 16.2, Release): `ctest --test-dir build -R 'np_common|public_headers' --output-on-failure`, 70/70 passed. `guest_np_common_runtime` passed 3 of 3 runs, in 0.03 s each. `TestMutexAndCondObjects` in `GuestNpCommonRuntime.cpp` uses real kernel mutexes, condition variables and threads to check: - the init state and the `0x80559E03` second `Init`; - the throw before `Init`; - that a held plain mutex cannot be taken again with `TryLock`, while flags `3` make it recursive; - that `Destroy` may be repeated; - that `Cond::Init` keeps `&mutex.mutex`; - a timed-out `Wait` returning `0x8055800B`; - `Signal` and `SignalTo` each waking a waiting thread; - `Init` with a null mutex; - both deleting destructors freeing through the allocator stored by `Object::operator new`. **Mutation check:** I changed 8 single lines of the new functions, one at a time; the test fails for all 8. The changes were: - the recursive flag dropped; - `TryLock` reporting busy as success; - the stored mutex address off by 8; - `Wait` hiding its error; - `SignalTo` ignoring the thread; - `Mutex::Destroy` and `Cond::Destroy` not clearing their state; - a missing double-`Init` check. **No firmware differential:** these methods wrap kernel objects. A unicorn run would only exercise the glue against a fake kernel, and I can't swap the kernel under AnyPS5. The contract above comes from the disassembly, including the vtable relocations and the C1/C2 and D1/D2 aliases (one address each). Windows not built. Not run on a console. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none. `D0` uses `sce::np::Object::operator delete` from #12836, which is merged; `main` is merged in. - #13120 adds `NotImplemented` declarations for 21 of these exports, the ones missing from `main`, so whichever lands second must drop them from `InventoryExports.cpp`; if #13120 lands first, I will do it here. - **This PR lands first, then #13270, then #13277** (all mine). They add the same `NP_ERROR_OBJECT_ALREADY_INITIALIZED` constant in the same place; #13270 and #13277 declare `Depends on` this one and keep its copy. - #11601, #12818, #12825, #12829, #12830 and #12859 touch neighbouring stub, declaration or include lines; whichever lands second needs a trivial merge, and I will do it. - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes Assisted With AI: Yes. All tests were run locally on computer hardware (AMD Ryzen 5 5600G, 32 GB RAM, NVIDIA GeForce RTX 3060, CachyOS Linux 7.3, GCC 16.2), not on an actual console. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
CnRJay commented 2026-11-01 19:50:17 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-11-01T19:50:17Z.

Review: COMMENTED


Withdrawn. This review applied a title-ID/log requirement that is not in CONTRIBUTING (Unblocks: none is allowed), and it contained no code review.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5729925019 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13130#pullrequestreview-5729925019). Originally posted by [CnRJay](https://github.com/CnRJay) on 2026-11-01T19:50:17Z. **Review:** COMMENTED --- Withdrawn. This review applied a title-ID/log requirement that is not in CONTRIBUTING (`Unblocks: none` is allowed), and it contained no code review.
XairRrR commented 2026-11-03 23:51:57 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by XairRrR on 2026-11-03T23:51:57Z.

Review: APPROVED


Reviewed — approved

The new sce::np::Mutex and sce::np::Cond exports merge and build cleanly, they behave as the description says, and the new test passes and catches both mutations I tried.

What I ran

Head 4d75a8a77a135d508f64b595566d96301aa0a3dd, main 1c8c0efc8c41314402e6966da5bef6ea3d639d10, merged with --no-ff (tree e3626249063bd3b8bdd6f9b1969b9db6504a99de). Debian 13 VM, GCC 14.2.0, Release, Ninja.

git diff --check 1c8c0efc8c41314402e6966da5bef6ea3d639d10...4d75a8a77a135d508f64b595566d96301aa0a3dd
python3 tools/check_conventions.py --base 1c8c0efc8c41314402e6966da5bef6ea3d639d10
ctest --test-dir build -R "^guest_np_common_runtime$" --repeat until-fail:3 --output-on-failure
# mutation 1+2: TryLock reports busy as success, and Cond::Init drops the +8 offset
ninja -C build -j32 -l32 guest_np_common_runtime_tests
build/tests/guest_np_common_runtime_tests
# mutation 2 alone (Cond::Init offset)
ninja -C build -j32 -l32 guest_np_common_runtime_tests
build/tests/guest_np_common_runtime_tests
# restore Runtime.cpp from the merged tree
git show e3626249063bd3b8bdd6f9b1969b9db6504a99de:core/libs/prx/libSceNpCommon/Runtime.cpp > core/libs/prx/libSceNpCommon/Runtime.cpp
git status --porcelain
ninja -C build -j32 -l32 guest_np_common_runtime_tests
ctest --test-dir build -R "^(guest_np_common_runtime|public_headers)$" -j8 --test-load 32 --output-on-failure

Results

Check Result
git diff --check clean
check_conventions.py All conventions checks passed
Configure / build / libs (script) ok
Selected tests (script, 826 run) 822 passed, 3 expected skips, 0 new failures, 0 timeouts. 1 known failure (unwrap_self_UnwrapTest_test_new_output_inherits_the_destination_directory_group), which also fails on main
guest_np_common_runtime ×3 passed, 0.04 s each
public_headers passed (62.7 s). It is over 30 s on main too, so this PR does not cause it
Vulkan validation not applicable: no AGC, shader or VideoOut files changed

Negative control

You can't just put the production files back from main: the test calls the new typed declarations and no longer compiles against the old int (void) stubs. JJenkx's comment already noted this. I mutated the production code instead:

  • TryLock returns true on NP_ERROR_MUTEX_BUSY (applied together with the offset mutation): the test aborts with a held plain mutex cannot be taken again.
  • Cond::Init stores the Mutex address without + offsetof(NpMutexObject, mutex) (applied alone): the test aborts with a condition keeps the kernel mutex of its sce::np::Mutex.

I restored Runtime.cpp from the merged tree. git status --porcelain came back empty, and after the rebuild the test passed again.

Findings

Blocking

None.

Non-blocking

  • core/libs/prx/libSceNpCommon/Runtime.cpp:1398-1399: the new block has no blank line between Cond::SignalTo and MemoryStreamReaderC1. The rest of the file puts one between functions. This is cosmetic.

Code notes (checked, no action needed)

  • Vtables: vtable = &NpXxxVtable[2], so vtable[0] is D1 and vtable[1] is D0. That matches the {0, 0, D1, D0} layout in the description, and the test calls vtable[1] and checks that the memory is freed through the stored allocator.
  • Return values: std::min(result, 0) gives the same value as the module's result & (result >> 31) for every 32-bit int.
  • Recursive flag: Mutex::Init passes flags & 1, and sceNpMutexInit (Export.cpp:83-92) turns bit 0 into MUTEX_TYPE_RECURSIVE. The test covers this with flags 3.
  • Error codes: TryLock compares against NP_ERROR_MUTEX_BUSY (0x8055800F, Runtime.cpp:472), the value sceNpMutexTryLock maps EBUSY to.
  • Throwing paths: the throws before Init and on kernel failure take the place of module halts, and both are recorded in docs/dev/debt/libSceNpCommon.md.
  • Stub cleanup: the five stubs that are now implemented are removed from PendingExportsRound7.cpp, Api.hpp and the debt list, and public_headers passes.
  • Struct sizes: on x86-64 both structs are 24 bytes (8 + 8 + 1 padded, and 8 + 8 + 8), as the description says. A static_assert(sizeof(...) == 0x18) next to each struct would lock that ABI in, but it isn't required.

Not verified

  • The behaviour of the firmware 13.60 module itself: I had no libSceNpCommon.sprx disassembly and no console. The contract comes from the author's reading of the disassembly.
  • Cond::Wait before Init sends a null mutex to scePthreadCondTimedwait, and Init with a null Mutex stores the address 8. The debt file records both, as the module's behaviour. The test covers the second case only up to Destroy, and nothing waits on such a condition, so I did not check what the AnyPS5 kernel does with those pointers.
  • I did not build or test on Windows. JJenkx reported a passing Windows run on an earlier head (8acf2c4809).
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5761141154 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/13130#pullrequestreview-5761141154). Originally posted by [XairRrR](https://github.com/XairRrR) on 2026-11-03T23:51:57Z. **Review:** APPROVED --- # Reviewed — approved The new `sce::np::Mutex` and `sce::np::Cond` exports merge and build cleanly, they behave as the description says, and the new test passes and catches both mutations I tried. ## What I ran Head `4d75a8a77a135d508f64b595566d96301aa0a3dd`, `main` `1c8c0efc8c41314402e6966da5bef6ea3d639d10`, merged with `--no-ff` (tree `e3626249063bd3b8bdd6f9b1969b9db6504a99de`). Debian 13 VM, GCC 14.2.0, Release, Ninja. ```sh git diff --check 1c8c0efc8c41314402e6966da5bef6ea3d639d10...4d75a8a77a135d508f64b595566d96301aa0a3dd python3 tools/check_conventions.py --base 1c8c0efc8c41314402e6966da5bef6ea3d639d10 ctest --test-dir build -R "^guest_np_common_runtime$" --repeat until-fail:3 --output-on-failure # mutation 1+2: TryLock reports busy as success, and Cond::Init drops the +8 offset ninja -C build -j32 -l32 guest_np_common_runtime_tests build/tests/guest_np_common_runtime_tests # mutation 2 alone (Cond::Init offset) ninja -C build -j32 -l32 guest_np_common_runtime_tests build/tests/guest_np_common_runtime_tests # restore Runtime.cpp from the merged tree git show e3626249063bd3b8bdd6f9b1969b9db6504a99de:core/libs/prx/libSceNpCommon/Runtime.cpp > core/libs/prx/libSceNpCommon/Runtime.cpp git status --porcelain ninja -C build -j32 -l32 guest_np_common_runtime_tests ctest --test-dir build -R "^(guest_np_common_runtime|public_headers)$" -j8 --test-load 32 --output-on-failure ``` ## Results | Check | Result | |---|---| | `git diff --check` | clean | | `check_conventions.py` | All conventions checks passed | | Configure / build / `libs` (script) | ok | | Selected tests (script, 826 run) | 822 passed, 3 expected skips, 0 new failures, 0 timeouts. 1 known failure (`unwrap_self_UnwrapTest_test_new_output_inherits_the_destination_directory_group`), which also fails on `main` | | `guest_np_common_runtime` ×3 | passed, 0.04 s each | | `public_headers` | passed (62.7 s). It is over 30 s on `main` too, so this PR does not cause it | | Vulkan validation | not applicable: no AGC, shader or VideoOut files changed | ## Negative control You can't just put the production files back from `main`: the test calls the new typed declarations and no longer compiles against the old `int (void)` stubs. JJenkx's comment already noted this. I mutated the production code instead: - **`TryLock` returns `true` on `NP_ERROR_MUTEX_BUSY`** (applied together with the offset mutation): the test aborts with `a held plain mutex cannot be taken again`. - **`Cond::Init` stores the `Mutex` address without `+ offsetof(NpMutexObject, mutex)`** (applied alone): the test aborts with `a condition keeps the kernel mutex of its sce::np::Mutex`. I restored `Runtime.cpp` from the merged tree. `git status --porcelain` came back empty, and after the rebuild the test passed again. ## Findings ### Blocking None. ### Non-blocking - `core/libs/prx/libSceNpCommon/Runtime.cpp:1398-1399`: the new block has no blank line between `Cond::SignalTo` and `MemoryStreamReaderC1`. The rest of the file puts one between functions. This is cosmetic. ### Code notes (checked, no action needed) - Vtables: `vtable = &NpXxxVtable[2]`, so `vtable[0]` is D1 and `vtable[1]` is D0. That matches the `{0, 0, D1, D0}` layout in the description, and the test calls `vtable[1]` and checks that the memory is freed through the stored allocator. - Return values: `std::min(result, 0)` gives the same value as the module's `result & (result >> 31)` for every 32-bit `int`. - Recursive flag: `Mutex::Init` passes `flags & 1`, and `sceNpMutexInit` (`Export.cpp:83-92`) turns bit 0 into `MUTEX_TYPE_RECURSIVE`. The test covers this with flags `3`. - Error codes: `TryLock` compares against `NP_ERROR_MUTEX_BUSY` (`0x8055800F`, `Runtime.cpp:472`), the value `sceNpMutexTryLock` maps EBUSY to. - Throwing paths: the throws before `Init` and on kernel failure take the place of module halts, and both are recorded in `docs/dev/debt/libSceNpCommon.md`. - Stub cleanup: the five stubs that are now implemented are removed from `PendingExportsRound7.cpp`, `Api.hpp` and the debt list, and `public_headers` passes. - Struct sizes: on x86-64 both structs are 24 bytes (8 + 8 + 1 padded, and 8 + 8 + 8), as the description says. A `static_assert(sizeof(...) == 0x18)` next to each struct would lock that ABI in, but it isn't required. ## Not verified - The behaviour of the firmware 13.60 module itself: I had no `libSceNpCommon.sprx` disassembly and no console. The contract comes from the author's reading of the disassembly. - `Cond::Wait` before `Init` sends a null mutex to `scePthreadCondTimedwait`, and `Init` with a null `Mutex` stores the address 8. The debt file records both, as the module's behaviour. The test covers the second case only up to `Destroy`, and nothing waits on such a condition, so I did not check what the AnyPS5 kernel does with those pointers. - I did not build or test on Windows. JJenkx reported a passing Windows run on an earlier head (`8acf2c4809`). <!-- anyps5-bots job=2220 head=4d75a8a77a135d508f64b595566d96301aa0a3dd -->
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!13130
No description provided.