feat(libSceNpCommon): implement sce::np::RingBuf and RingBufMemory #12852

Merged
hypermoist merged 15 commits from upstream-pr/12852 into main 2026-11-05 08:50:16 +00:00
hypermoist commented 2026-10-29 12:42:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hypermoist on 2026-10-29T12:42:43Z.


What

Implements sce::np::RingBuf and sce::np::RingBufMemory from libSceNpCommon.sprx of firmware 13.60 (read from disassembly, not measured on a console), in a new RingBuf.cpp. That is 30 exports:

  • 9 were NotImplemented stubs with placeholder int (void) declarations;
  • 21 are exported by the module but were missing from AnyPS5, including the C2/D2 aliases.

RingBuf::IsFull and RingBufMemory::IsInit are left as they are on main, because #12823 implements them.

This is stacked on #12839 (itself on #12836): D0 frees through sce::np::Object's delete, and RingBufMemory uses the extended allocator. The new commits are ba9b4ebcb0, 76858c5f19, 56551447a9 and aac4ad09ba; 03fb3cb264 only merges #12839.

Layout (NpRingBuf, 0x30 bytes, and NpRingBufMemory, 0x38 bytes): vtable, buf, read pointer, write pointer, data size, buffer size, and for RingBufMemory the SceNpAllocatorEx*. Both vtables are {0, 0, D1, D0}, as in the module, and the constructors store a pointer to the D1 slot.

RingBuf

  • C1/C2 set the vtable and clear the fields. ctor clears the fields only, and dtor does nothing. D1/D2 reset the vtable, and D0 also frees the object through its sce::np::Object header.
  • Init(buf, size) attaches caller storage. Destroy clears the fields, and Clear resets both pointers and the size.
  • IsEmpty, GetDataSize and GetFreeSize report the counts.
  • CheckoutForWrite(size_t*) returns the contiguous free block, or null when full. When the buffer is empty it first moves both pointers back to the start.
  • CheckinForWrite(n) advances the write pointer and wraps it at the end.
  • CheckoutForRead / CheckinForRead are the read-side pair. CheckinForRead does not check its size.
  • Write(data, n):
    • returns 0x80559E0A when n exceeds the free size;
    • otherwise writes in up to two blocks across the wrap.
  • Read(dst, n):
    • returns 0 for n == 0 and 0x80559E0B when n exceeds the data;
    • otherwise reads in up to two blocks;
    • a null dst only drops the data.
  • Peek(offset, dst, n):
    • copies without consuming;
    • returns 0x80559E0A unless offset < size and offset + n <= size.

RingBufMemory

  • C1/C2(SceNpAllocatorEx*) store the allocator. D1/D2 release buf and leave the RingBuf vtable, and D0 then frees the object. dtor releases buf, and ctor does nothing.
  • Init(size) allocates first and returns the allocator's outOfMemoryError when that fails.
  • Destroy releases buf and clears the fields.
  • Expand(n) reallocates to bufSize + n and returns 0x80559E09 when that fails. It moves the data after the read pointer up by n only when the write pointer is below the read pointer. So, as in the module, expanding a full buffer keeps both pointers together: the next write takes it for empty, starts at the beginning over the queued data, and the following read asserts. The debt entry records this, and TestRingBuf pins it.

Gaps (debt entry). Where the module asserts and calls sceNpPanic, this throws std::invalid_argument naming the check. That covers:

  • Init on a buffer that already has storage, or with null or empty storage;
  • a null CheckoutForWrite size, and a CheckinForWrite past the end;
  • a zero-byte Write into a full buffer;
  • a null or empty Peek;
  • read pointers that disagree with the data size.

The debt file drops the 9 "signature unknown" entries.

Tested

