fix(libc): convert multibyte text as UTF-8 like the console's C locale #8855

Merged
hypermoist merged 12 commits from upstream-pr/8855 into main 2026-10-23 06:30:12 +00:00
hypermoist commented 2026-10-21 03:25:34 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hypermoist on 2026-10-21T03:25:34Z.


What

The console's C locale converts multibyte text as UTF-8, and this libc used a single-byte C locale. This PR switches the multibyte conversions to UTF-8. The evidence is the decrypted libSceLibcInternal.sprx (PS5 12.00): its exports were loaded and called directly, and their results compared with this build's. It also agrees with the payload measurement already in libc.md (U+263A → E2 98 BA).

Rules taken from the firmware:

  • Characters are at most 3 bytes and _Getmbcurmax returns 3. Four-byte leads (≥ 0xF0) are invalid; overlong forms and encoded surrogates decode.
  • __mb_cur_max stays 1, like the console's variable.
  • The conversion state is 16 bytes: the value at offset 0 and the count of bytes still expected as 16 bits at offset 0xA. mbsinit reads that count.

Per function:

  • mbrtowc (0x836a0) converts a null source as "" with a null destination and the caller's count:
    • with n == 0 it returns -2 and leaves the state as it was;
    • otherwise it returns 0 from the initial state, or -1 with EILSEQ from a pending state, which it keeps.
  • mbrlen (0x83660) with a null source returns 0 and resets the state, whatever the count.
  • mbtowc (0x6f7b0) keeps its state per thread and clamps n to 3.
  • mblen (0x6f680) uses a fresh state on each call.
  • mbsrtowcs (0x83720) writes dst[0] = 0 on entry.
  • wcstombs (0x89260) fills the capacity even in the middle of a character.
  • wctob (0x89810) truncates its argument to 16 bits.
  • btowc (0x7da90) returns WEOF for 0x80 and above. It sets EILSEQ when the low byte is 0x80–0xBF or 0xF0–0xFF, which cannot start a character, and leaves errno alone for lead bytes 0xC0–0xEF and EOF. Found by @JJenkx against titles' libc.prx and confirmed on the firmware export.
  • wcstombs_s (0x893e0) ends without error when a character does not fit a limit below the capacity, as C11 K.3.6.5.2 allows. wcsrtombs_s (0x85fd0) keeps reporting ERANGE there. Both paths were unreachable with a single-byte locale.
  • wcsftime sizes its narrow buffer with _Getmbcurmax and checks the length before it writes. Characters above 0xFF now pass through: the console copies them verbatim.

Tests changed: the wcstombs_s cases in GuestWcsrtombsS.cpp and GuestAmprThreads.cpp that expected EILSEQ for U+0100 now expect 61 C4 80, the firmware's result. GuestMultibyteLocale.cpp is new.

Debt entries: the "Wide-character conversions", c16rtomb/mbrtoc16 and wcsftime entries in libc.md now describe the UTF-8 locale and the remaining gaps. For wcsftime those are:

  • on overflow the console leaves partial output in the buffer;
  • with a null buffer the console writes through it;
  • with a SIZE_MAX count the console formats as usual, while here it returns 0 with EINVAL.

Two entries are left for a follow-up because #7841 inserts a line next to them: the wcsrtombs_s sentence about MB_CUR_MAX 1, and #7841's Annex K locale line.

Tested

Linux (CachyOS, GCC, Release): full build. All 539 guest_* and Ampr tests pass.

Firmware differential (the harness loads the module and calls the addresses above):

  • mbrtowc: every 1–4-byte input from a fresh state (16.8M cases), 0 mismatches.
  • Stateful sequences and string conversions: 300k cases each. The stateful ones have 0 mismatches. In the string conversions, the only mismatches seen are wcstombs with a null destination: there the console reads past the terminator when the capacity equals the running count, as recorded in the debt entry.
  • wcstombs_s and wcsrtombs_s: 400k random cases, 0 mismatches.

tools/check_conventions.py reports no errors; it warns that the c16rtomb entry I edited is over 1000 characters. pr_overlap: 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
  • 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 (libc only)
  • AI-assisted: yes (Claude Code), reviewed by the contributor

🤖 Generated with Claude Code

