fix(libSceNKWebKit): copy WTF string value guest pointers safely #22470

Merged
domx4q merged 1 commit from upstream-pr/22470 into main 2026-11-27 15:41:13 +00:00
domx4q commented 2026-11-17 17:28:57 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by domx4q on 2026-11-17T17:28:57Z.


What

WtfValues.cpp in libSceNKWebKit read and wrote guest objects directly in the string value exports. They now copy guest memory in, compute on host copies and copy results out, following the pattern of the merged WTF::MediaTime and WebCore::Region fixes in this library (GuestCopyIn_nid_no_patch, GuestCopyOut_nid_no_patch, failure through NotImplementedAt_nid_no_patch).

  • StringImpl::replace(char16_t, const LChar*, unsigned): the guest replacement bytes are checked readable in 4 KiB chunks before the result string is allocated. An oversized repStrLength with a short guest buffer now fails before any allocation, where it used to allocate up to 2 GiB and then read past the buffer. The bytes are read once into the first match position of the result, and later matches copy from there. 8-bit and 16-bit results are byte-identical to before.
  • StringView::SplitResult::Iterator::findNextSubstring and operator++: the iterator and its SplitResult are copied in. Only position, length and isDone are written back, so the iterator padding stays as before. The scan moved into a host helper.
  • String::split, splitAllowingEmptyEntries, charactersWithNullTermination, toFloat, toDouble, isolatedCopy() const & and isolatedCopy() &&: the StringImpl* of the guest String is copied in. toFloat and toDouble parse into a host ok flag and copy it out once, so a non-null ok gets the same byte as before. isolatedCopy() && clears the guest String through GuestCopyOut_nid_no_patch before it hands over the reference, so a read-only String keeps its reference and refcount.

An unreadable or unwritable guest pointer now fails through NotImplementedAt_nid_no_patch instead of faulting. Null this and null replacement still throw std::invalid_argument as before.

I split the file into two PRs by topic. WTF::Persistence::Encoder/Decoder and WTF::URL from the same file are in a separate PR (fix/nkwebkit-wtf-persistence-url-guest-pointers).

False positives left unchanged (still listed by tools/guest_pointer_audit.py libSceNKWebKit):

  • StringImpl::replace(char16_t, char16_t) and StringImpl::replace(char16_t, const LChar*, unsigned), parameter self: StringImpl objects are allocated by the library (StringImpl::create, createUninitialized). They are host objects, like Region::Shape in the merged Region fix.
  • SplitResult::Iterator::operator++, self (dereference): this is the return *self; of the reference return, and nothing is read. The merged MediaTime::operator= keeps the same hit.

Characters behind a StringView (the SplitResult view) are read the same way as in every other StringView export of this library, and I did not change that here.

No debt change: no debt entry describes the old behaviour.

Tested

Arch Linux, GCC, Release (-DBUILD_TESTING=ON).

  • New nkwebkit_wtfstringvaluesguestpointers (tests/WtfStringValuesGuestPointers.cpp, under 0.1 s):
    • every changed export with an unreadable this (0x10) and with an unwritable ok;
    • a SplitResult pointer that cannot be read, and a read-only iterator page (left unchanged);
    • a read-only String passed to isolatedCopy() && (keeps its impl and refcount);
    • an unreadable replacement, a replacement that ends 1 byte before a PROT_NONE page, and an oversized count (0x10000000) over a 3-byte buffer;
    • a 12287-byte replacement spread over three pages (chunk boundaries, repeated match);
    • valid results from read-only and page-backed guest objects.
  • ctest --test-dir build -R 'public_headers|nkwebkit' -j 4: 187/187 passed (includes the existing nkwebkit_wtfvalues behaviour tests).
  • Mutation checks, each restored afterwards:
    • LoadStringImpl reading string->impl directly: segfault;
    • CopyGuestLatin1 using memcpy instead of GuestCopyIn_nid_no_patch: segfault;
    • the iterator store writing *self = iterator directly: segfault.
  • python3 tools/progress.py --root . --module libSceNKWebKit: 3308 done on both origin/main and this branch.
  • python3 tools/check_conventions.py --base origin/main: all checks passed.