Linux (CachyOS, GCC 16.2, Release): ctest --test-dir build -R 'np_common|public_headers' --output-on-failure, 70/70 passed. TestRingBuf in GuestNpCommonRuntime.cpp covers:

  • a write that does not fit, an in-order read, a write and a peek across the wrap;
  • both error codes, a null read buffer, and the checkout/checkin pairs;
  • RingBufMemory on a memory heap: Init, a wrap, and Expand keeping the order of wrapped data;
  • expanding a full buffer, then writing to it (the module's result);
  • the deleting destructor called through the vtable.

Comparison against the firmware code: I relinked the 13.60 module with this repo's relinker and ran both classes under unicorn (x86-64 emulation on a PC, not a console). The allocator callbacks and printf/abort (reached through the module's sceNpPanic) were bound to recording handlers.

  • Corpus: 1,500 random sequences plus 4 fixed Expand sequences (full with the pointers meeting at 1, full at 0, wrapped but not full, and empty), half of them RingBuf on caller storage and half RingBufMemory on a recording allocator (with injected allocation failures), 31,279 operations in all. Buffer sizes run from 1 to 64. The operations are writes and reads of random sizes (including 0 and more than fits, and a null destination), peeks, the checkout/checkin pairs (with checkins up to one past the block), Clear, the size queries, Expand, re-Init and Destroy. A firmware assertion is recorded as panic and ends the sequence; there were 441.
  • What was recorded after each operation: the result, the bytes read or peeked (plus 4 guard bytes), the object (vtable, which buffer, both pointers as offsets, both sizes), the buffer contents, and every allocator release.
  • Result: replaying the same sequences through this implementation gives 0 mismatches, every panic included. 29 corrupted expectations give 29 mismatches.
  • Not in the corpus: the constructors, destructors, ctor and dtor. I ran those separately on an object behind a sce::np::Object header, and they match: D0 frees the header block, and RingBufMemory's destructors release buf first.
  • IsFull / IsInit: the replay computes these two from the fields, because they belong to #12823.