https://claude.ai/code/session_01RbLgECLQ2bpDM7oe2urGZK

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4945912846 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855). Originally posted by [hypermoist](https://github.com/hypermoist) on 2026-10-21T03:25:34Z. --- ### What The console's C locale converts multibyte text as UTF-8, and this libc used a single-byte C locale. This PR switches the multibyte conversions to UTF-8. The evidence is the decrypted `libSceLibcInternal.sprx` (PS5 12.00): its exports were loaded and called directly, and their results compared with this build's. It also agrees with the payload measurement already in `libc.md` (U+263A → `E2 98 BA`). **Rules taken from the firmware:** - Characters are at most 3 bytes and `_Getmbcurmax` returns 3. Four-byte leads (≥ 0xF0) are invalid; overlong forms and encoded surrogates decode. - `__mb_cur_max` stays 1, like the console's variable. - The conversion state is 16 bytes: the value at offset 0 and the count of bytes still expected as 16 bits at offset 0xA. `mbsinit` reads that count. **Per function:** - **`mbrtowc` (0x836a0)** converts a null source as `""` with a null destination and the caller's count: - with `n == 0` it returns -2 and leaves the state as it was; - otherwise it returns 0 from the initial state, or -1 with `EILSEQ` from a pending state, which it keeps. - **`mbrlen` (0x83660)** with a null source returns 0 and resets the state, whatever the count. - **`mbtowc` (0x6f7b0)** keeps its state per thread and clamps `n` to 3. - **`mblen` (0x6f680)** uses a fresh state on each call. - **`mbsrtowcs` (0x83720)** writes `dst[0] = 0` on entry. - **`wcstombs` (0x89260)** fills the capacity even in the middle of a character. - **`wctob` (0x89810)** truncates its argument to 16 bits. - **`btowc` (0x7da90)** returns `WEOF` for 0x80 and above. It sets `EILSEQ` when the low byte is 0x80–0xBF or 0xF0–0xFF, which cannot start a character, and leaves `errno` alone for lead bytes 0xC0–0xEF and `EOF`. Found by @JJenkx against titles' `libc.prx` and confirmed on the firmware export. - **`wcstombs_s` (0x893e0)** ends without error when a character does not fit a limit below the capacity, as C11 K.3.6.5.2 allows. **`wcsrtombs_s` (0x85fd0)** keeps reporting `ERANGE` there. Both paths were unreachable with a single-byte locale. - **`wcsftime`** sizes its narrow buffer with `_Getmbcurmax` and checks the length before it writes. Characters above 0xFF now pass through: the console copies them verbatim. **Tests changed:** the `wcstombs_s` cases in `GuestWcsrtombsS.cpp` and `GuestAmprThreads.cpp` that expected `EILSEQ` for U+0100 now expect `61 C4 80`, the firmware's result. `GuestMultibyteLocale.cpp` is new. **Debt entries:** the "Wide-character conversions", `c16rtomb`/`mbrtoc16` and `wcsftime` entries in `libc.md` now describe the UTF-8 locale and the remaining gaps. For `wcsftime` those are: - on overflow the console leaves partial output in the buffer; - with a null buffer the console writes through it; - with a `SIZE_MAX` count the console formats as usual, while here it returns 0 with `EINVAL`. Two entries are left for a follow-up because #7841 inserts a line next to them: the `wcsrtombs_s` sentence about `MB_CUR_MAX` 1, and #7841's Annex K locale line. ### Tested Linux (CachyOS, GCC, Release): full build. All 539 `guest_*` and Ampr tests pass. Firmware differential (the harness loads the module and calls the addresses above): - `mbrtowc`: every 1–4-byte input from a fresh state (16.8M cases), 0 mismatches. - Stateful sequences and string conversions: 300k cases each. The stateful ones have 0 mismatches. In the string conversions, the only mismatches seen are `wcstombs` with a null destination: there the console reads past the terminator when the capacity equals the running count, as recorded in the debt entry. - `wcstombs_s` and `wcsrtombs_s`: 400k random cases, 0 mismatches. `tools/check_conventions.py` reports no errors; it warns that the `c16rtomb` entry I edited is over 1000 characters. `pr_overlap`: no overlap with open pull requests. ### Checklist - [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 - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a (libc only) - [x] AI-assisted: yes (Claude Code), reviewed by the contributor 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01RbLgECLQ2bpDM7oe2urGZK
MarcZX10 commented 2026-10-21 03:44:10 +00:00 (Migrated from github.com)

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

Code review location: core/libs/prx/libc/src/Multibyte.cpp; line 144

@@ -63,51 +121,47 @@ int APS5_VABI ___mb_cur_max_nid_postfix() {
     return 1;
 }
 
-int APS5_VABI _Getmbcurmax_nid_postfix() { return ___mb_cur_max_nid_postfix(); }
+int APS5_VABI _Getmbcurmax_nid_postfix() { return static_cast<int>(LocaleMaxLength); }
 
-int APS5_VABI mbsinit_nid_postfix(const void*) {
-    return 1;
+int APS5_VABI mbsinit_nid_postfix(const void* state) {
+    if (!state) return 1;
+    std::int16_t pending = 0;
+    std::memcpy(&pending, static_cast<const unsigned char*>(state) + PendingOffset, sizeof(pending));
+    return pending == 0;
 }
 
-std::size_t APS5_VABI mbrtowc_nid_postfix(std::uint16_t* destination, const char* source, std::size_t count, void*) {
-    if (!source) return 0;
-    if (!count) return static_cast<std::size_t>(-2);
-    const auto value = static_cast<unsigned char>(*source);
-    if (destination) *destination = value;
-    return value != 0;
+std::size_t APS5_VABI mbrtowc_nid_postfix(std::uint16_t* destination, const char* source, std::size_t count, void* state) {
+    thread_local unsigned char internal[StateSize]{};
+    if (!source) {
+        destination = nullptr;
+        source = "";
+    }
+    return LocaleToWide(destination, source, count, state ? static_cast<unsigned char*>(state) : internal);
 }
 
 std::size_t APS5_VABI mbrlen_nid_postfix(const char* source, std::size_t count, void* state) {
-    return mbrtowc_nid_postfix(nullptr, source, count, state);
+    thread_local unsigned char internal[StateSize]{};
+    return LocaleToWide(nullptr, source, count, state ? static_cast<unsigned char*>(state) : internal);

The implementation and summary disagree on this edge case. mbrtowc turns a null source into "" and then passes the caller’s count to LocaleToWide; when count == 0, that helper returns Incomplete before reading the empty string or changing state. The PR summary says a null source resets state and returns 0. CheckState tests a pending state with null source at count == 1 (expecting Invalid) and tests mbrlen(nullptr, 1, state), but not mbrtowc(nullptr, 0, state). Could you reconcile the reported firmware behavior for n == 0 and add the exact null-source/zero-count case, including whether pending state is cleared?

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4332821229 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855#discussion_r4332821229). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-21T03:44:10Z. **Code review location:** `core/libs/prx/libc/src/Multibyte.cpp`; line 144 ~~~~diff @@ -63,51 +121,47 @@ int APS5_VABI ___mb_cur_max_nid_postfix() { return 1; } -int APS5_VABI _Getmbcurmax_nid_postfix() { return ___mb_cur_max_nid_postfix(); } +int APS5_VABI _Getmbcurmax_nid_postfix() { return static_cast<int>(LocaleMaxLength); } -int APS5_VABI mbsinit_nid_postfix(const void*) { - return 1; +int APS5_VABI mbsinit_nid_postfix(const void* state) { + if (!state) return 1; + std::int16_t pending = 0; + std::memcpy(&pending, static_cast<const unsigned char*>(state) + PendingOffset, sizeof(pending)); + return pending == 0; } -std::size_t APS5_VABI mbrtowc_nid_postfix(std::uint16_t* destination, const char* source, std::size_t count, void*) { - if (!source) return 0; - if (!count) return static_cast<std::size_t>(-2); - const auto value = static_cast<unsigned char>(*source); - if (destination) *destination = value; - return value != 0; +std::size_t APS5_VABI mbrtowc_nid_postfix(std::uint16_t* destination, const char* source, std::size_t count, void* state) { + thread_local unsigned char internal[StateSize]{}; + if (!source) { + destination = nullptr; + source = ""; + } + return LocaleToWide(destination, source, count, state ? static_cast<unsigned char*>(state) : internal); } std::size_t APS5_VABI mbrlen_nid_postfix(const char* source, std::size_t count, void* state) { - return mbrtowc_nid_postfix(nullptr, source, count, state); + thread_local unsigned char internal[StateSize]{}; + return LocaleToWide(nullptr, source, count, state ? static_cast<unsigned char*>(state) : internal); ~~~~ --- The implementation and summary disagree on this edge case. `mbrtowc` turns a null `source` into `""` and then passes the caller’s `count` to `LocaleToWide`; when `count == 0`, that helper returns `Incomplete` before reading the empty string or changing state. The PR summary says a null source resets state and returns 0. `CheckState` tests a pending state with null source at `count == 1` (expecting `Invalid`) and tests `mbrlen(nullptr, 1, state)`, but not `mbrtowc(nullptr, 0, state)`. Could you reconcile the reported firmware behavior for `n == 0` and add the exact null-source/zero-count case, including whether pending state is cleared?
hypermoist commented 2026-10-21 03:47:39 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hypermoist on 2026-10-21T03:47:39Z.

Code review location: core/libs/prx/libc/src/Multibyte.cpp; line 144

@@ -63,51 +121,47 @@ int APS5_VABI ___mb_cur_max_nid_postfix() {
     return 1;
 }
 
-int APS5_VABI _Getmbcurmax_nid_postfix() { return ___mb_cur_max_nid_postfix(); }
+int APS5_VABI _Getmbcurmax_nid_postfix() { return static_cast<int>(LocaleMaxLength); }
 
-int APS5_VABI mbsinit_nid_postfix(const void*) {
-    return 1;
+int APS5_VABI mbsinit_nid_postfix(const void* state) {
+    if (!state) return 1;
+    std::int16_t pending = 0;
+    std::memcpy(&pending, static_cast<const unsigned char*>(state) + PendingOffset, sizeof(pending));
+    return pending == 0;
 }
 
-std::size_t APS5_VABI mbrtowc_nid_postfix(std::uint16_t* destination, const char* source, std::size_t count, void*) {
-    if (!source) return 0;
-    if (!count) return static_cast<std::size_t>(-2);
-    const auto value = static_cast<unsigned char>(*source);
-    if (destination) *destination = value;
-    return value != 0;
+std::size_t APS5_VABI mbrtowc_nid_postfix(std::uint16_t* destination, const char* source, std::size_t count, void* state) {
+    thread_local unsigned char internal[StateSize]{};
+    if (!source) {
+        destination = nullptr;
+        source = "";
+    }
+    return LocaleToWide(destination, source, count, state ? static_cast<unsigned char*>(state) : internal);
 }
 
 std::size_t APS5_VABI mbrlen_nid_postfix(const char* source, std::size_t count, void* state) {
-    return mbrtowc_nid_postfix(nullptr, source, count, state);
+    thread_local unsigned char internal[StateSize]{};
+    return LocaleToWide(nullptr, source, count, state ? static_cast<unsigned char*>(state) : internal);

Thanks, you're right: the summary was wrong and the code was right. I ran the firmware mbrtowc (0x836a0) and mbrlen (0x83660) with a null source at counts 0, 1 and 5, from the initial state and from states pending after one and after two bytes of a three-byte character. All 18 results (return value, errno and all 16 state bytes) match this branch:

call state n result state after
mbrtowc(&w, NULL, n, st) any 0 -2, errno unchanged unchanged (a pending state stays pending)
mbrtowc(&w, NULL, n, st) initial ≥1 0 initial; *w not written
mbrtowc(&w, NULL, n, st) pending ≥1 -1, EILSEQ (86) unchanged; *w not written
mbrlen(NULL, n, st) any any (0 too) 0 reset to initial

So a null source in mbrtowc does not reset the state; it converts "" with the caller's count, as the code does. Only mbrlen resets.

In 1c96d7ca1d, CheckState now covers the exact cases:

  • mbrtowc(&value, nullptr, 0, state) returns -2 and leaves a pending state byte for byte;
  • the null/count-1 case checks EILSEQ, an untouched *value and the kept state;
  • mbrlen(nullptr, 0, state) resets;
  • from the initial state, null with count 0 returns -2 and null with count 1 returns 0, both leaving the state zeroed.

As a negative control I made mbrtowc reset the state on a null source, as the old summary described, and the test fails on the count-0 pending case. The PR description is corrected. All 539 guest_*/Ampr tests pass.

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4332837939 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855#discussion_r4332837939). Originally posted by [hypermoist](https://github.com/hypermoist) on 2026-10-21T03:47:39Z. **Code review location:** `core/libs/prx/libc/src/Multibyte.cpp`; line 144 ~~~~diff @@ -63,51 +121,47 @@ int APS5_VABI ___mb_cur_max_nid_postfix() { return 1; } -int APS5_VABI _Getmbcurmax_nid_postfix() { return ___mb_cur_max_nid_postfix(); } +int APS5_VABI _Getmbcurmax_nid_postfix() { return static_cast<int>(LocaleMaxLength); } -int APS5_VABI mbsinit_nid_postfix(const void*) { - return 1; +int APS5_VABI mbsinit_nid_postfix(const void* state) { + if (!state) return 1; + std::int16_t pending = 0; + std::memcpy(&pending, static_cast<const unsigned char*>(state) + PendingOffset, sizeof(pending)); + return pending == 0; } -std::size_t APS5_VABI mbrtowc_nid_postfix(std::uint16_t* destination, const char* source, std::size_t count, void*) { - if (!source) return 0; - if (!count) return static_cast<std::size_t>(-2); - const auto value = static_cast<unsigned char>(*source); - if (destination) *destination = value; - return value != 0; +std::size_t APS5_VABI mbrtowc_nid_postfix(std::uint16_t* destination, const char* source, std::size_t count, void* state) { + thread_local unsigned char internal[StateSize]{}; + if (!source) { + destination = nullptr; + source = ""; + } + return LocaleToWide(destination, source, count, state ? static_cast<unsigned char*>(state) : internal); } std::size_t APS5_VABI mbrlen_nid_postfix(const char* source, std::size_t count, void* state) { - return mbrtowc_nid_postfix(nullptr, source, count, state); + thread_local unsigned char internal[StateSize]{}; + return LocaleToWide(nullptr, source, count, state ? static_cast<unsigned char*>(state) : internal); ~~~~ --- Thanks, you're right: the summary was wrong and the code was right. I ran the firmware `mbrtowc` (0x836a0) and `mbrlen` (0x83660) with a null source at counts 0, 1 and 5, from the initial state and from states pending after one and after two bytes of a three-byte character. All 18 results (return value, errno and all 16 state bytes) match this branch: | call | state | n | result | state after | |---|---|---|---|---| | `mbrtowc(&w, NULL, n, st)` | any | 0 | -2, errno unchanged | unchanged (a pending state stays pending) | | `mbrtowc(&w, NULL, n, st)` | initial | ≥1 | 0 | initial; `*w` not written | | `mbrtowc(&w, NULL, n, st)` | pending | ≥1 | -1, `EILSEQ` (86) | unchanged; `*w` not written | | `mbrlen(NULL, n, st)` | any | any (0 too) | 0 | reset to initial | So a null source in `mbrtowc` does not reset the state; it converts `""` with the caller's count, as the code does. Only `mbrlen` resets. In 1c96d7ca1d, `CheckState` now covers the exact cases: - `mbrtowc(&value, nullptr, 0, state)` returns -2 and leaves a pending state byte for byte; - the null/count-1 case checks `EILSEQ`, an untouched `*value` and the kept state; - `mbrlen(nullptr, 0, state)` resets; - from the initial state, null with count 0 returns -2 and null with count 1 returns 0, both leaving the state zeroed. As a negative control I made `mbrtowc` reset the state on a null source, as the old summary described, and the test fails on the count-0 pending case. The PR description is corrected. All 539 `guest_*`/Ampr tests pass.
MaxLikesCode commented 2026-10-21 17:38:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MaxLikesCode on 2026-10-21T17:38:36Z.


Windows run of head 1c96d7ca1 merged onto main d34da5d69: it builds, and guest_bounds_checking fails 3 of 3:

wctomb_s converted an unrepresentable character

That test's checks came in with #7841 after this PR's base (e0e57a327). Lines 132 and 147 of core/libs/tests/GuestBoundsChecking.cpp expect wctomb_s and wcrtomb_s to refuse U+263A with 86 (EILSEQ) in the C locale. With this PR both convert it, which is what this PR and the payload measurement in libc.md say the console does:

wctomb_s(0x263a)  = 0, status 3, bytes e2 98 ba
wcrtomb_s(0x263a) = 0, result 3, bytes e2 98 ba

With those two checks replaced by the prints above, the rest of guest_bounds_checking passes, so only those two expectations need to change. The other 946 non-GPU tests that tools/select_tests.py selects for this PR pass. main alone passes guest_bounds_checking.

Windows 11 Pro 26200, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6322494033 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855#issuecomment-6322494033). Originally posted by [MaxLikesCode](https://github.com/MaxLikesCode) on 2026-10-21T17:38:36Z. --- Windows run of head `1c96d7ca1` merged onto `main` `d34da5d69`: it builds, and `guest_bounds_checking` fails 3 of 3: ```text wctomb_s converted an unrepresentable character ``` That test's checks came in with #7841 after this PR's base (`e0e57a327`). Lines 132 and 147 of `core/libs/tests/GuestBoundsChecking.cpp` expect `wctomb_s` and `wcrtomb_s` to refuse U+263A with 86 (`EILSEQ`) in the C locale. With this PR both convert it, which is what this PR and the payload measurement in `libc.md` say the console does: ```text wctomb_s(0x263a) = 0, status 3, bytes e2 98 ba wcrtomb_s(0x263a) = 0, result 3, bytes e2 98 ba ``` With those two checks replaced by the prints above, the rest of `guest_bounds_checking` passes, so only those two expectations need to change. The other 946 non-GPU tests that `tools/select_tests.py` selects for this PR pass. `main` alone passes `guest_bounds_checking`. Windows 11 Pro 26200, WinLibs GCC 15.2.0 r7, Release, `BUILD_TESTING=ON`. AI-assisted: yes (Claude Code)
oneandonlydean commented 2026-10-21 23:55:40 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-21T23:55:40Z.


@hypermoist, after #7841 merged, this PR's checks fail guest_bounds_checking on both Linux and Windows:

wctomb_s converted an unrepresentable character

The test is from #7841 and was written against the single-byte locale. core/libs/tests/GuestBoundsChecking.cpp:133 expects wctomb_s(..., 0x263a) to return EILSEQ with status -1, and :147 expects the same from wcrtomb_s. With this PR's UTF-8 conversions, U+263A converts to E2 98 BA, and no 16-bit value is unrepresentable any more. So both assertions need the firmware's result: return 0, status/result 3, bytes E2 98 BA. Those are the only two locale-dependent cases in that file. The rest use ASCII or check arguments.

There is also a real bug where the two PRs meet. wctomb_s and wcrtomb_s in core/libs/prx/libc/src/BoundsChecking.cpp (lines 130 and 157) stage through a scratch buffer only when ___mb_cur_max() is larger than the capacity. This PR keeps __mb_cur_max at 1, as the console does, while characters are now up to 3 bytes. So any capacity of 1 or more skips the scratch buffer, and wctomb_s(&status, buffer, 2, 0x263a) writes 3 bytes into a 2-byte buffer. Comparing against _Getmbcurmax() (3) in those two places restores the staging path and the ERANGE check. Could you add a case with capacity 2 and U+263A that checks for ERANGE and that nothing past the buffer changes? If the firmware answers that case differently, its answer wins, but it must not write past the capacity.

wcstombs_s and wcsrtombs_s don't have this issue. They're the ones you already adjusted here.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6329223936 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855#issuecomment-6329223936). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-21T23:55:40Z. --- @hypermoist, after #7841 merged, this PR's checks fail `guest_bounds_checking` on both Linux and Windows: ``` wctomb_s converted an unrepresentable character ``` The test is from #7841 and was written against the single-byte locale. `core/libs/tests/GuestBoundsChecking.cpp:133` expects `wctomb_s(..., 0x263a)` to return `EILSEQ` with status -1, and `:147` expects the same from `wcrtomb_s`. With this PR's UTF-8 conversions, U+263A converts to `E2 98 BA`, and no 16-bit value is unrepresentable any more. So both assertions need the firmware's result: return 0, status/result 3, bytes `E2 98 BA`. Those are the only two locale-dependent cases in that file. The rest use ASCII or check arguments. There is also a real bug where the two PRs meet. `wctomb_s` and `wcrtomb_s` in `core/libs/prx/libc/src/BoundsChecking.cpp` (lines 130 and 157) stage through a scratch buffer only when `___mb_cur_max()` is larger than the capacity. This PR keeps `__mb_cur_max` at 1, as the console does, while characters are now up to 3 bytes. So any capacity of 1 or more skips the scratch buffer, and `wctomb_s(&status, buffer, 2, 0x263a)` writes 3 bytes into a 2-byte buffer. Comparing against `_Getmbcurmax()` (3) in those two places restores the staging path and the `ERANGE` check. Could you add a case with capacity 2 and U+263A that checks for `ERANGE` and that nothing past the buffer changes? If the firmware answers that case differently, its answer wins, but it must not write past the capacity. `wcstombs_s` and `wcsrtombs_s` don't have this issue. They're the ones you already adjusted here.
hypermoist commented 2026-10-22 01:42:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hypermoist on 2026-10-22T01:42:36Z.


@MaxLikesCode @oneandonlydean thanks, both fixed. I merged main (clean), then in d06dfb1caf:

  • GuestBoundsChecking.cpp: wctomb_s and wcrtomb_s of U+263A now expect the console's result: 0, status/result 3, bytes E2 98 BA.
  • The overrun is real. wctomb_s and wcrtomb_s now stage through the scratch buffer when _Getmbcurmax() is larger than the capacity, as the firmware does. In libSceLibcInternal.sprx both call _Getmbcurmax (0x3c90) for that comparison, not ___mb_cur_max (read from disassembly, not measured on a console). With a capacity of 2, U+263A now returns ERANGE through the constraint handler. wctomb_s leaves the status and all four bytes untouched. wcrtomb_s sets the result to -1 and writes 0 only to the first byte, which is what the firmware's too-small path stores. The new cases check that nothing past the buffer changes.

The next commit shortens the char16/char32 debt entry to under 1000 characters. Locally, all 526 non-GPU guest_* tests pass on Linux and check_conventions passes.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6330639435 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855#issuecomment-6330639435). Originally posted by [hypermoist](https://github.com/hypermoist) on 2026-10-22T01:42:36Z. --- @MaxLikesCode @oneandonlydean thanks, both fixed. I merged `main` (clean), then in d06dfb1caf: - `GuestBoundsChecking.cpp`: `wctomb_s` and `wcrtomb_s` of U+263A now expect the console's result: 0, status/result 3, bytes `E2 98 BA`. - The overrun is real. `wctomb_s` and `wcrtomb_s` now stage through the scratch buffer when `_Getmbcurmax()` is larger than the capacity, as the firmware does. In `libSceLibcInternal.sprx` both call `_Getmbcurmax` (0x3c90) for that comparison, not `___mb_cur_max` (read from disassembly, not measured on a console). With a capacity of 2, U+263A now returns `ERANGE` through the constraint handler. `wctomb_s` leaves the status and all four bytes untouched. `wcrtomb_s` sets the result to -1 and writes 0 only to the first byte, which is what the firmware's too-small path stores. The new cases check that nothing past the buffer changes. The next commit shortens the char16/char32 debt entry to under 1000 characters. Locally, all 526 non-GPU `guest_*` tests pass on Linux and `check_conventions` passes.
JJenkx commented 2026-10-22 07:28:54 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by JJenkx on 2026-10-22T07:28:54Z.


Supporting evidence from the libc.prx that titles bundle, which is the module this libc replaces (read from disassembly of the decrypted copies of PPSA13934, PPSA07923 and PPSA05916; not run, not measured on a console). It agrees with this PR's rules from libSceLibcInternal.sprx.

  • _Getmbcurmax (U52BlHBvYvE; 0x3a40, 0x38d0 and 0x3810 in the three copies) is movsbq of one byte of .data that is 3 in the file in all three.
  • mbrtowc (qVHpv0PxouI, 91 bytes) uses an internal state when ps is null. A null s becomes "" with a null pwc and the caller's n. It then calls one converter (0x3f990 in PPSA13934), passing a pointer to an eight-entry table of state tables (0x113bf8). That table is in .bss, so it is null until a locale installs one. While it is null, the converter takes a hard-coded UTF-8 path:
    • a byte below 0x80 is a character;
    • (b & 0xE0) == 0xC0 expects 1 more byte, keeping 5 bits;
    • (b & 0xF0) == 0xE0 expects 2 more bytes, keeping 4 bits;
    • anything else as a first byte, including 0xF0 to 0xFF and a stray continuation byte, sets errno to 0x56 (86, EILSEQ) and returns -1 without writing the state back;
    • a continuation byte is checked only with (b & 0xC0) == 0x80, with no overlong or surrogate check;
    • the result is stored as 16 bits;
    • running out of input stores the value and count (16 bits at offset 0xA) and returns -2;
    • a complete character returns the bytes used in this call, or 0 for a null character, and clears the count.
  • The same instructions (and 0xffffffe0 / cmp 0xc0, and 0xfffffff0 / cmp 0xe0, movl $0x56) and the same null-table check are in all three copies (PPSA07923 0x40e70, PPSA05916 0x46fb0).

So a title calling its bundled mbrtowc, fgetwc (which goes through the same converter) or _Getmbcurmax at startup gets UTF-8 with characters of up to 3 bytes. That is what this PR implements, and it resolves the "Titles bundle their own libc.prx, whose locale was not measured" sentence in libc.md. One limit: I did not follow what setlocale installs in that table. The code that fills it is reached through a getter (0x7a50) with 43 callers, so a title that calls setlocale with another locale may get a table-driven conversion instead.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6335267758 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855#issuecomment-6335267758). Originally posted by [JJenkx](https://github.com/JJenkx) on 2026-10-22T07:28:54Z. --- Supporting evidence from the `libc.prx` that titles bundle, which is the module this libc replaces (read from disassembly of the decrypted copies of PPSA13934, PPSA07923 and PPSA05916; not run, not measured on a console). It agrees with this PR's rules from `libSceLibcInternal.sprx`. - **`_Getmbcurmax`** (`U52BlHBvYvE`; 0x3a40, 0x38d0 and 0x3810 in the three copies) is `movsbq` of one byte of `.data` that is 3 in the file in all three. - **`mbrtowc`** (`qVHpv0PxouI`, 91 bytes) uses an internal state when `ps` is null. A null `s` becomes `""` with a null `pwc` and the caller's `n`. It then calls one converter (0x3f990 in PPSA13934), passing a pointer to an eight-entry table of state tables (0x113bf8). That table is in `.bss`, so it is null until a locale installs one. While it is null, the converter takes a hard-coded UTF-8 path: - a byte below 0x80 is a character; - `(b & 0xE0) == 0xC0` expects 1 more byte, keeping 5 bits; - `(b & 0xF0) == 0xE0` expects 2 more bytes, keeping 4 bits; - anything else as a first byte, including 0xF0 to 0xFF and a stray continuation byte, sets `errno` to 0x56 (86, `EILSEQ`) and returns -1 without writing the state back; - a continuation byte is checked only with `(b & 0xC0) == 0x80`, with no overlong or surrogate check; - the result is stored as 16 bits; - running out of input stores the value and count (16 bits at offset 0xA) and returns -2; - a complete character returns the bytes used in this call, or 0 for a null character, and clears the count. - The same instructions (`and 0xffffffe0 / cmp 0xc0`, `and 0xfffffff0 / cmp 0xe0`, `movl $0x56`) and the same null-table check are in all three copies (PPSA07923 0x40e70, PPSA05916 0x46fb0). So a title calling its bundled `mbrtowc`, `fgetwc` (which goes through the same converter) or `_Getmbcurmax` at startup gets UTF-8 with characters of up to 3 bytes. That is what this PR implements, and it resolves the "Titles bundle their own libc.prx, whose locale was not measured" sentence in `libc.md`. One limit: I did not follow what `setlocale` installs in that table. The code that fills it is reached through a getter (0x7a50) with 43 callers, so a title that calls `setlocale` with another locale may get a table-driven conversion instead.
DavidSamir commented 2026-10-22 08:49:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by DavidSamir on 2026-10-22T08:49:58Z.


Hi @hypermoist, a merge-order note for #9552 (fix(libc): accept printf argument positions above 99). It edits the same docs/dev/debt/libc.md paragraph as this PR, so they conflict in that file only; the code doesn't meet. Proposal: neither depends on the other, and whichever merges second keeps both sentence changes. Does that work for you? I'll record it in #9552's checklist.

AI-assisted: yes

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6336709902 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855#issuecomment-6336709902). Originally posted by [DavidSamir](https://github.com/DavidSamir) on 2026-10-22T08:49:58Z. --- Hi @hypermoist, a merge-order note for #9552 (`fix(libc): accept printf argument positions above 99`). It edits the same `docs/dev/debt/libc.md` paragraph as this PR, so they conflict in that file only; the code doesn't meet. Proposal: neither depends on the other, and whichever merges second keeps both sentence changes. Does that work for you? I'll record it in #9552's checklist. AI-assisted: yes
hypermoist commented 2026-10-22 09:08:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hypermoist on 2026-10-22T09:08:09Z.


@DavidSamir that works for me. The two PRs only meet in the "narrow printf family" paragraph of docs/dev/debt/libc.md, and neither depends on the other. Whichever merges second keeps both sentence changes. If #9552 lands first, I'll merge main into this branch and combine the paragraph that way.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6337045587 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855#issuecomment-6337045587). Originally posted by [hypermoist](https://github.com/hypermoist) on 2026-10-22T09:08:09Z. --- @DavidSamir that works for me. The two PRs only meet in the "narrow printf family" paragraph of `docs/dev/debt/libc.md`, and neither depends on the other. Whichever merges second keeps both sentence changes. If #9552 lands first, I'll merge `main` into this branch and combine the paragraph that way.
hypermoist commented 2026-10-22 09:09:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hypermoist on 2026-10-22T09:09:47Z.


@JJenkx thanks, that settles the open point. The libc.md entry used to say the locale of a title's own libc.prx was not measured. In a37f8c630a it says a title's bundled libc.prx also converts UTF-8 by default, until setlocale installs a table, and links your comment. The rules in the code didn't need to change, because your three copies agree with what this PR takes from libSceLibcInternal.sprx.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6337076430 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8855#issuecomment-6337076430). Originally posted by [hypermoist](https://github.com/hypermoist) on 2026-10-22T09:09:47Z. --- @JJenkx thanks, that settles the open point. The `libc.md` entry used to say the locale of a title's own `libc.prx` was not measured. In a37f8c630a it says a title's bundled `libc.prx` also converts UTF-8 by default, until `setlocale` installs a table, and links your comment. The rules in the code didn't need to change, because your three copies agree with what this PR takes from `libSceLibcInternal.sprx`.
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!8855
No description provided.