fix(libc): throw for 16-bit wide scanf conversions on Linux #3984

Merged
zmeizy merged 2 commits from upstream-pr/3984 into main 2026-10-12 08:37:09 +00:00
zmeizy commented 2026-10-11 20:35:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by zmeizy on 2026-10-11T20:35:24Z.


What

On Linux, sscanf, vsscanf and fscanf give the guest format to glibc. With a wide conversion (%ls, %lc, %l[, %S, %C), glibc stores a 32-bit wchar_t per character into a buffer the guest sized for 16-bit characters. That writes past the end of the buffer: sscanf("ab cd", "%ls", buffer) stores 12 bytes into a 4-character char16_t array.

These functions now throw (NotImplemented_nid_no_patch) on Linux when the format has one of these conversions, instead of corrupting guest memory. Formats without wide conversions are handled as before. Windows is unchanged: it hands %ls, %lc and %l[ to the host, whose wchar_t is 16 bits.

I did not implement the conversion, because how the console decodes the input into UTF-16 is not settled. The narrow printf family writes UTF-8, while the Windows host widens each byte. The gap is recorded in TechnicalDebt.

Tested

Ubuntu 24.04, GCC 13.3, on main 12c22662.

  • guest_formatting: new Linux-only checks call sscanf with %ls, %*s %3lc, %l[a-z], %S and %2$C. Each must throw, with the guest buffer left untouched.
  • They fail on main without the change (the buffer is overwritten) and pass with it.
  • guest_scan_count, guest_wide_formatting, guest_wide_strings and guest_wide_conversion pass.
  • The Windows code is not changed.

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 in TechnicalDebt
  • 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 (n/a)
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes

🤖 Generated with Claude Code

https://claude.ai/code/session_01Ha6Tsy62AFUyp9a5Mf7vjA

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4822153024 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3984). Originally posted by [zmeizy](https://github.com/zmeizy) on 2026-10-11T20:35:24Z. --- ### What On Linux, `sscanf`, `vsscanf` and `fscanf` give the guest format to glibc. With a wide conversion (`%ls`, `%lc`, `%l[`, `%S`, `%C`), glibc stores a 32-bit `wchar_t` per character into a buffer the guest sized for 16-bit characters. That writes past the end of the buffer: `sscanf("ab cd", "%ls", buffer)` stores 12 bytes into a 4-character `char16_t` array. These functions now throw (`NotImplemented_nid_no_patch`) on Linux when the format has one of these conversions, instead of corrupting guest memory. Formats without wide conversions are handled as before. Windows is unchanged: it hands `%ls`, `%lc` and `%l[` to the host, whose `wchar_t` is 16 bits. I did not implement the conversion, because how the console decodes the input into UTF-16 is not settled. The narrow printf family writes UTF-8, while the Windows host widens each byte. The gap is recorded in TechnicalDebt. ### Tested Ubuntu 24.04, GCC 13.3, on `main` `12c22662`. - `guest_formatting`: new Linux-only checks call `sscanf` with `%ls`, `%*s %3lc`, `%l[a-z]`, `%S` and `%2$C`. Each must throw, with the guest buffer left untouched. - They fail on `main` without the change (the buffer is overwritten) and pass with it. - `guest_scan_count`, `guest_wide_formatting`, `guest_wide_strings` and `guest_wide_conversion` pass. - The Windows code is not changed. ### 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 in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [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 (n/a) - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Ha6Tsy62AFUyp9a5Mf7vjA
Dextroid17 commented 2026-10-11 21:26:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Dextroid17 on 2026-10-11T21:26:36Z.

Review: COMMENTED


Verified on Linux: the change does what it says for the conversions it names — and the same write is still reachable two ways this diff leaves alone.

Head d358374a merged onto upstream/main 0a8b1d32 — the tip my checkout had; a later git fetch shows that ref standing 15 commits behind the live main (c5da8233), so read the run as main-of-yesterday. The API reports the PR MERGEABLE/CLEAN against today's base.

Arms

  • PR head: ctest --test-dir build -R '^guest_formatting$' → 1/1 Passed, exit 0.
  • Negative control — only core/libs/prx/libc/src/Formatting.cpp checked out at upstream/main, the new cases kept: exit 134, and the message is the test's own:
    terminate called after throwing an instance of 'std::runtime_error'
    what():  Formatting check failed
    
    thrown by Require (core/libs/tests/Formatting.cpp:20) and terminated in LibcException::DefaultTerminate (core/libs/prx/libc/src/exception/Runtime.cpp:58). So the new cases do fail on the old code.

Artifact-level check, not only the test

Built libs on both revisions and called the produced unpatched/libc.prx directly from a ctypes harness (the unpatched module still carries symbol names):

  • main: sscanf("ab cd", "%ls", buf) → returns 1 and writes 32-bit units into a 16-bit guest buffer.
  • PR: the same call → what(): scanf 16-bit wide conversion on Linux not implemented.
  • Narrow control sscanf("ab cd", "%s", buf) → "ab" on both revisions.

Finding 1 — the _s variants still hand the wide conversion to the host

Same harness, against your libc.prx:

sscanf_s("ab cd", "%ls", char16_t buf, 8) -> r=1
bytes: 61 00 00 00 62 00 00 00 00 00 00 00 21 21 21 21

byte-for-byte the output main produces: a 32-bit wchar_t per character. A guest char16_t wide[4] (8 bytes) still gets 12 bytes written into it — the corruption this PR exists to stop, through a front door the diff does not cover. The capacity argument does not save it either, because the width is a count of guest characters while glibc writes 32-bit units: capacity 3 still writes the full 12 bytes, and only capacity 2 (where the field is cut to a single character) returns without writing.

Route on Linux: sscanf_s (core/libs/prx/libc/src/Formatting.cpp:375 on your tree) and vsscanf_s (:453) go to ScanGuest (:62), which builds each directive with HostLength — a no-op outside _WIN32 (:52) — and hands it to std::sscanf at :144. So %ls reaches glibc as the host's %ls, with a guest-sized buffer.

Fix, whichever you prefer: call RejectGuestWideScan at the _s entry points too, or move the call to the top of ScanGuest behind #ifndef _WIN32 — it reads only the named format argument, before nextPointer()/nextCapacity() consume the va_list, so it cannot disturb that walk — or leave them and say so in the TechnicalDebt line, which today reads as if the %ls family is closed on Linux.

Finding 2 — the reject's skip class is narrower than the one already in the file, so %'ls slips through

RejectGuestWideScan skips "*0123456789$", while the guard already in this file, HasGuestWideFormat (Formatting.cpp:32), skips "-+ #0'0123456789.*$". The new guard therefore rejects less than the old one on the ' flag — and ' is not cosmetic here. I compiled both loops' skip classes and swept the conversion set:

format      new guard    glibc write into a guest 16-bit buffer
%ls         REJECTS      r=1  61 00 00 00 62 00   <- 32-bit stride, caught
%l[         REJECTS      (HasGuestWideFormat misses this one)
%S  %C      REJECTS      caught
%2$C        REJECTS      caught (the loop consumes `$`)
%'ls        passes       r=1  61 00 00 00 62 00   <- 32-bit stride, NOT caught

So sscanf("ab cd", "%'ls", buf) still corrupts exactly as %ls does. One-character fix: reuse the sibling's skip class ("-+ #0'0123456789.*$"), or better, share one helper between HasGuestWideFormat and RejectGuestWideScan so the two cannot drift — they already differ in both directions (%l[ is caught by yours only, %'ls by the sibling only). For what it is worth, the other flags glibc declined in my probe (% lc, %-lc, %#lc, %.3ls), so ' is the actionable one.

Finding 3 — scope of the fix, stated precisely

Everything else in this scanf class is covered, and I re-ran that search repo-wide rather than in one directory: outside ScanGuest, the only sites that hand a guest format to the host scanner are Formatting.cpp:254 (patched), :338 (patched) and :357 (patched); the std::sscanf calls at :144 and :153 are inside ScanGuest itself; swscanf_s (ScanningWide.cpp:381) scans through its own wide scanner and never reaches the host; and the remaining hits elsewhere in the tree parse host-side text with fixed literals, not a guest format.

Not verified, so it is not claimed

  • Windows: Linux only here.
  • The fscanf/vfscanf route (Formatting.cpp:254) is not exercised by the harness — only sscanf (which forwards through vsscanf) and sscanf_s were run, so the diff's third call site is verified by reading, not by running.
  • The positional forms (%2$C) I checked only in the same loop replication and in your test, not by running the built module with a positional format.

The harness is probe_libc_scan.py in my scratch dir, and the loop/skip-class matrix is rejectmatrix.c — say the word and I will paste either here so you can re-run them.

Hermes Agent 🤖 at your service

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5485033445 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3984#pullrequestreview-5485033445). Originally posted by [Dextroid17](https://github.com/Dextroid17) on 2026-10-11T21:26:36Z. **Review:** COMMENTED --- **Verified on Linux: the change does what it says for the conversions it names — and the same write is still reachable two ways this diff leaves alone.** Head `d358374a` merged onto `upstream/main` `0a8b1d32` — the tip my checkout had; a later `git fetch` shows that ref standing 15 commits behind the live `main` (`c5da8233`), so read the run as main-of-yesterday. The API reports the PR `MERGEABLE/CLEAN` against today's base. **Arms** - PR head: `ctest --test-dir build -R '^guest_formatting$'` → `1/1 Passed`, exit 0. - Negative control — only `core/libs/prx/libc/src/Formatting.cpp` checked out at `upstream/main`, the new cases kept: exit **134**, and the message is the test's own: ``` terminate called after throwing an instance of 'std::runtime_error' what(): Formatting check failed ``` thrown by `Require` (`core/libs/tests/Formatting.cpp:20`) and terminated in `LibcException::DefaultTerminate` (`core/libs/prx/libc/src/exception/Runtime.cpp:58`). So the new cases do fail on the old code. **Artifact-level check, not only the test** Built `libs` on both revisions and called the produced `unpatched/libc.prx` directly from a ctypes harness (the unpatched module still carries symbol names): - `main`: `sscanf("ab cd", "%ls", buf)` → returns 1 and writes 32-bit units into a 16-bit guest buffer. - PR: the same call → `what(): scanf 16-bit wide conversion on Linux not implemented`. - Narrow control `sscanf("ab cd", "%s", buf)` → `"ab"` on both revisions. **Finding 1 — the `_s` variants still hand the wide conversion to the host** Same harness, against **your** `libc.prx`: ``` sscanf_s("ab cd", "%ls", char16_t buf, 8) -> r=1 bytes: 61 00 00 00 62 00 00 00 00 00 00 00 21 21 21 21 ``` byte-for-byte the output `main` produces: a 32-bit `wchar_t` per character. A guest `char16_t wide[4]` (8 bytes) still gets 12 bytes written into it — the corruption this PR exists to stop, through a front door the diff does not cover. The capacity argument does not save it either, because the width is a count of *guest* characters while glibc writes 32-bit units: capacity 3 still writes the full 12 bytes, and only capacity 2 (where the field is cut to a single character) returns without writing. Route on Linux: `sscanf_s` (`core/libs/prx/libc/src/Formatting.cpp:375` on your tree) and `vsscanf_s` (`:453`) go to `ScanGuest` (`:62`), which builds each directive with `HostLength` — a no-op outside `_WIN32` (`:52`) — and hands it to `std::sscanf` at `:144`. So `%ls` reaches glibc as the host's `%ls`, with a guest-sized buffer. Fix, whichever you prefer: call `RejectGuestWideScan` at the `_s` entry points too, or move the call to the top of `ScanGuest` behind `#ifndef _WIN32` — it reads only the named `format` argument, before `nextPointer()`/`nextCapacity()` consume the va_list, so it cannot disturb that walk — or leave them and say so in the TechnicalDebt line, which today reads as if the `%ls` family is closed on Linux. **Finding 2 — the reject's skip class is narrower than the one already in the file, so `%'ls` slips through** `RejectGuestWideScan` skips `"*0123456789$"`, while the guard already in this file, `HasGuestWideFormat` (`Formatting.cpp:32`), skips `"-+ #0'0123456789.*$"`. The new guard therefore rejects *less* than the old one on the `'` flag — and `'` is not cosmetic here. I compiled both loops' skip classes and swept the conversion set: ``` format new guard glibc write into a guest 16-bit buffer %ls REJECTS r=1 61 00 00 00 62 00 <- 32-bit stride, caught %l[ REJECTS (HasGuestWideFormat misses this one) %S %C REJECTS caught %2$C REJECTS caught (the loop consumes `$`) %'ls passes r=1 61 00 00 00 62 00 <- 32-bit stride, NOT caught ``` So `sscanf("ab cd", "%'ls", buf)` still corrupts exactly as `%ls` does. One-character fix: reuse the sibling's skip class (`"-+ #0'0123456789.*$"`), or better, share one helper between `HasGuestWideFormat` and `RejectGuestWideScan` so the two cannot drift — they already differ in both directions (`%l[` is caught by yours only, `%'ls` by the sibling only). For what it is worth, the other flags glibc declined in my probe (`% lc`, `%-lc`, `%#lc`, `%.3ls`), so `'` is the actionable one. **Finding 3 — scope of the fix, stated precisely** Everything else in this *scanf* class is covered, and I re-ran that search repo-wide rather than in one directory: outside `ScanGuest`, the only sites that hand a guest format to the host scanner are `Formatting.cpp:254` (patched), `:338` (patched) and `:357` (patched); the `std::sscanf` calls at `:144` and `:153` are inside `ScanGuest` itself; `swscanf_s` (`ScanningWide.cpp:381`) scans through its own wide scanner and never reaches the host; and the remaining hits elsewhere in the tree parse host-side text with fixed literals, not a guest format. **Not verified, so it is not claimed** - Windows: Linux only here. - The `fscanf`/`vfscanf` route (`Formatting.cpp:254`) is not exercised by the harness — only `sscanf` (which forwards through `vsscanf`) and `sscanf_s` were run, so the diff's third call site is verified by reading, not by running. - The positional forms (`%2$C`) I checked only in the same loop replication and in your test, not by running the built module with a positional format. The harness is `probe_libc_scan.py` in my scratch dir, and the loop/skip-class matrix is `rejectmatrix.c` — say the word and I will paste either here so you can re-run them. Hermes Agent 🤖 at your service
TideOPL commented 2026-10-11 22:05:48 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by TideOPL on 2026-10-11T22:05:48Z.


Good catch on the 32-bit wchar_t overflow. One gap and a small note:

  • sscanf_s and vsscanf_s are still affected on Linux. They go through ScanGuest, which builds a host format for each directive ("%" + width + HostLength(length) + specifier), and HostLength returns l unchanged on Linux. So sscanf_s("ab", "%ls", buf, 4) still makes glibc store 32-bit wchar_ts into the 16-bit guest buffer, which is the same overflow this PR fixes for sscanf, vsscanf and fscanf. Calling RejectGuestWideScan there too, or checking length == "l" with s, c or [ (plus S and C) inside ScanGuest, would close it.
  • False positive inside a scanset: RejectGuestWideScan doesn't skip over scanset contents, so a format like "%[^%ls]" is rejected as if it contained %ls. That's harmless in practice; just noting it.

I didn't run this one. The change is Linux-only and I'm on Windows, where these paths go to the 16-bit host wchar_t.

AI-assisted: yes. Written with AI assistance (Claude Code); I reviewed it.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6114356675 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3984#issuecomment-6114356675). Originally posted by [TideOPL](https://github.com/TideOPL) on 2026-10-11T22:05:48Z. --- Good catch on the 32-bit `wchar_t` overflow. One gap and a small note: - **`sscanf_s` and `vsscanf_s` are still affected on Linux.** They go through `ScanGuest`, which builds a host format for each directive (`"%" + width + HostLength(length) + specifier`), and `HostLength` returns `l` unchanged on Linux. So `sscanf_s("ab", "%ls", buf, 4)` still makes glibc store 32-bit `wchar_t`s into the 16-bit guest buffer, which is the same overflow this PR fixes for `sscanf`, `vsscanf` and `fscanf`. Calling `RejectGuestWideScan` there too, or checking `length == "l"` with `s`, `c` or `[` (plus `S` and `C`) inside `ScanGuest`, would close it. - **False positive inside a scanset:** `RejectGuestWideScan` doesn't skip over scanset contents, so a format like `"%[^%ls]"` is rejected as if it contained `%ls`. That's harmless in practice; just noting it. I didn't run this one. The change is Linux-only and I'm on Windows, where these paths go to the 16-bit host `wchar_t`. AI-assisted: yes. Written with AI assistance (Claude Code); I reviewed it.
oneandonlydean commented 2026-10-11 23:19:55 +00:00 (Migrated from github.com)

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


Please cover sscanf_s and vsscanf_s too: they go through ScanGuest, where HostLength leaves l as it is on Linux, so %ls still reaches glibc with the guest's 16-bit buffer. RejectGuestWideScan also needs ' in its skip set, as HasGuestWideFormat has, or %'ls gets past it. Dextroid17's review above has the output for both.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6115032803 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3984#issuecomment-6115032803). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-11T23:19:55Z. --- Please cover `sscanf_s` and `vsscanf_s` too: they go through `ScanGuest`, where `HostLength` leaves `l` as it is on Linux, so `%ls` still reaches glibc with the guest's 16-bit buffer. `RejectGuestWideScan` also needs `'` in its skip set, as `HasGuestWideFormat` has, or `%'ls` gets past it. Dextroid17's review above has the output for both.
zmeizy commented 2026-10-11 23:41:39 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by zmeizy on 2026-10-11T23:41:39Z.


should be good now

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6115214516 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3984#issuecomment-6115214516). Originally posted by [zmeizy](https://github.com/zmeizy) on 2026-10-11T23:41:39Z. --- should be good now
github-actions[bot] commented 2026-10-12 07:38:28 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-12T07:38:28Z.


Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
#4358 docs/dev/TechnicalDebt.md L625
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6119875942 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3984#issuecomment-6119875942). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-12T07:38:28Z. --- <!-- pr-overlap --> Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in **Depends on**. | Pull request | Conflicting files (lines on `main`) | Same exports | Same new files | |---|---|---|---| | #4358 | `docs/dev/TechnicalDebt.md` [L625](https://github.com/boykopovar/AnyPS5/blob/9bc362351780feb4ac57e0c10790ce5727f78cc6/docs/dev/TechnicalDebt.md#L625) | | |
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!3984
No description provided.