The generator and harness are np_ringbuf_make_cases.py / np_ringbuf_replay.cpp in https://gist.github.com/hypermoist/1834cf221fd737cdb4cca272cc1156d1. The gist has no module or recorded output.

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: #12839. It removes stubs next to the ones #12823 and #12825 remove, so whichever lands later needs a trivial rebase; I will do it on this side.
  • 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:5068200770 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12852). Originally posted by [hypermoist](https://github.com/hypermoist) on 2026-10-29T12:42:43Z. --- ### What Implements `sce::np::RingBuf` and `sce::np::RingBufMemory` from `libSceNpCommon.sprx` of firmware 13.60 (read from disassembly, not measured on a console), in a new `RingBuf.cpp`. That is 30 exports: - 9 were `NotImplemented` stubs with placeholder `int (void)` declarations; - 21 are exported by the module but were missing from AnyPS5, including the `C2`/`D2` aliases. `RingBuf::IsFull` and `RingBufMemory::IsInit` are left as they are on main, because #12823 implements them. **This is stacked on #12839** (itself on #12836): `D0` frees through `sce::np::Object`'s delete, and `RingBufMemory` uses the extended allocator. The new commits are `ba9b4ebcb0`, `76858c5f19`, `56551447a9` and `aac4ad09ba`; `03fb3cb264` only merges #12839. **Layout** (`NpRingBuf`, 0x30 bytes, and `NpRingBufMemory`, 0x38 bytes): vtable, `buf`, read pointer, write pointer, data size, buffer size, and for `RingBufMemory` the `SceNpAllocatorEx*`. Both vtables are `{0, 0, D1, D0}`, as in the module, and the constructors store a pointer to the `D1` slot. **RingBuf** - `C1`/`C2` set the vtable and clear the fields. `ctor` clears the fields only, and `dtor` does nothing. `D1`/`D2` reset the vtable, and `D0` also frees the object through its `sce::np::Object` header. - `Init(buf, size)` attaches caller storage. `Destroy` clears the fields, and `Clear` resets both pointers and the size. - `IsEmpty`, `GetDataSize` and `GetFreeSize` report the counts. - `CheckoutForWrite(size_t*)` returns the contiguous free block, or null when full. When the buffer is empty it first moves both pointers back to the start. - `CheckinForWrite(n)` advances the write pointer and wraps it at the end. - `CheckoutForRead` / `CheckinForRead` are the read-side pair. `CheckinForRead` does not check its size. - `Write(data, n)`: - returns `0x80559E0A` when `n` exceeds the free size; - otherwise writes in up to two blocks across the wrap. - `Read(dst, n)`: - returns 0 for `n == 0` and `0x80559E0B` when `n` exceeds the data; - otherwise reads in up to two blocks; - a null `dst` only drops the data. - `Peek(offset, dst, n)`: - copies without consuming; - returns `0x80559E0A` unless `offset < size` and `offset + n <= size`. **RingBufMemory** - `C1`/`C2(SceNpAllocatorEx*)` store the allocator. `D1`/`D2` release `buf` and leave the RingBuf vtable, and `D0` then frees the object. `dtor` releases `buf`, and `ctor` does nothing. - `Init(size)` allocates first and returns the allocator's `outOfMemoryError` when that fails. - `Destroy` releases `buf` and clears the fields. - `Expand(n)` reallocates to `bufSize + n` and returns `0x80559E09` when that fails. It moves the data after the read pointer up by `n` only when the write pointer is below the read pointer. So, as in the module, expanding a full buffer keeps both pointers together: the next write takes it for empty, starts at the beginning over the queued data, and the following read asserts. The debt entry records this, and `TestRingBuf` pins it. **Gaps (debt entry).** Where the module asserts and calls `sceNpPanic`, this throws `std::invalid_argument` naming the check. That covers: - `Init` on a buffer that already has storage, or with null or empty storage; - a null `CheckoutForWrite` size, and a `CheckinForWrite` past the end; - a zero-byte `Write` into a full buffer; - a null or empty `Peek`; - read pointers that disagree with the data size. The debt file drops the 9 "signature unknown" entries. ### Tested Linux (CachyOS, GCC 16.2, Release): `ctest --test-dir build -R 'np_common|public_headers' --output-on-failure`, 70/70 passed. `TestRingBuf` in `GuestNpCommonRuntime.cpp` covers: - a write that does not fit, an in-order read, a write and a peek across the wrap; - both error codes, a null read buffer, and the checkout/checkin pairs; - `RingBufMemory` on a memory heap: `Init`, a wrap, and `Expand` keeping the order of wrapped data; - expanding a full buffer, then writing to it (the module's result); - the deleting destructor called through the vtable. **Comparison against the firmware code:** I relinked the 13.60 module with this repo's relinker and ran both classes under unicorn (x86-64 emulation on a PC, not a console). The allocator callbacks and `printf`/`abort` (reached through the module's `sceNpPanic`) were bound to recording handlers. - **Corpus:** 1,500 random sequences plus 4 fixed `Expand` sequences (full with the pointers meeting at 1, full at 0, wrapped but not full, and empty), half of them `RingBuf` on caller storage and half `RingBufMemory` on a recording allocator (with injected allocation failures), 31,279 operations in all. Buffer sizes run from 1 to 64. The operations are writes and reads of random sizes (including 0 and more than fits, and a null destination), peeks, the checkout/checkin pairs (with checkins up to one past the block), `Clear`, the size queries, `Expand`, re-`Init` and `Destroy`. A firmware assertion is recorded as `panic` and ends the sequence; there were 441. - **What was recorded after each operation:** the result, the bytes read or peeked (plus 4 guard bytes), the object (vtable, which buffer, both pointers as offsets, both sizes), the buffer contents, and every allocator release. - **Result:** replaying the same sequences through this implementation gives **0 mismatches**, every `panic` included. 29 corrupted expectations give 29 mismatches. - **Not in the corpus:** the constructors, destructors, `ctor` and `dtor`. I ran those separately on an object behind a `sce::np::Object` header, and they match: `D0` frees the header block, and `RingBufMemory`'s destructors release `buf` first. - **IsFull / IsInit:** the replay computes these two from the fields, because they belong to #12823. The generator and harness are `np_ringbuf_make_cases.py` / `np_ringbuf_replay.cpp` in https://gist.github.com/hypermoist/1834cf221fd737cdb4cca272cc1156d1. The gist has no module or recorded output. 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: #12839. It removes stubs next to the ones #12823 and #12825 remove, so whichever lands later needs a trivial rebase; I will do it on this side. - [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)
MarcZX10 commented 2026-10-29 12:47:02 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T12:47:02Z.

Review: CHANGES_REQUESTED


Reviewed — changes requested

The full-buffer expansion path loses the write boundary, so a subsequent valid write corrupts the queue and the next read throws.

What I ran

Reviewed head 56551447a9832cf004baa8bc1ae9c2cbec172424 against main at 5454cd2e455994d992aca39335ce60507eeda1eb; git merge-tree --write-tree was clean (54933ccfa14a16254bcfd74c62637a621b67f78e). Local environment: Debian Linux x86_64, GCC 12.2.0.

Commands:

git merge-tree --write-tree upstream/main HEAD
git diff --check upstream/main...HEAD
python3 tools/check_conventions.py --base upstream/main
g++ -std=c++20 -Icore/libs /tmp/ringbuf_expand_repro.cpp core/libs/prx/libSceNpCommon/RingBuf.cpp -o /tmp/ringbuf_expand_repro
/tmp/ringbuf_expand_repro

The standalone harness linked the submitted RingBuf.cpp with malloc/realloc/free callbacks and a no-op object-delete stub. Its operations were: initialize capacity 4; write ABCD; read one byte; write E to fill the ring and make the pointers meet at offset 1; expand by 2; write FG; then read the six queued bytes. The expected FIFO data after the first read is BCDEFG.

Results

Check Result
Merge preview Pass; clean tree 54933ccfa14a16254bcfd74c62637a621b67f78e
git diff --check Pass; no output
Conventions Pass
Focused full-buffer expand/write/read reproduction Fail; read throws after the subsequent write
Hosted Windows build/test In progress at the time of this review
Hosted Linux build/test Skipped by workflow
Raw local output
All conventions checks passed.
after expand: size=4 capacity=6 readOffset=1 writeOffset=1 firstRead=A
read threw: sce::np::RingBuf::CheckoutForRead: the data size does not match the pointers

Negative control

Assertion Change to code under test Did the new test fail?
A write after expanding a full ring preserves the queued bytes and FIFO order No mutation/negative-control variant was run Not exercised

Findings

Blocking

In Expand, when a full ring has equal read/write pointers at a nonzero offset, the offsets remain equal after the capacity increases. The next WriteBlock treats any equal-pointer, non-full state as empty and resets both pointers to buf. That writes over queued bytes; the read then reaches the internal size/pointer assertion. The deterministic sequence above reproduces this on the submitted head. The PR's test only expands a partially occupied wrapped ring, so it does not cover the equal-pointer case. See WriteBlock and its pointer reset, Expand, and the current expansion test.

Please add this full-buffer sequence as a deterministic test and compare it against the firmware module. If the module preserves the FIFO data, adjust the pointer handling so the expanded free span can be written without moving or overwriting queued bytes. If the module itself exhibits this behavior, include the recorded result and document the limitation in technical debt; the current PR does not identify it as a gap, and its test currently implies that expansion preserves usable capacity and data order.

Non-blocking

The PR reports a 1,500-sequence firmware comparison under Unicorn, but its generator/replay files are external and the module/output are not attached. Including the targeted equal-pointer case in the reported comparison would make this edge result easier to verify.

Sources

Not verified

  • The hosted Windows job was still in progress; Linux and console checks did not run in hosted CI.
  • I did not run the full CMake build/CTest suite or compare this exact sequence against firmware on a console.

To get this to a good state

Please add the deterministic full-buffer case, establish its firmware result, and either preserve the FIFO on the new capacity or record and test the confirmed firmware limitation. I will rerun the same local commands and recheck the hosted jobs on the updated head.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5697905932 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12852#pullrequestreview-5697905932). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-29T12:47:02Z. **Review:** CHANGES_REQUESTED --- # Reviewed — changes requested The full-buffer expansion path loses the write boundary, so a subsequent valid write corrupts the queue and the next read throws. ## What I ran Reviewed head `56551447a9832cf004baa8bc1ae9c2cbec172424` against `main` at `5454cd2e455994d992aca39335ce60507eeda1eb`; `git merge-tree --write-tree` was clean (`54933ccfa14a16254bcfd74c62637a621b67f78e`). Local environment: Debian Linux x86_64, GCC 12.2.0. Commands: ```sh git merge-tree --write-tree upstream/main HEAD git diff --check upstream/main...HEAD python3 tools/check_conventions.py --base upstream/main g++ -std=c++20 -Icore/libs /tmp/ringbuf_expand_repro.cpp core/libs/prx/libSceNpCommon/RingBuf.cpp -o /tmp/ringbuf_expand_repro /tmp/ringbuf_expand_repro ``` The standalone harness linked the submitted `RingBuf.cpp` with malloc/realloc/free callbacks and a no-op object-delete stub. Its operations were: initialize capacity 4; write `ABCD`; read one byte; write `E` to fill the ring and make the pointers meet at offset 1; expand by 2; write `FG`; then read the six queued bytes. The expected FIFO data after the first read is `BCDEFG`. ## Results | Check | Result | |---|---| | Merge preview | Pass; clean tree `54933ccfa14a16254bcfd74c62637a621b67f78e` | | `git diff --check` | Pass; no output | | Conventions | Pass | | Focused full-buffer expand/write/read reproduction | Fail; read throws after the subsequent write | | Hosted Windows build/test | In progress at the time of this review | | Hosted Linux build/test | Skipped by workflow | <details> <summary>Raw local output</summary> ```text All conventions checks passed. after expand: size=4 capacity=6 readOffset=1 writeOffset=1 firstRead=A read threw: sce::np::RingBuf::CheckoutForRead: the data size does not match the pointers ``` </details> ## Negative control | Assertion | Change to code under test | Did the new test fail? | |---|---|---| | A write after expanding a full ring preserves the queued bytes and FIFO order | No mutation/negative-control variant was run | Not exercised | ## Findings ### Blocking In `Expand`, when a full ring has equal read/write pointers at a nonzero offset, the offsets remain equal after the capacity increases. The next `WriteBlock` treats any equal-pointer, non-full state as empty and resets both pointers to `buf`. That writes over queued bytes; the read then reaches the internal size/pointer assertion. The deterministic sequence above reproduces this on the submitted head. The PR's test only expands a partially occupied wrapped ring, so it does not cover the equal-pointer case. See [WriteBlock and its pointer reset](https://github.com/boykopovar/AnyPS5/blob/56551447a9832cf004baa8bc1ae9c2cbec172424/core/libs/prx/libSceNpCommon/RingBuf.cpp#L51-L59), [Expand](https://github.com/boykopovar/AnyPS5/blob/56551447a9832cf004baa8bc1ae9c2cbec172424/core/libs/prx/libSceNpCommon/RingBuf.cpp#L269-L284), and [the current expansion test](https://github.com/boykopovar/AnyPS5/blob/56551447a9832cf004baa8bc1ae9c2cbec172424/core/libs/tests/GuestNpCommonRuntime.cpp#L389-L396). Please add this full-buffer sequence as a deterministic test and compare it against the firmware module. If the module preserves the FIFO data, adjust the pointer handling so the expanded free span can be written without moving or overwriting queued bytes. If the module itself exhibits this behavior, include the recorded result and document the limitation in technical debt; the current PR does not identify it as a gap, and its test currently implies that expansion preserves usable capacity and data order. ### Non-blocking The PR reports a 1,500-sequence firmware comparison under Unicorn, but its generator/replay files are external and the module/output are not attached. Including the targeted equal-pointer case in the reported comparison would make this edge result easier to verify. ## Sources - [Submitted `RingBuf.cpp`, pinned to `56551447a9832cf004baa8bc1ae9c2cbec172424`](https://github.com/boykopovar/AnyPS5/blob/56551447a9832cf004baa8bc1ae9c2cbec172424/core/libs/prx/libSceNpCommon/RingBuf.cpp) - [Submitted runtime test, pinned to `56551447a9832cf004baa8bc1ae9c2cbec172424`](https://github.com/boykopovar/AnyPS5/blob/56551447a9832cf004baa8bc1ae9c2cbec172424/core/libs/tests/GuestNpCommonRuntime.cpp) ## Not verified - The hosted Windows job was still in progress; Linux and console checks did not run in hosted CI. - I did not run the full CMake build/CTest suite or compare this exact sequence against firmware on a console. ## To get this to a good state Please add the deterministic full-buffer case, establish its firmware result, and either preserve the FIFO on the new capacity or record and test the confirmed firmware limitation. I will rerun the same local commands and recheck the hosted jobs on the updated head.
CnRJay commented 2026-11-01 19:54:11 +00:00 (Migrated from github.com)

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

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:5729937525 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12852#pullrequestreview-5729937525). Originally posted by [CnRJay](https://github.com/CnRJay) on 2026-11-01T19:54:11Z. **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.
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!12852
No description provided.