fix(libSceNKWebKit): copy WTF::Persistence and WTF::URL guest pointers safely #22472
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/22472"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by domx4q on 2026-11-17T17:29:02Z.
What
WtfValues.cppin libSceNKWebKit read and wrote guestWTF::Persistence::Encoder,WTF::Persistence::DecoderandWTF::URLobjects directly. They now copy guest memory in, compute on host copies and copy results out. This follows the mergedWTF::MediaTimeandWebCore::Regionfixes in this library:GuestCopyIn_nid_no_patch,GuestCopyOut_nid_no_patch,GuestWritable_nid_no_patch, and failure throughNotImplementedAt_nid_no_patch.Encoderconstructor, destructor,encodeChecksumand the ten numericoperator<<exports:buffer,capacity,size) and the SHA-1 state are copied in once per call. Before that, the whole 4216-byteEncoderis checked writable.GuestCopyOut_nid_no_patchper call. That buffer is the guest inline buffer, or the library'sfastMallocbuffer after growth.GuestCopyIn_nid_no_patch. The newbufferandcapacity(with the unchangedsize) are written to the guest header before the old buffer is freed; if that write fails, the new buffer is freed and the old one stays in place. A later failure in the same call therefore leaves the header owning a live buffer that holds the old bytes.GuestCopyOut_nid_no_patchand hashed from the host value.bufferpointer.StringandCStringcoders copy theString/CStringpointer, theStringImpl/CStringBufferheader and the whole payload into host memory withGuestCopyIn_nid_no_patchbefore touching the encoder. Only then do they load the encoder once, append length, 8-bit flag (Stringonly) and payload, and store it once. A payload or header that cannot be read fails with the encoder header, buffer and SHA-1 state unchanged.Decoder::bufferIsLargeEnoughToContainandverifyChecksum: theDecoderis copied in. The 20 checksum bytes are read from the guest data buffer withGuestCopyIn_nid_no_patch, and the updatedDecoderis written back once.URL::protocolIs(const char*): the guest C string is read in 4 KiB chunks that never cross a page, and the host allocation grows only by bytes already read. The guestURLis copied into a hostURLwithGuestCopyIn_nid_no_patchbefore theStringViewoverload runs. Before, it calledstrlenon the guest pointer and passed the guestURLstraight to the overload.URL::removeQueryAndFragmentIdentifier,hostAndPort,isMatchingDomain,protocolHostAndPort,userandpassword: the 40-byteURLis copied in, and the host copy goes to thehost,encodedUserandencodedPasswordaccessors.removeQueryAndFragmentIdentifierreleases the old string only after the truncated URL is written back. A read-only URL keeps its string and refcount.Encoded bytes, checksums and URL results for valid inputs are unchanged. The test compares a page-backed encoder against a host encoder byte for byte, including growth past the 4096-byte inline buffer. Null
thisstill throwsstd::invalid_argument, and a nullEncoderin the destructor is still a no-op.The string value exports of the same file are in a separate PR (
fix/nkwebkit-wtf-string-values-guest-pointers). The two branches touch different hunks and merge cleanly (git merge-tree).False positives left unchanged:
tools/guest_pointer_audit.py libSceNKWebKitstill lists the tenEncoder::operator<<exports asself (dereference). That hit is thereturn *self;of the reference return, and nothing is read. The mergedMediaTime::operator=keeps the same hit.StringImplandCStringBufferobjects behindURLare allocated by the library and stay host objects, likeRegion::Shapein the mergedRegionfix; theStringandCStringcoders read theirs withGuestCopyIn_nid_no_patch.No debt change: no debt entry describes the old behaviour.
Tested
Arch Linux, GCC, Release (
-DBUILD_TESTING=ON).nkwebkit_wtfpersistenceurlguestpointers(tests/WtfPersistenceUrlGuestPointers.cpp, under 0.1 s):this(0x10);Encoder,DecoderandURLpages, checked unchanged after the failure;Decoderwhose data pointer cannot be read;PROT_NONEpage without a terminator, and one that crosses a page boundary;protocolIs(const char*)withthison aPROT_NONEpage, with aURLthat runs into aPROT_NONEpage, and with a validURLthat ends exactly at a page boundary;StringandCStringencodes, each with no prefix, a short prefix and a 5000-byte prefix that already grew the buffer: an 8-bitStringpayload of 5000 and 3 bytes and a 16-bit one of 3 characters on aPROT_NONEpage, aStringwhoseStringImplis on aPROT_NONEpage, aCStringpayload of 5000 and 3 bytes running into aPROT_NONEpage, and aCStringwhose buffer header is on aPROT_NONEpage. The whole 4216-byte guestEncoderand its buffer are byte-identical after the failure, and a followingStringencode andoperator<<give the same bytes and SHA-1 state as a fresh host encoder that saw only the prefix and those valid encodes;URLresults from a read-only page;removeQueryAndFragmentIdentifieron a writable page.ctest --test-dir build -R 'public_headers|nkwebkit' -j 4: 187/187 passed (includes the existingnkwebkit_wtfvaluesbehaviour tests).EncoderAppendBytes, hashing the payload before copying it: segfault;String/CStringcoders as of709b054f57(length and 8-bit flag appended before the payload is read):check failed at line 120(wrong failing export), and with only the failed-encode tests run,check failed at line 167(guestEncoderchanged after the failed encode);LoadEncoderusingmemcpy: segfault;LoadURLreading*sourcedirectly: segfault;verifyChecksumreading the checksum bytes withmemcpy: segfault;protocolIscopying the guest string withstd::stringassignment: segfault;protocolIs(const char*)passing the guestURLto theStringViewoverload without a host copy: segfault.python3 tools/progress.py --root . --module libSceNKWebKit: 3308 done on bothorigin/mainand this branch.python3 tools/check_conventions.py --base origin/main: all checks passed.Overlap
python3 tools/pr_overlap.py --namesfor all 33WtfValues.cppexports listed by the audit: all implemented onmainin libSceNKWebKit, no open PR edits them.python3 tools/pr_overlap.py --branch fix/nkwebkit-wtf-persistence-url-guest-pointers: only #24136, which is stacked on this PR and carries this branch'stests/WtfPersistenceUrlGuestPointers.cpp; no other overlap.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)Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-17T17:33:49Z.
Review: APPROVED
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against
5b71407663:tools/check_conventions.pypassed.nkwebkit_wtfpersistenceurlguestpointers_testsbuilt cleanly.nkwebkit_wtfpersistenceurlguestpointers):core/libs/prx/libSceNKWebKit/src/WtfValues.cppreverted tomainand the new tests kept, the suite fails: Restoring the change makes it pass again.Looks Good To Me
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T07:06:12Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: copy the guest
URLinto host memory before delegating from theprotocolIs(const char*)overload.What I ran
Reviewed head
5b7140766399c64194cc396b5a6c614906c169f6. I did not run commands or tests; the PR description reports the author’s test results.Results
Findings
Blocking
core/libs/prx/libSceNKWebKit/src/WtfValues.cpp:683passes the original guestselfpointer to theStringViewoverload. That overload callsChecked(self), which accesses the URL object directly, so an unreadable guest URL can still fault instead of being handled throughGuestCopyIn_nid_no_patch. Load the URL into a host copy and pass that copy to the overload. The new tests cover an unreadable protocol string, but pass a host URL object, so they do not catch this case. Changed call at the reviewed commit · Delegated overloadNon-blocking
None.
Sources
Read
review/description.md,review/commits.md,review/manifest.json,review/diff.patch, and both changed files:core/libs/prx/libSceNKWebKit/src/WtfValues.cppandcore/libs/prx/libSceNKWebKit/tests/WtfPersistenceUrlGuestPointers.cpp. Also read the delegated overload incore/libs/prx/libSceNKWebKit/src/WtfString.cpp.Not verified
Tests, builds, and runtime behavior were not run in this review. The description reports tests on Arch Linux with GCC Release, including 187 passing CTest cases and mutation checks; these results were not independently verified. No changed files were excluded from review.
To get this to a good state
Copy the guest URL into a host-side
URLbefore calling theStringViewoverload, and add coverage for an unreadableselfpointer to this overload. Rerun the reported targeted test and CTest checks on the updated head.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T10:57:26Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: preserve the encoder's updated state when an append fails after growing its buffer.
What I ran
3517150f9390a047060f41a27c0a79765e046f07using the prepared diff andrepo_read.pyat that pinned head.Results
Findings
Blocking
core/libs/prx/libSceNKWebKit/src/WtfValues.cpp:336:EncoderAppendNumcan grow the buffer and replace/free the old one inEncoderEnsure, then return beforeStoreEncoderif the guest copy-out of the value fails. The guest header still points at the old buffer, which may already have been freed, while the new allocation is leaked. Subsequent use or destruction of that encoder can access a dangling pointer. Store the updated buffer/capacity state as soon as growth succeeds, or otherwise ensure failure leaves the guest header valid and frees any new allocation.Non-blocking
None.
Not verified
review/description.md,review/commits.md,review/manifest.json, the relevant ranges ofreview/diff.patch,WtfValues.cpp, andWtfValueExports.hpp. The manifest lists two changed files and marks both included; the test source was present in the prepared diff, but its full source could not be reliably inspected due to truncated tool output.To get this to a good state
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T11:24:22Z.
Review: COMMENTED
Reviewed — no blocking findings
Nothing blocks this; the points below are optional.
What I ran
Reviewed head
bcb24a8dd206987dff56b819b702f2d95ab82b16using the prepared diff and the pinned repository reader. No commands or tests were run by me; test results below are author-reported.Results
Findings
Blocking
None.
Non-blocking
core/libs/prx/libSceNKWebKit/src/WtfValues.cpp:367—CopyGuestCStringderives its chunk boundary using a fixed 4096-byte modulus. If the host page size differs, a chunk can cross a page boundary and fail on an otherwise valid NUL-terminated string. Query or use the actual host page boundary when choosing each chunk.Not verified
WtfValues.cppwas read in the changed implementation ranges, along with its ABI definitions, relevant helper declarations/implementation,WtfString.cppprotocol behavior, and the test discovery configuration.review/description.md,review/commits.md,review/manifest.json, andreview/diff.patchwere read; no files were excluded by rule according to the manifest.To get this to a good state
Nothing is required. Optional: calculate
CopyGuestCStringchunk sizes using the host page size so reads remain within a page across supported hosts.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T15:30:19Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: make string and C string encoding leave the encoder unchanged when their payload cannot be read.
What I ran
Reviewed head
709b054f579ad9f3f6d8a88d6353109dd8ab7c95against the prepared diff. No tests or builds were run; the description reports author-run checks.Results
Findings
Blocking
core/libs/prx/libSceNKWebKit/src/WtfValues.cpp:674-676: String encoding appends the length and 8-bit flag through separate encoder calls before attempting to copy the payload. If payloadGuestCopyInfails, the function throws after those prefix bytes and their SHA-1 state have already been committed; a retry or subsequent encode therefore operates on a partially encoded value. The CString encoder has the same ordering at lines 684-688. Validate/copy the payload before committing the prefix, or roll back encoder state and bytes when the payload copy fails.Non-blocking
None.
Not verified
To get this to a good state
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T17:22:56Z.
Review: COMMENTED
Reviewed — comments
The guest pointer handling is substantially covered by new tests, but the
Decoderbounds check can perform undefined pointer arithmetic on malformed guest state.What I ran
Reviewed head
646f74a8a2f707fabc56cecfe98bd3ec705cbea6using the prepared diff andrepo_read.pytargeted reads. No tests or build commands were run.Results
Findings
Blocking
None.
Non-blocking
core/libs/prx/libSceNKWebKit/src/WtfValues.cpp:353formsbufferData + bufferSizebefore establishing that the guest-provided size is within a valid object range. If the size is invalid or the pointer is near the address-space limit, this pointer arithmetic is undefined behavior; the attempted bounds check itself is not safe for malformed state. Consider validating the range using checked integer address arithmetic before forming pointers, and returning false when the range overflows.Not verified
The build, tests, and author-reported runs were not independently verified. The prepared diff and targeted source reads were reviewed; other repository files listed in
manifest.jsonwere not read in full.To get this to a good state
Nothing is required. Optional: make the
DecoderHasRoomrange validation safe for malformed pointers and sizes.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T18:09:41Z.
Review: DISMISSED
Reviewed — changes requested
Changes are required before merge: make failed
Encoderappends leave both the guest header and buffer state consistent.What I ran
Reviewed head
2880e0cc618d9757bcf07ee17668fbcb7a6a3bab; no commands or tests were run. Readdescription.md,commits.md,manifest.json,diff.patch, and the full changed source and test files through the reader.files.jsonwas unavailable, so excluded files and the complete reviewed-file list could not be confirmed.Results
files.jsonunavailableFindings
Blocking
core/libs/prx/libSceNKWebKit/src/WtfValues.cpp:332—EncoderWritecopies payload bytes into the guest buffer before updating the host-side SHA-1 and size. IfGuestCopyOut_nid_no_patchpartially writes and then reports failure, the helper returns false without committing the new size or hash; the guest buffer can nevertheless contain changed bytes within the unused region, violating the claimed unchanged-on-failure behavior and making a retry or subsequent append overwrite those bytes. The tested unreadable cases may fail before copying any bytes, but the implementation does not establish atomicity for a copy-out failure. Stage writes so a failed copy cannot alter the current buffer, or otherwise restore affected bytes before returning.Non-blocking
None.
Sources
core/libs/prx/libSceNKWebKit/src/WtfValues.cpp:331-336.core/libs/prx/libSceNKWebKit/tests/WtfPersistenceUrlGuestPointers.cpp:163-168.Not verified
Tests and build were not run. The author reports test runs in the PR description, but their output was not available here. The
files.jsoninventory was unavailable, so files excluded by preparation rules and whether all reviewed files were read are not verified. No behavior beyond the two changed files read was assessed.To get this to a good state
Make
EncoderWritefailure-safe if guest buffer copy-out can partially modify its destination, then rerun the targeted guest-pointer tests and the reportedctestcommand on the updated head.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T18:23:24Z.
Review: COMMENTED
Reviewed — no blocking findings
The inspected changes have no verified blocking defect; I did not run the reported checks, so a formal approval is not justified.
What I ran
Reviewed head
2b449290332d9f1a5636fd58ef93fb3d5283cd5d. No commands were run; this session provides the pinned reader but no shell. The description reports Arch Linux/GCC tests and checks; those are author-reported, not runs performed here.Results
Negative control
Not run; the reported mutation checks were not independently performed.
Findings
Blocking
None verified.
Non-blocking
None.
Sources
Reviewed
core/libs/prx/libSceNKWebKit/src/WtfValues.cppandcore/libs/prx/libSceNKWebKit/tests/WtfPersistenceUrlGuestPointers.cppfrom the prepared diff and pinned head.Not verified
The test suite, mutation checks, convention/progress checks, and console behavior were not independently verified. The prepared bundle lists both changed files as included;
files.jsonwas not available through the reader.To get this to a good state
Nothing is required.
Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T14:57:32Z.
Review: COMMENTED
Built the changed WebKit sources and ran the branch's
WtfPersistenceUrlGuestPointersfixture against the existing Linux runtime. It passed, covering the persistence and URL calls changed by this PR.AI-assisted: yes.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.