fix(libSceIcu): copy lenient UTF-8 conversion and UTF-8 cursor guest pointers safely #22460

Merged
domx4q merged 3 commits from upstream-pr/22460 into main 2026-12-04 00:12:50 +00:00
domx4q commented 2026-11-17 17:06:25 +00:00 (Migrated from github.com)

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


What

Guest pointer safety for the libSceIcu UTF-8 exports that tools/guest_pointer_audit.py libSceIcu listed:

  • UtfConversions.cpp (u_strFromUTF8Lenient): the status is read with GuestCopyIn_nid_no_patch and written back with GuestCopyOut_nid_no_patch only where the old code assigned it. The source is read in chunks that stop at the next 4 KiB boundary, and only as far as the conversion reaches; with length -1 it is measured through the same chunks. The UTF-16 output collects in a fixed 2048-unit host buffer that is flushed with one GuestCopyOut_nid_no_patch per chunk. No host allocation depends on sourceLength or capacity. Writes happen in the old order (destination units, length, terminator, status), and the status is read again after the length is written, because the old Finish re-read *error there. guest_icu_utf_memory checks that order with the length and status aliased.
  • Utf8.cpp (utf8_nextCharSafeBody, utf8_prevCharSafeBody): the index is read with GuestCopyIn_nid_no_patch and written back with GuestCopyOut_nid_no_patch. The audit flagged only the index, but the text bytes were read directly too, through the Read helper. They now come from a small reader that copies at most four bytes per call: forward from the position, or backward ending at it, never past a 4 KiB boundary. So a sequence that ends at a page whose next or previous page is inaccessible is decoded without touching that page, and most calls copy only once. utf8_back1SafeBody shares PreviousPrefix, so it uses the same reader.