Overlap

  • python3 tools/pr_overlap.py --names for all 33 WtfValues.cpp exports listed by the audit: all implemented on main in libSceNKWebKit, no open PR edits them.
  • python3 tools/pr_overlap.py --branch fix/nkwebkit-wtf-string-values-guest-pointers: no overlap with open pull requests.

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 and the licence notice of code adapted from upstream (see AGENTS.md)
  • 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
  • AI-assisted: yes (Claude Code)
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5361756954 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/22470). Originally posted by [domx4q](https://github.com/domx4q) on 2026-11-17T17:28:57Z. --- ### What `WtfValues.cpp` in libSceNKWebKit read and wrote guest objects directly in the string value exports. They now copy guest memory in, compute on host copies and copy results out, following the pattern of the merged `WTF::MediaTime` and `WebCore::Region` fixes in this library (`GuestCopyIn_nid_no_patch`, `GuestCopyOut_nid_no_patch`, failure through `NotImplementedAt_nid_no_patch`). - `StringImpl::replace(char16_t, const LChar*, unsigned)`: the guest replacement bytes are checked readable in 4 KiB chunks before the result string is allocated. An oversized `repStrLength` with a short guest buffer now fails before any allocation, where it used to allocate up to 2 GiB and then read past the buffer. The bytes are read once into the first match position of the result, and later matches copy from there. 8-bit and 16-bit results are byte-identical to before. - `StringView::SplitResult::Iterator::findNextSubstring` and `operator++`: the iterator and its `SplitResult` are copied in. Only `position`, `length` and `isDone` are written back, so the iterator padding stays as before. The scan moved into a host helper. - `String::split`, `splitAllowingEmptyEntries`, `charactersWithNullTermination`, `toFloat`, `toDouble`, `isolatedCopy() const &` and `isolatedCopy() &&`: the `StringImpl*` of the guest `String` is copied in. `toFloat` and `toDouble` parse into a host `ok` flag and copy it out once, so a non-null `ok` gets the same byte as before. `isolatedCopy() &&` clears the guest `String` through `GuestCopyOut_nid_no_patch` before it hands over the reference, so a read-only `String` keeps its reference and refcount. An unreadable or unwritable guest pointer now fails through `NotImplementedAt_nid_no_patch` instead of faulting. Null `this` and null replacement still throw `std::invalid_argument` as before. I split the file into two PRs by topic. `WTF::Persistence::Encoder`/`Decoder` and `WTF::URL` from the same file are in a separate PR (`fix/nkwebkit-wtf-persistence-url-guest-pointers`). False positives left unchanged (still listed by `tools/guest_pointer_audit.py libSceNKWebKit`): - `StringImpl::replace(char16_t, char16_t)` and `StringImpl::replace(char16_t, const LChar*, unsigned)`, parameter `self`: `StringImpl` objects are allocated by the library (`StringImpl::create`, `createUninitialized`). They are host objects, like `Region::Shape` in the merged `Region` fix. - `SplitResult::Iterator::operator++`, `self (dereference)`: this is the `return *self;` of the reference return, and nothing is read. The merged `MediaTime::operator=` keeps the same hit. Characters behind a `StringView` (the `SplitResult` view) are read the same way as in every other `StringView` export of this library, and I did not change that here. No debt change: no debt entry describes the old behaviour. ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> Arch Linux, GCC, Release (`-DBUILD_TESTING=ON`). - New `nkwebkit_wtfstringvaluesguestpointers` (`tests/WtfStringValuesGuestPointers.cpp`, under 0.1 s): - every changed export with an unreadable `this` (`0x10`) and with an unwritable `ok`; - a `SplitResult` pointer that cannot be read, and a read-only iterator page (left unchanged); - a read-only `String` passed to `isolatedCopy() &&` (keeps its impl and refcount); - an unreadable replacement, a replacement that ends 1 byte before a `PROT_NONE` page, and an oversized count (`0x10000000`) over a 3-byte buffer; - a 12287-byte replacement spread over three pages (chunk boundaries, repeated match); - valid results from read-only and page-backed guest objects. - `ctest --test-dir build -R 'public_headers|nkwebkit' -j 4`: 187/187 passed (includes the existing `nkwebkit_wtfvalues` behaviour tests). - Mutation checks, each restored afterwards: - `LoadStringImpl` reading `string->impl` directly: segfault; - `CopyGuestLatin1` using `memcpy` instead of `GuestCopyIn_nid_no_patch`: segfault; - the iterator store writing `*self = iterator` directly: segfault. - `python3 tools/progress.py --root . --module libSceNKWebKit`: 3308 done on both `origin/main` and this branch. - `python3 tools/check_conventions.py --base origin/main`: all checks passed. ### Overlap - `python3 tools/pr_overlap.py --names` for all 33 `WtfValues.cpp` exports listed by the audit: all implemented on `main` in libSceNKWebKit, no open PR edits them. - `python3 tools/pr_overlap.py --branch fix/nkwebkit-wtf-string-values-guest-pointers`: no overlap with open pull requests. ### 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) and the licence notice of code adapted from upstream (see AGENTS.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 - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes (Claude Code)
PrivacyOnion commented 2026-11-17 17:33:50 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-17T17:33:50Z.

Review: APPROVED


Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 8e2f06fa5f:

  • Conventions: tools/check_conventions.py passed.
  • Build: nkwebkit_wtfstringvaluesguestpointers_tests built cleanly.
  • CTest (nkwebkit_wtfstringvaluesguestpointers):
    1/1 Test #4526: nkwebkit_wtfstringvaluesguestpointers ...   Passed    0.05 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libSceNKWebKit/src/WtfValues.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #4526: nkwebkit_wtfstringvaluesguestpointers ...***Exception: SegFault  0.62 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified GuestCopyIn_nid_no_patch / GuestCopyOut_nid_no_patch semantics and error handling via NotImplementedAt_nid_no_patch across StringImpl::replace, findNextSubstring, operator++, split, splitAllowingEmptyEntries, charactersWithNullTermination, toFloat, toDouble, and isolatedCopy
    • Checked StringImpl::replace chunking logic and first match index caching in AppendReplacement against buffer overflow and re-copying correctness
    • Verified SplitResultIterator state slicing offset and size calculations (splitIteratorStateOffset and splitIteratorStateBytes) matching position, length, and isDone fields
    • Audited String::isolatedCopy rvalue overload local String emulation (&impl) and null-out writeback via GuestCopyOut_nid_no_patch
    • Confirmed absence of comments, special-cased title IDs, and verified clean tests with memory protection page checks in WtfStringValuesGuestPointers.cpp

Looks Good To Me

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5943450855 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/22470#pullrequestreview-5943450855). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-17T17:33:50Z. **Review:** APPROVED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `8e2f06fa5f`: - **Conventions**: `tools/check_conventions.py` passed. - **Build**: `nkwebkit_wtfstringvaluesguestpointers_tests` built cleanly. - **CTest** (`nkwebkit_wtfstringvaluesguestpointers`): ``` 1/1 Test #4526: nkwebkit_wtfstringvaluesguestpointers ... Passed 0.05 sec 100% tests passed, 0 tests failed out of 1 ``` - **Negative control**: with `core/libs/prx/libSceNKWebKit/src/WtfValues.cpp` reverted to `main` and the new tests kept, the suite fails: ``` 1/1 Test #4526: nkwebkit_wtfstringvaluesguestpointers ...***Exception: SegFault 0.62 sec 0% tests passed, 1 tests failed out of 1 ``` Restoring the change makes it pass again. - **Code reading**: - Verified GuestCopyIn_nid_no_patch / GuestCopyOut_nid_no_patch semantics and error handling via NotImplementedAt_nid_no_patch across StringImpl::replace, findNextSubstring, operator++, split, splitAllowingEmptyEntries, charactersWithNullTermination, toFloat, toDouble, and isolatedCopy - Checked StringImpl::replace chunking logic and first match index caching in AppendReplacement against buffer overflow and re-copying correctness - Verified SplitResultIterator state slicing offset and size calculations (splitIteratorStateOffset and splitIteratorStateBytes) matching position, length, and isDone fields - Audited String::isolatedCopy rvalue overload local String emulation (&impl) and null-out writeback via GuestCopyOut_nid_no_patch - Confirmed absence of comments, special-cased title IDs, and verified clean tests with memory protection page checks in WtfStringValuesGuestPointers.cpp Looks Good To Me
MarcZX10 commented 2026-11-23 07:05:01 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T07:05:01Z.

Review: APPROVED


Reviewed — looks good

Nothing blocks this change; the reviewed code supports merging.

What I ran

Reviewed head 8e2f06fa5f8cb54042bfe1f4fa781d709727ebb4. No commands or tests were run; the author-reported test results were not independently verified. Read description.md, commits.md, manifest.json, diff.patch, and the complete text of both changed files. Also inspected targeted guest-copy, string helper, and CMake test-discovery code. Both changed files were included in the review folder; no changed files were excluded.

Results

Check Result Note
Code review passed Both changed files read
Tests not run Results in the description are author-reported
Build and precheck not run Not run during this review

Findings

Blocking

None.

Non-blocking

None.

Not verified

The reported test, mutation-check, progress, and convention-check results were not independently run. Console behavior and other operating systems were not verified.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6017653845 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/22470#pullrequestreview-6017653845). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-23T07:05:01Z. **Review:** APPROVED --- # Reviewed — looks good Nothing blocks this change; the reviewed code supports merging. ## What I ran Reviewed head `8e2f06fa5f8cb54042bfe1f4fa781d709727ebb4`. No commands or tests were run; the author-reported test results were not independently verified. Read `description.md`, `commits.md`, `manifest.json`, `diff.patch`, and the complete text of both changed files. Also inspected targeted guest-copy, string helper, and CMake test-discovery code. Both changed files were included in the review folder; no changed files were excluded. ## Results | Check | Result | Note | |---|---|---| | Code review | passed | Both changed files read | | Tests | not run | Results in the description are author-reported | | Build and precheck | not run | Not run during this review | ## Findings ### Blocking None. ### Non-blocking None. ## Not verified The reported test, mutation-check, progress, and convention-check results were not independently run. Console behavior and other operating systems were not verified. ## To get this to a good state Nothing is required.
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!22470
No description provided.