Failures follow what each file already does. In UtfConversions.cpp a null status, inaccessible output or overlong source already threw through NotImplemented_nid_no_patch, and the new paths call NotImplementedAt_nid_no_patch(__func__, __FILE__, __LINE__). An unreadable status or source and an unwritable status, length or destination now throw too. In Utf8.cpp inaccessible memory throws APS5_INVALID_ARG_EX, as null pointers and utf8_appendCharSafeBody (#22164) already did. GuestCopyIn/GuestCopyOut/GuestWritable restore errno themselves. Results for valid inputs do not change.

One behaviour moved. The old OutputAccess opened a GuestArena::HostWrite over the whole capacity before converting. On Linux that open never fails, so nothing was checked there, and the new code does not check the whole range up front either. A destination that becomes unwritable partway throws when its chunk is flushed. Earlier chunks, at most 2048 units each, are already written by then. The status and length are checked with GuestWritable_nid_no_patch before anything is written. Source and destination still must not overlap, as the debt entry and ICU require.

The debt fragment changes two entries. The UTF-8 macro helpers entry now says that unreadable buffers and unreadable or unwritable index pointers throw. The UTF-8 and UTF-16 conversions entry describes the chunked lenient path and its partial-write case.

u_strFromUTF8, u_strFromUTF8WithSub, u_strToUTF8 and u_strToUTF8WithSub share Validate/Length/Finish and still read the source and write outputs in place. The audit does not list them because the dereferences sit in helpers. They are left for a follow-up so this PR stays with the listed functions. No false positives in this set: all pointers are caller (guest) memory.

Overlap

python3 tools/pr_overlap.py --names u_strFromUTF8Lenient utf8_nextCharSafeBody utf8_prevCharSafeBody: utf8_nextCharSafeBody and utf8_prevCharSafeBody are implemented on main, and u_strFromUTF8Lenient is reported as a stub on main (its helpers contain NotImplemented_nid_no_patch(). Open: none for all three.
python3 tools/pr_overlap.py --branch fix/icu-utf-conversion-guest-pointers: no overlap with open pull requests.

Tested

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

  • ctest --test-dir build -R icu: 61/61 passed. ctest --test-dir build -R public_headers: 65/65 passed.
  • New checks:
    • guest_icu_utf8 (GuestPointers):
      • An unmapped index or text throws for utf8_nextCharSafeBody, utf8_prevCharSafeBody and utf8_back1SafeBody, and leaves the index unchanged.
      • A sequence that ends exactly at a PROT_NONE page decodes forward. A sequence right after a PROT_NONE page decodes backward, with the text pointer inside the protected page and start past it.
      • An unterminated sequence that runs into the protected page throws, and so do trail bytes that run back into it.
      • A read-only index throws without being changed.
    • guest_icu_utf8 (PageBoundaries): U+00E9, U+20AC and U+1F600 split at every position across two readable pages decode forward (counted and NUL-terminated), backward and with utf8_back1SafeBody. The same prefixes in front of a PROT_NONE page match host ICU when the length stops at the boundary, and throw without changing the index when the length or a missing terminator reaches the protected page.
    • guest_icu_utf_conversions (LenientGuestPointers, LenientChunks):
      • An unreadable or null status throws, and so does an unwritable length, an unreadable counted or terminated source, or an unwritable destination. Outputs stay unchanged.
      • A latched failure status returns before touching the other pointers.
      • sourceLength = INT32_MAX with a small capacity is rejected quickly without reading.
      • A source and a destination that end exactly at a PROT_NONE page convert.
      • INT32_MAX source and capacity against a few readable bytes throw at the guard page without a host allocation, and leave the outputs unchanged. So do an unterminated source and a destination that crosses the guard page.
      • Read-only destination, status and length throw.
    • guest_icu_utf_conversions (LenientPageBoundaries): the same 2-, 3- and 4-byte sequences split at every position across two readable pages convert, counted and NUL-terminated. In front of a PROT_NONE page, a counted length that stops at the boundary or a terminator just before it gives U+FFFD as for any truncated sequence; a counted length or missing terminator that reaches the protected page throws and leaves the outputs unchanged.
      • About 0x1800 bytes (0xC00 units) of mixed 1-, 3- and 4-byte sequences convert through several source and output chunks, NUL-terminated and counted. With capacity 0x900 the result is BufferOverflow with an exact prefix and an untouched canary.
  • Mutation checks:
    • Utf8.cpp and UtfConversions.cpp reverted to origin/main with the new tests kept: both test programs SEGFAULT.
    • Forward byte window not stopped at the 4 KiB boundary: guest_icu_utf8 aborts.
    • Backward byte window not stopped at the 4 KiB boundary: guest_icu_utf8 aborts.
    • Source chunks of a fixed 4096 bytes instead of ending at the boundary: guest_icu_utf_conversions aborts.
    • Continuation bytes taken from the cached chunk instead of byte(position + index): guest_icu_utf_conversions aborts (lenient sequence crossing an accessible page boundary); without LenientPageBoundaries the test program passed.
    • Flushing every output chunk to the start of the destination: guest_icu_utf_conversions aborts (lenient chunked conversion).
    • Without the status re-read after the length write: guest_icu_utf_memory aborts (positive aliased status preserves terminator canary).
  • python3 tools/guest_pointer_audit.py libSceIcu no longer lists Utf8.cpp or UtfConversions.cpp.
  • python3 tools/progress.py --module libSceIcu: 261 done on origin/main, 262 on this branch. u_strFromUTF8Lenient no longer goes through helpers that contain NotImplemented_nid_no_patch(.
  • python3 tools/check_conventions.py --base origin/main: passed. python3 tools/debt_fold.py --check: passed.
  • Not run on Windows.

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:5361399469 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/22460). Originally posted by [domx4q](https://github.com/domx4q) on 2026-11-17T17:06:25Z. --- ### What Guest pointer safety for the libSceIcu UTF-8 exports that `tools/guest_pointer_audit.py libSceIcu` listed: - `UtfConversions.cpp` (`u_strFromUTF8Lenient`): the status is read with `GuestCopyIn_nid_no_patch` and written back with `GuestCopyOut_nid_no_patch` only where the old code assigned it. The source is read in chunks that stop at the next 4 KiB boundary, and only as far as the conversion reaches; with length -1 it is measured through the same chunks. The UTF-16 output collects in a fixed 2048-unit host buffer that is flushed with one `GuestCopyOut_nid_no_patch` per chunk. No host allocation depends on `sourceLength` or `capacity`. Writes happen in the old order (destination units, length, terminator, status), and the status is read again after the length is written, because the old `Finish` re-read `*error` there. `guest_icu_utf_memory` checks that order with the length and status aliased. - `Utf8.cpp` (`utf8_nextCharSafeBody`, `utf8_prevCharSafeBody`): the index is read with `GuestCopyIn_nid_no_patch` and written back with `GuestCopyOut_nid_no_patch`. The audit flagged only the index, but the text bytes were read directly too, through the `Read` helper. They now come from a small reader that copies at most four bytes per call: forward from the position, or backward ending at it, never past a 4 KiB boundary. So a sequence that ends at a page whose next or previous page is inaccessible is decoded without touching that page, and most calls copy only once. `utf8_back1SafeBody` shares `PreviousPrefix`, so it uses the same reader. Failures follow what each file already does. In `UtfConversions.cpp` a null status, inaccessible output or overlong source already threw through `NotImplemented_nid_no_patch`, and the new paths call `NotImplementedAt_nid_no_patch(__func__, __FILE__, __LINE__)`. An unreadable status or source and an unwritable status, length or destination now throw too. In `Utf8.cpp` inaccessible memory throws `APS5_INVALID_ARG_EX`, as null pointers and `utf8_appendCharSafeBody` (#22164) already did. `GuestCopyIn`/`GuestCopyOut`/`GuestWritable` restore `errno` themselves. Results for valid inputs do not change. One behaviour moved. The old `OutputAccess` opened a `GuestArena::HostWrite` over the whole `capacity` before converting. On Linux that open never fails, so nothing was checked there, and the new code does not check the whole range up front either. A destination that becomes unwritable partway throws when its chunk is flushed. Earlier chunks, at most 2048 units each, are already written by then. The status and length are checked with `GuestWritable_nid_no_patch` before anything is written. Source and destination still must not overlap, as the debt entry and ICU require. The debt fragment changes two entries. The UTF-8 macro helpers entry now says that unreadable buffers and unreadable or unwritable index pointers throw. The UTF-8 and UTF-16 conversions entry describes the chunked lenient path and its partial-write case. `u_strFromUTF8`, `u_strFromUTF8WithSub`, `u_strToUTF8` and `u_strToUTF8WithSub` share `Validate`/`Length`/`Finish` and still read the source and write outputs in place. The audit does not list them because the dereferences sit in helpers. They are left for a follow-up so this PR stays with the listed functions. No false positives in this set: all pointers are caller (guest) memory. ### Overlap `python3 tools/pr_overlap.py --names u_strFromUTF8Lenient utf8_nextCharSafeBody utf8_prevCharSafeBody`: `utf8_nextCharSafeBody` and `utf8_prevCharSafeBody` are implemented on `main`, and `u_strFromUTF8Lenient` is reported as a stub on `main` (its helpers contain `NotImplemented_nid_no_patch(`). Open: none for all three. `python3 tools/pr_overlap.py --branch fix/icu-utf-conversion-guest-pointers`: no overlap with open pull requests. ### 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`). - `ctest --test-dir build -R icu`: 61/61 passed. `ctest --test-dir build -R public_headers`: 65/65 passed. - New checks: - `guest_icu_utf8` (`GuestPointers`): - An unmapped index or text throws for `utf8_nextCharSafeBody`, `utf8_prevCharSafeBody` and `utf8_back1SafeBody`, and leaves the index unchanged. - A sequence that ends exactly at a `PROT_NONE` page decodes forward. A sequence right after a `PROT_NONE` page decodes backward, with the text pointer inside the protected page and `start` past it. - An unterminated sequence that runs into the protected page throws, and so do trail bytes that run back into it. - A read-only index throws without being changed. - `guest_icu_utf8` (`PageBoundaries`): U+00E9, U+20AC and U+1F600 split at every position across two readable pages decode forward (counted and NUL-terminated), backward and with `utf8_back1SafeBody`. The same prefixes in front of a `PROT_NONE` page match host ICU when the length stops at the boundary, and throw without changing the index when the length or a missing terminator reaches the protected page. - `guest_icu_utf_conversions` (`LenientGuestPointers`, `LenientChunks`): - An unreadable or null status throws, and so does an unwritable length, an unreadable counted or terminated source, or an unwritable destination. Outputs stay unchanged. - A latched failure status returns before touching the other pointers. - `sourceLength = INT32_MAX` with a small capacity is rejected quickly without reading. - A source and a destination that end exactly at a `PROT_NONE` page convert. - `INT32_MAX` source and capacity against a few readable bytes throw at the guard page without a host allocation, and leave the outputs unchanged. So do an unterminated source and a destination that crosses the guard page. - Read-only destination, status and length throw. - `guest_icu_utf_conversions` (`LenientPageBoundaries`): the same 2-, 3- and 4-byte sequences split at every position across two readable pages convert, counted and NUL-terminated. In front of a `PROT_NONE` page, a counted length that stops at the boundary or a terminator just before it gives U+FFFD as for any truncated sequence; a counted length or missing terminator that reaches the protected page throws and leaves the outputs unchanged. - About 0x1800 bytes (0xC00 units) of mixed 1-, 3- and 4-byte sequences convert through several source and output chunks, NUL-terminated and counted. With capacity 0x900 the result is `BufferOverflow` with an exact prefix and an untouched canary. - Mutation checks: - `Utf8.cpp` and `UtfConversions.cpp` reverted to `origin/main` with the new tests kept: both test programs SEGFAULT. - Forward byte window not stopped at the 4 KiB boundary: `guest_icu_utf8` aborts. - Backward byte window not stopped at the 4 KiB boundary: `guest_icu_utf8` aborts. - Source chunks of a fixed 4096 bytes instead of ending at the boundary: `guest_icu_utf_conversions` aborts. - Continuation bytes taken from the cached chunk instead of `byte(position + index)`: `guest_icu_utf_conversions` aborts (`lenient sequence crossing an accessible page boundary`); without `LenientPageBoundaries` the test program passed. - Flushing every output chunk to the start of the destination: `guest_icu_utf_conversions` aborts (`lenient chunked conversion`). - Without the status re-read after the length write: `guest_icu_utf_memory` aborts (`positive aliased status preserves terminator canary`). - `python3 tools/guest_pointer_audit.py libSceIcu` no longer lists `Utf8.cpp` or `UtfConversions.cpp`. - `python3 tools/progress.py --module libSceIcu`: 261 done on `origin/main`, 262 on this branch. `u_strFromUTF8Lenient` no longer goes through helpers that contain `NotImplemented_nid_no_patch(`. - `python3 tools/check_conventions.py --base origin/main`: passed. `python3 tools/debt_fold.py --check`: passed. - Not run on Windows. ### 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)
MarcZX10 commented 2026-11-25 16:02:10 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T16:02:10Z.

Review: DISMISSED


Reviewed — changes requested

Changes are required before merge: prevent out-of-bounds access when the lenient converter processes a UTF-8 sequence split across its input chunk boundary.

What I ran

Reviewed head 589353cde553d9d53508d7860a8ea883b74a71e1. Read the prepared description, commits, manifest, complete diff, and all six changed files listed in the review bundle. Inspected Utf8.cpp and UtfConversions.cpp at the pinned head. No commands or tests were run in this review environment.

Results

Check Result Note
Source review failed Chunk boundary can split a multibyte sequence
Tests not run Author reports Linux tests; not independently run
Windows and console behavior not run Not confirmed here

Findings

Blocking

  • core/libs/prx/libSceIcu/UtfConversions.cpp:361 — The input cache loads only through the current 4 KiB boundary, but the decoder reads each sequence's continuation bytes with repeated byte(position + index) calls. If a valid multibyte lead byte is the final byte of a chunk, position + index falls outside the cached range and causes a second GuestCopyIn starting in the next page. When that page is inaccessible, conversion throws even though the sequence may be complete within the declared readable source region only if the range crossed the boundary; more directly, the cache behavior itself reads ahead to the end of a page on the lead-byte access, so it fails immediately when the page ends before the requested source sequence is fully accessible. The stated tests cover sources ending at a guard page but do not establish correct decoding of sequences straddling accessible page boundaries. Preserve incomplete sequence bytes across chunk loads or ensure each sequence is read safely without requiring bytes beyond the source's available range.

Non-blocking

None.

Not verified

Tests and runtime behavior were not independently run. The prepared description reports Arch Linux/GCC tests and says Windows was not run. Console behavior is unverified. All changed files in the manifest were read; no changed files were excluded by the manifest.

To get this to a good state

Fix sequence decoding at input chunk boundaries and add coverage for valid multibyte sequences crossing a 4 KiB boundary, including the case where the next page is inaccessible.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6060892525 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/22460#pullrequestreview-6060892525). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-25T16:02:10Z. **Review:** DISMISSED --- # Reviewed — changes requested Changes are required before merge: prevent out-of-bounds access when the lenient converter processes a UTF-8 sequence split across its input chunk boundary. ## What I ran Reviewed head `589353cde553d9d53508d7860a8ea883b74a71e1`. Read the prepared description, commits, manifest, complete diff, and all six changed files listed in the review bundle. Inspected `Utf8.cpp` and `UtfConversions.cpp` at the pinned head. No commands or tests were run in this review environment. ## Results | Check | Result | Note | |---|---|---| | Source review | failed | Chunk boundary can split a multibyte sequence | | Tests | not run | Author reports Linux tests; not independently run | | Windows and console behavior | not run | Not confirmed here | ## Findings ### Blocking - `core/libs/prx/libSceIcu/UtfConversions.cpp:361` — The input cache loads only through the current 4 KiB boundary, but the decoder reads each sequence's continuation bytes with repeated `byte(position + index)` calls. If a valid multibyte lead byte is the final byte of a chunk, `position + index` falls outside the cached range and causes a second `GuestCopyIn` starting in the next page. When that page is inaccessible, conversion throws even though the sequence may be complete within the declared readable source region only if the range crossed the boundary; more directly, the cache behavior itself reads ahead to the end of a page on the lead-byte access, so it fails immediately when the page ends before the requested source sequence is fully accessible. The stated tests cover sources ending at a guard page but do not establish correct decoding of sequences straddling accessible page boundaries. Preserve incomplete sequence bytes across chunk loads or ensure each sequence is read safely without requiring bytes beyond the source's available range. ### Non-blocking None. ## Not verified Tests and runtime behavior were not independently run. The prepared description reports Arch Linux/GCC tests and says Windows was not run. Console behavior is unverified. All changed files in the manifest were read; no changed files were excluded by the manifest. ## To get this to a good state Fix sequence decoding at input chunk boundaries and add coverage for valid multibyte sequences crossing a 4 KiB boundary, including the case where the next page is inaccessible.
MarcZX10 commented 2026-11-25 17:23:54 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T17:23:54Z.

Review: COMMENTED


Reviewed — no blocking findings

The inspected changes handle the described guest pointer and page boundary cases; I did not run the reported checks, so this review does not support a formal approval.

What I ran

Reviewed head 09fd90090af13c01cea01dee9844b6f9cec2b69d using the prepared review materials and repo_read.py. No commands or tests were run; reported test results are author supplied.

Results

Check Result Note
Patch and changed code review passed Six changed files inspected
Reported automated checks not run Results in the description are author supplied
Windows and console behavior not run Not confirmed

Findings

Blocking

None.

Non-blocking

None.

Not verified

No build or tests were run. Windows and physical console behavior remain unverified. The description, commits, manifest, and full diff were read. All six changed files were listed as included; the two implementation files and both test files were inspected, along with both changed debt fragments. The review did not independently reproduce the reported checks.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6062006474 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/22460#pullrequestreview-6062006474). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-25T17:23:54Z. **Review:** COMMENTED --- # Reviewed — no blocking findings The inspected changes handle the described guest pointer and page boundary cases; I did not run the reported checks, so this review does not support a formal approval. ## What I ran Reviewed head `09fd90090af13c01cea01dee9844b6f9cec2b69d` using the prepared review materials and `repo_read.py`. No commands or tests were run; reported test results are author supplied. ## Results | Check | Result | Note | |---|---|---| | Patch and changed code review | passed | Six changed files inspected | | Reported automated checks | not run | Results in the description are author supplied | | Windows and console behavior | not run | Not confirmed | ## Findings ### Blocking None. ### Non-blocking None. ## Not verified No build or tests were run. Windows and physical console behavior remain unverified. The description, commits, manifest, and full diff were read. All six changed files were listed as included; the two implementation files and both test files were inspected, along with both changed debt fragments. The review did not independently reproduce the reported checks. ## To get this to a good state Nothing is required.
ligmaSec commented 2026-12-03 11:10:23 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T11:10:23Z.

Review: COMMENTED


Built the submitted UTF-8 conversion sources against bundled ICU and ran both exact Linux fixtures. GuestIcuUtf8 and GuestIcuUtfConversions passed, including chunked conversions, guarded state, and the output prefix and sentinel checks on overflow.

AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6168576468 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/22460#pullrequestreview-6168576468). Originally posted by [ligmaSec](https://github.com/ligmaSec) on 2026-12-03T11:10:23Z. **Review:** COMMENTED --- Built the submitted UTF-8 conversion sources against bundled ICU and ran both exact Linux fixtures. `GuestIcuUtf8` and `GuestIcuUtfConversions` passed, including chunked conversions, guarded state, and the output prefix and sentinel checks on overflow. AI-assisted: yes.
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!22460
No description provided.