Skip to content

fix(libc): follow snprintf_s and sscanf_s constraints as measured on a PS5 - #9087

Open
orezraey wants to merge 31 commits into
boykopovar:mainfrom
orezraey:fix/libc-formatting-measured-ps5
Open

orezraey wants to merge 31 commits into
boykopovar:mainfrom
orezraey:fix/libc-formatting-measured-ps5

Conversation

@orezraey

@orezraey orezraey commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What

snprintf_s, vsnprintf_s, sscanf_s and vsscanf_s followed C11 Annex K with guessed constants. Their debt entries said the constraint handler is not invoked and the console's values are unverified. In a payload process on a PS5 (firmware 13.60, libSceLibcInternal.sprx) most of those guesses differ.

snprintf_s / vsnprintf_s (both behave the same; errno never changes):

Case Payload process, firmware 13.60 main before this PR here now
RSIZE_MAX 2^61 - 1 (a boundary search: 0x1fffffffffffffff passes, 0x2000000000000000 fails) SIZE_MAX >> 1 2^61 - 1
null buffer, size 0 or above RSIZE_MAX -1, buffer untouched, handler called with "snprintf_s: bad argument" (or vsnprintf_s: …), a null pointer and 22 -1, no handler, SIZE_MAX >> 1 accepted as on the console
null format -1, buffer[0] = 0, handler "…: bad format argument" -1, buffer[0] = 0, no handler as on the console
%n / %hn (also after truncation) -23; the output before it stays written without a terminator, then buffer[0] = 0; handler "printf_s: %n disallowed"; the pointer is not written -1, terminated output as on the console
null %s argument (also %.0s) -23, same buffer handling, handler "printf_s: bad %s argument" -1, no handler as on the console
null %ls / %S argument -23, handler "printf_s: bad %ls argument" -1, no handler as on the console

sscanf_s / vsscanf_s (both behave the same):

Case Payload process, firmware 13.60 main before this PR here now
size argument 64 bits: a size of 2^32 + 2 is used as such read as unsigned int 64 bits
%s / %[ field of size or more characters the first size characters stored without a terminator; matching failure, returns the items assigned so far buffer[0] = 0 as on the console
%c with a width above size stores size characters and succeeds, consuming only those failure, buffer[0] = 0 as on the console
%ls / %l[ and %lc with a width above size (titles' own libc.prx, measured by JJenkx) %ls and %l[ follow the narrow rules; %lc stores size units and succeeds, but consumes the whole width %lc consumed only the stored characters as measured
size above RSIZE_MAX handler "scanf_s: bad %c, %s, or %[ size" not checked as on the console
null %s / %c / %[ destination handler "scanf_s: bad %c, %s, or %[ argument", checked before reading input (also on empty input) EOF, no handler as on the console
null integer, %p or floating-point destination checked only after a successful conversion: empty input gives EOF and "x" gives 0, without the handler EOF as on the console
result of any violation the handler with the console's message, a null pointer and 22; returns the assignments so far, or -23 when no conversion (suppressed ones and %n included) has completed EOF as on the console
null input or format EOF, handler "sscanf_s: bad argument" / "vsscanf_s: bad argument" EOF, no handler as on the console
literal mismatch at the end of input ("" with "x%d") 0 EOF 0

fscanf_s / vfscanf_s / scanf_s: a literal mismatch at the end of input now returns the assignments, as sscanf_s does: empty input with "x%2c%n" returns 0 and leaves errno, the %n target and the destination untouched, following JJenkx's CPU-only run of two reference libc modules (earlier heads and main return EOF). %% at the end of input still returns EOF. A %c field takes the same width rule and size clamp as in sscanf_s: %8c%n on abc with size 2 stores ab, sets the count to 2 and leaves c next; with size 4 it stores abc; on abcdef with size 4 it stores abcd and leaves e next (JJenkx's reference rows; main returned 0 before reading). The stream forms were not run on a console.

The -23 is the same with a recording handler, an empty one and ignore_handler_s. set_constraint_handler_s, abort_handler_s and ignore_handler_s are exported, and passing NULL reinstalls the default.

The formatter's terminator: to leave the partial output unterminated on a violation, FormatOutput now writes the terminator once at the end instead of after every piece. Every caller goes through FormatWindows, which does that at the end. On success every output is the same as before, which the existing formatting tests check.

Not measured, recorded in docs/dev/debt/libc.md:

Tests: guest_formatting, guest_scan_count (also JJenkx's wide rows) and guest_strings check the measured cases, with the old expectations updated and size arguments passed as size_t. guest_scan_count fails if the -23 constant is changed.

How the console was measured

  • Setup:
    • The console runs firmware 13.60 and is jailbroken.
    • The probes are ELF payloads built with ps5-payload-dev/sdk v0.44 and clang 18.1.8 and started through elfldr, so they ran in a payload process, not in a title.
  • Provenance: libSceLibcInternal.sprx was loaded with dlopen, and every function was taken from it with dlsym.
  • Method:
    • Buffers are filled with ~ and integer destinations preset to -7.
    • A recording constraint handler logs the message, pointer and error of each call.
    • libcfmt3 and libcfmt4 reinstall the default handler and end their own process with it, to see what it does.
  • Files: the probe sources and full logs are in this gist.
Console output (excerpt, copied unchanged)
libcfmt: meta fw=0x13600007 pid=153 sdk=v0.44 compiler=Clang 18.1.8 built=Oct 21 2026 08:20:42 log=/data/anyps5-probes/libcfmt.log
libcfmt: case snprintf_s truncate size=5 "abcdef" ret=6 errno=0 buf="abcd\x00~~~~~~~~~~~" handler=0
libcfmt: case snprintf_s size=0 ret=-1 errno=0 buf="~~~~~~~~~~~~~~~~" handler=1 msg="snprintf_s: bad argument" err=22 ptr_off=-2
libcfmt: case size_boundary last_ret_1=0x1fffffffffffffff first_ret_-1=0x2000000000000000
libcfmt: case snprintf_s %n ret=-23 errno=0 buf="\x00b~~~~~~~~~~~~~~" handler=1 msg="printf_s: %n disallowed" err=22 ptr_off=-2
libcfmt: case vsscanf_s "abc1" %[a-z] cap=4 ret=1 errno=0 n1=-7 n2=-7 a="abc\x00~~~~" b="~~~~~~~~" handler=0
libcfmt: case vsscanf_s "abcd1" %[a-z] cap=4 ret=0 errno=0 n1=-7 n2=-7 a="abcd~~~~" b="~~~~~~~~" handler=0
libcfmt: case vsscanf_s "x" %3c cap=2 ret=1 errno=0 n1=-7 n2=-7 a="x~~~~~~~" b="~~~~~~~~" handler=0
libcfmt2: case vsscanf_s null %s first ret=-23 n1=-7 n2=-7 f=-7 a="~~~~~~~~" b="~~~~~~~~" handler=1 msg="scanf_s: bad %c, %s, or %[ argument" err=22
libcfmt2: case vsscanf_s "ab" %s cap=2^61 ret=-23 n1=-7 n2=-7 f=-7 a="~~~~~~~~" b="~~~~~~~~" handler=1 msg="scanf_s: bad %c, %s, or %[ size" err=22
libcfmt3: case vsscanf_s "5 ab" %d %s(null) %d ret=1 n1=5 n2=-7 f=-7 a="~~~~~~~~" b="~~~~~~~~" handler=1 msg="scanf_s: bad %c, %s, or %[ argument" err=22

Tested

  • Head 1c3b118df8: main (0263899e99, with fix(libc): retain ordinary short character scan fields #13119) was merged in. Formatting.cpp met in two places: the %n bookkeeping keeps both fix(libc): retain ordinary short character scan fields #13119's ordinary rule and this PR's secure contiguous one, and sscanf uses fix(libc): retain ordinary short character scan fields #13119's ScansInProcess with this PR's null secure name. As agreed with JJenkx, the shared stream %c loop now takes a %c width by its low 32 bits (zero or above INT_MAX reads one) and clamps a secure field to its size instead of failing before reading; guest_stdio_variadic gains five stream rows from JJenkx's matrix (%8c%n on abc with sizes 2 and 4, on abcdef with size 4, %2147483648c and %4294967298c), which fail when the clamp is removed. tests/Formatting.cpp keeps this PR's unterminated %s check and fix(libc): retain ordinary short character scan fields #13119's CheckOrdinaryCharacterScans; libc.md keeps this PR's entries, and fix(libc): retain ordinary short character scan fields #13119's sentence about the secure %c width and size is dropped since both paths now follow those references. At this head guest_formatting, guest_scan_count, guest_stdio_variadic, file_streams and guest_strings pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL, GCC); check_conventions reports no errors (one debt-length warning on a libc.md entry this PR did not add).
  • Head d44f653788: main (b8efa6292a, with fix(libc): print unknown printf conversions and ' as titles' libc.prx does #11907) was merged in. Only core/libs/tests/Formatting.cpp met, in CheckSecureFormat: it keeps this PR's measured snprintf_s/vsnprintf_s checks and adds main's new cases, [%y][%-4k] printed literally (with no constraint call) and %hhn refused with the buffer emptied and the destination untouched. At this head guest_formatting, guest_wide_formatting, guest_scan_count, guest_stdio_variadic and guest_strings pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL, GCC 16.2), and check_conventions reports 0 errors.
  • Head 0f9bb22b03: main (c2eafe4461, with fix(libc): retain short wide scanf character fields #9863 and fix(libc): bound and report the Annex K copies as measured on a PS5 #10270) was merged in. Only libc.md met: it keeps main's wcsncat_s and set_constraint_handler_s entries (the default handler now writes the message and returns), fix(libc): retain short wide scanf character fields #9863's short-field wording in the _WStoul/swscanf_s entry with this PR's measured sscanf_s comparison, and this PR's snwprintf_s sentence. Formatting.cpp now uses SonyRsizeMax from SonyCrt.hpp (same 2^61 - 1) instead of its own secureSizeMax, as agreed with harisibrar1 on this PR. At this head guest_formatting, guest_scan_count, guest_stdio_variadic, guest_strings and guest_safe_errors pass three runs in a row on Windows (MinGW, GCC 15.2) and on Linux (WSL, GCC 16.2); check_conventions reports no errors (one debt-length warning on the long _WStoul entry).
  • Head d826fd16d3: main was merged in, with fix(libc): match bundled narrow scansets and scan directive parsing #12428; the unknown-conversion exit now comes before the secure block. guest_formatting, guest_wide_formatting, guest_scan_count, guest_stdio_variadic, guest_safe_errors and guest_strings pass three runs in a row on Windows (MinGW, GCC 15.2) and on Linux (WSL, GCC); check_conventions passes. Disregard the Linux result recorded for 24f4242cbd: another checkout changed the shared tree while that build ran. This Linux run replaces it, on a tree nothing else touched.
  • Head 24f4242cbd: main (1d91f2966d, with fix(libc): read wide scanf fields byte by byte, as titles' libc.prx does #12468) was merged in and the secure bounds were re-applied on its source scanner: for sscanf_s and vsscanf_s, %ls, %lc and %l[ keep the first size characters without a terminator when they do not fit, and %lc consumes the rest of its width, which now counts bytes as fix(libc): read wide scanf fields byte by byte, as titles' libc.prx does #12468's loop does. Stream forms keep main's behaviour. libc.md keeps fix(libc): read wide scanf fields byte by byte, as titles' libc.prx does #12468's scanf_s wording and this PR's. At this head guest_formatting, guest_scan_count, guest_wide_formatting, guest_stdio_variadic, guest_strings, guest_wide_strings and guest_safe_errors pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC); check_conventions reports no errors.
  • Head e16c92d39f merges main (93dbd0f82a, with feat(libc): add Dinkumware float bit helpers from firmware #8397); only the sscanf_s debt line met feat(libc): add Dinkumware float bit helpers from firmware #8397's new _LDnorm entry, and both are kept. At this head the twelve tests below pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL, GCC 16.2), and check_conventions reports no errors (one debt-length warning on a libc.md entry this PR did not add).
  • Head 053ebd8a33: main (1ff6c8739b) was merged in. Only libc.md met, at the scanf_s and freopen_s entries: it keeps this PR's scanf_s wording with JJenkx's end-of-input result and main's new freopen_s entry with its constraint handler calls. At this head guest_formatting, guest_scan_count, guest_wide_formatting, guest_stdio_variadic, guest_strings and guest_safe_errors pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC); check_conventions passes (the one debt-length warning on the _WStoul entry, as before).
  • Head 29d8de386f: main (3b32cc7b61, with fix(libc): read swscanf scanset ranges and string lengths as titles do #12420) was merged in. Only libc.md met, in the _WStoul/swscanf_s entry: it keeps fix(libc): read swscanf scanset ranges and string lengths as titles do #12420's scanset range, length and %p wording and this PR's measured sscanf_s comparison (64-bit size, first size characters stored without a terminator). At this head guest_formatting, guest_scan_count, guest_wide_formatting, guest_stdio_variadic, guest_strings and guest_safe_errors pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC); check_conventions passes (the one debt-length warning on the _WStoul entry, as before).
  • Head d00ac4ec91: main (0362b1521c, with feat(libc): implement dprintf and vdprintf #12933) was merged in. Only libc.md met: it keeps feat(libc): implement dprintf and vdprintf #12933's new dprintf/vdprintf entry and this PR's measured snprintf_s/vsnprintf_s entry, with the old vsscanf_s entry still removed. At this head guest_formatting, guest_scan_count, guest_wide_formatting, guest_stdio_variadic, guest_strings and guest_safe_errors pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC); check_conventions passes (the one debt-length warning on the _WStoul entry, as before).
  • Head 4eaf64fee1: sscanf_s/vsscanf_s take a %c width by its low 32 bits and read one character when it is zero or above INT_MAX, following JJenkx's reference rows (%2147483648c on abc stores one byte with size 2 or 4; %4294967298c reads two). guest_scan_count gains those three rows, which fail on 16a242bbaa. The stream scanner keeps main's path until fix(libc): retain short stream character scan fields #13057 and fix(libc): retain ordinary short character scan fields #13119 land. At this head guest_formatting, guest_scan_count, guest_wide_formatting, guest_stdio_variadic, guest_strings and guest_safe_errors pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC); check_conventions passes (the one debt-length warning on the _WStoul entry, as before).
  • Head 16a242bbaa: the stream scanner (fscanf_s, vfscanf_s, scanf_s) returns the assignments for a literal mismatch at the end of input, following JJenkx's reference rows. guest_stdio_variadic gains the empty-input "x%2c%n" case (0, errno 97, %n -77 and the 0xa5 destination untouched) and %% at the end of file (EOF); the first check fails on the previous head. The twelve tests listed below pass three runs in a row on Windows (WinLibs GCC) and on Linux (WSL Ubuntu, GCC); check_conventions passes (the existing _WStoul debt-length warning only).
  • Head 3b0fa2fc4d: main (157b02c4f1, with fix(libc): end sscanf and vsscanf at a q length on Linux and macOS #11852) was merged in. Only Formatting.cpp met, in sscanf: it keeps fix(libc): end sscanf and vsscanf at a q length on Linux and macOS #11852's cut at a q length directive (applied to sscanf and vsscanf only, as on main) and this PR's ScanGuest signature with a null secure name. At this head guest_formatting, guest_scan_count, guest_stdio_variadic, guest_strings and guest_safe_errors pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC); check_conventions passes (the one debt-length warning on the _WStoul entry, as before).
  • Head ec862a495a: %lc with a width above size consumes the whole width, following JJenkx's run of titles' libc.prx (PPSA07923, PPSA05916). guest_scan_count gains CheckWideFields with the eight rows of that table, and its two %lc rows fail on acb1ec494f. At this head guest_formatting, guest_scan_count, guest_stdio_variadic, guest_strings and guest_safe_errors pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC); check_conventions passes (the one debt-length warning on the _WStoul entry, as before).
  • Head acb1ec494f: main (f80ce6cec1, with docs(libc): record feholdexcept, fegetexcept, setlocale and strcasecmp as measured on a PS5 #11121) was merged in. Only libc.md met: it keeps this PR's snprintf_s/vsnprintf_s and set_constraint_handler_s wording and its removal of the old vsscanf_s entry, and main's localeconv entry with its removal of the setlocale entry. At this head guest_formatting, guest_scan_count, guest_stdio_variadic, guest_strings and guest_safe_errors pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC); check_conventions passes (the one debt-length warning on the _WStoul entry, as before).
  • Head 0055557985: main (5bdda3661e, with docs(libc): record that libSceLibcInternal does not export memmem or memccpy #10176 and fix(libc): leave errno alone for out-of-range float and double in swscanf #9973) was merged in. Only libc.md met: it keeps this PR's measured sscanf_s/vsscanf_s and _WStoul/swscanf_s entries, main's firmware 13.60 export note on memmem and memccpy and fix(libc): leave errno alone for out-of-range float and double in swscanf #9973's new floating scan errno entry. At this head the twelve tests below pass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC); check_conventions passes (the one debt-length warning on the _WStoul entry, as before).
  • Head 2f05aac2d2: main (5b85225ef3, with feat(libc): add the Annex K stream printf, scanf and freopen_s functions #9527's ScanSource) was merged in 5652af2d1a. This PR's measured sscanf_s/vsscanf_s rules were ported onto ScanSource for StringSource only; StreamSource keeps main's fscanf_s/scanf_s path. 2f05aac2d2 makes feat(libc): add the Annex K stream printf, scanf and freopen_s functions #9527's GuestStdioVariadic checks expect the measured snprintf_s (-23 with a handler call) and undersized sscanf_s %s results instead of the old ones. At this head the twelve tests below pass three runs in a row on Windows and on Linux, and the 49 libc tests matching scan|format|print|string|stdio|safe|constraint|bounds|crt|locale|wide pass on Windows. Before that, head after merging main again (9dbc017c71, with fix(libc): convert scanf integers as FreeBSD does on Windows #9479): efeb582327; only core/libs/tests/Formatting.cpp met, keeping this PR's constraint-handler helpers and measured sscanf_s too-small %s check together with fix(libc): convert scanf integers as FreeBSD does on Windows #9479's CheckIntegerScanWidths and its RunChecks call. At this head the twelve tests below pass three runs in a row on Windows and on Linux (the Linux public_headers audit times out at 30 s on the WSL /mnt/c checkout, unrelated to this change). Before that, main (ac65cf490e, with docs(debt): cite the bundled libc.prx for _Mtx_trylock, strdup and strndup #9613) was merged in b824e3b277; only the strndup and snprintf_s debt lines met, keeping docs(debt): cite the bundled libc.prx for _Mtx_trylock, strdup and strndup #9613's strndup disassembly reading and this PR's measured snprintf_s entry (the old vsscanf_s line stays removed, as its measured sscanf_s entry replaces it). At this head the twelve tests below pass three runs in a row on Windows and on Linux. Before that, main (66e6772ca2, with docs(libc): correct the RSIZE_MAX that swprintf_s and vswprintf_s assume #9360) was merged in 6b9e2f1574; only the snwprintf_s and swprintf_s debt lines met, keeping this PR's snwprintf_s wording and main's swprintf_s limit. Before that, main (f26434afa3, with refactor(libs): add full export headers for libs #10706) was merged in 7b400cbcfe. The tests take their declarations from libc/include/Api.hpp. guest_formatting, guest_scan_count, guest_wide_formatting, guest_wide_stream_scan, guest_stdio_variadic, guest_locale, guest_strings, guest_wide_strings, guest_wide_conversion, guest_safe_errors, guest_crt and guest_bounds_checking pass three runs in a row on Windows (WinLibs GCC) and on Linux (WSL Ubuntu, GCC), which now also builds the #ifndef _WIN32 wide scan path. public_headers audit and check_conventions pass (one debt-length warning on the _WStoul entry, already 3083 characters on main).
    Windows 11, WinLibs GCC 15.2.0, Release: the 30 libc tests whose names cover formatting, scanning, strings, wide characters, streams, locales and bounds checking pass. Linux not built: the #ifndef _WIN32 wide scan path in ScanGuest was changed with the narrow rules and only passed a g++ syntax check, so this PR relies on the Linux CI job to build and run it.

Checklist

orezraey and others added 2 commits October 21, 2026 08:57
…a PS5

Measured on libSceLibcInternal.sprx of a PS5 on firmware 13.60:

- snprintf_s and vsnprintf_s: RSIZE_MAX is 2^61 - 1. A null buffer,
  size 0 or a size above RSIZE_MAX returns -1 with the buffer untouched;
  a null format returns -1 with buffer[0] zeroed; %n or a null %s, %ls
  or %S argument returns -23, keeps the output written before it and
  zeroes buffer[0]. Every violation calls the constraint handler with
  the console's message, a null pointer and EINVAL.
- sscanf_s and vsscanf_s: the size argument is 64 bits. A %s or %[
  field of at least size characters stores its first size characters
  without a terminator and is a matching failure; %c stores at most
  size characters and succeeds. Null destinations and sizes above
  RSIZE_MAX call the handler and return the assignments, or -23 before
  any conversion. A literal mismatch at the end of input returns the
  assignments, and %n counts as a conversion for the EOF result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 7715 docs/dev/debt/libc.md
PR 8965 core/libs/tests/GuestStrings.cpp
docs/dev/debt/libc.md
PR 10007 docs/dev/debt/libc.md
PR 10409 docs/dev/debt/libc.md
PR 11661 docs/dev/debt/libc.md
PR 11689 docs/dev/debt/libc.md
PR 11698 docs/dev/debt/libc.md
PR 12184 docs/dev/debt/libc.md
PR 12849 docs/dev/debt/libc.md
PR 15973 docs/dev/debt/libc.md
PR 16214 docs/dev/debt/libc.md
PR 16516 docs/dev/debt/libc.md
PR 16560 docs/dev/debt/libc.md
PR 16919 docs/dev/debt/libc.md
PR 16924 docs/dev/debt/libc.md
PR 16944 docs/dev/debt/libc.md
PR 16949 docs/dev/debt/libc.md
PR 16975 docs/dev/debt/libc.md
PR 17259 docs/dev/debt/libc.md
PR 17261 docs/dev/debt/libc.md
PR 17277 docs/dev/debt/libc.md
PR 17296 docs/dev/debt/libc.md
PR 17331 docs/dev/debt/libc.md
PR 17539 docs/dev/debt/libc.md
PR 17555 docs/dev/debt/libc.md
PR 17556 docs/dev/debt/libc.md
PR 17557 docs/dev/debt/libc.md
PR 17558 docs/dev/debt/libc.md
PR 17568 docs/dev/debt/libc.md
PR 17578 docs/dev/debt/libc.md
PR 17607 docs/dev/debt/libc.md
PR 17610 docs/dev/debt/libc.md
PR 19434 core/libs/prx/libc/src/Formatting.cpp
PR 22943 core/libs/tests/GuestStrings.cpp
PR 24377 docs/dev/debt/libc.md
PR 25024 core/libs/prx/libc/include/WindowsFormatting.hpp
PR 27339 core/libs/tests/GuestStrings.cpp
PR 28809 core/libs/tests/GuestStdioVariadic.cpp

@MarcZX10

Copy link
Copy Markdown
Contributor

Overlap coordination for a follow-up to #9321: I have a narrow wide-scanner patch for incomplete-exponent and literal-at-EOF behavior. Its code and tests are separate from this PR's measured formatting constraints, but both branches update the same libc debt bullet, which pr_overlap.py flags. Would you prefer that follow-up to depend on this PR and rebase the debt update after yours merges, or do you have another sequencing preference?

@orezraey

Copy link
Copy Markdown
Contributor Author

Thanks for checking. Making your follow-up depend on this PR and rebasing the debt bullet after it merges works for me. If this one is still waiting when yours is ready, go ahead first and I'll rebase the debt bullet here.

@EagleBearerYS

Copy link
Copy Markdown
Contributor

@orezraey a merge-order note: #9479 (Windows scanf integer conversions) adds a check function after CheckWidePrecision in core/libs/tests/Formatting.cpp and a call at the end of RunChecks, where this PR adds its own, so the two conflict in that test file only. The library changes are in different files: this PR's in Formatting.cpp and WindowsFormatting.hpp, #9479's in WindowsScanning.hpp. MarcZX10's code review on #9479 is resolved, and MarcZX10 asked that the two agree on the order (comment). #9479 proposes going first, and this PR would rebase the test file over it, keeping both check functions and both calls. If you'd rather this one went first, say so and #9479 will list it under Depends on and do the rebase itself.

@orezraey

Copy link
Copy Markdown
Contributor Author

Thanks for coordinating. #9479 going first works for me; once it merges I'll rebase this PR's test file over it, keeping both check functions and both calls in RunChecks.

@JJenkx

JJenkx commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

A data point for the set_constraint_handler_s debt line, from a different module than the one it cites. Your text describes libSceLibcInternal.sprx (firmware 13.60), whose default handler writes the message and a newline, then ends the process.

The libc.prx that PPSA13934 ships in sce_module/ behaves differently: its default handler returns. I read this from disassembly, not by measuring.

  • The default handler is installed at load and when NULL is passed. set_constraint_handler_s (ENLfKJEZTjE, 0x4360) stores handler ? handler : 0x43b0. The slot's initial value is an R_X86_64_RELATIVE relocation with addend 0x43b0. That is neither abort_handler_s (0x43e0) nor ignore_handler_s (0x4410).
  • 0x43b0, the default handler, writes the message and a newline, then returns:
    lea    _Stderr,%rbx          ; H8AprKeZtNg, 0x110480
    mov    %rbx,%rsi
    call   fputs                 ; QrZZdJ8XsX0, 0x44a0 (message in rdi)
    mov    $0xa,%edi
    mov    %rbx,%rsi
    call   fputc                 ; aZK8lNei-Qw, 0x4730
    add    $0x8,%rsp
    pop    %rbx
    pop    %rbp
    ret
    
  • abort_handler_s (0x43e0) makes the same two calls, then calls abort (L1SBTkC+Cvw, 0x48d0).

What this means: sources disagree on whether the default handler ends the process. For a title that installs no handler, this bundled libc.prx writes the line to stderr and lets the _s function return its error. That matches the wcsrtombs_s debt line ("writes the message and a newline to stderr before returning").

main's SonyDefaultConstraintHandler calls std::abort() without writing anything. The copies of PPSA07923 and PPSA05916 have the same default handler: fputs and fputc to _Stderr, then ret.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 22, 2026
…les ship

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@orezraey

Copy link
Copy Markdown
Contributor Author

Thanks, that is a useful distinction. In 49903de the set_constraint_handler_s debt entry now records both console modules: libSceLibcInternal.sprx's default handler (measured) writes the message and ends the process, while the libc.prx that PPSA13934, PPSA07923 and PPSA05916 ship writes it to stderr and returns, citing your disassembly here. This PR keeps the current default (abort) so it stays on the measured _s constraints; making the default handler write and return, as the bundled libc.prx this module stands for does, will be a separate PR.

@xXPBSXx

xXPBSXx commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

I ran vsnprintf_s on a PS5 with firmware 11.60 and the values match what this PR implements (the 13.60 measurement it describes). This is a data point for another firmware, not a change request.

Setup: a homebrew payload process (ps5-payload-sdk v0.45, elfldr) on a PS5 with firmware 11.60 (kernel_get_fw_version 0x11600005), calling vsnprintf_s and set_constraint_handler_s from libSceLibcInternal.sprx through dlsym, with a handler that only counts its calls. Run 1 on 2026-11-14 at 06:55 UTC (build a77f15551258), run 2 on 2026-11-14 at 07:55 UTC (build 8348e4c1a649). A title process may differ. The 16-byte buffer has a 16-byte guard area filled with 0x7e.

Call PS5, payload process, firmware 11.60 this PR at 16498b1a6a33 (read from the diff, not run)
"%n" and "a%nb" (run 1, lines 12 and 13) -23, buf[0] = 0, handler called once secureViolationResult = -23
"%s" with a null argument (line 14) -23, buf[0] = 0, handler once -23
size 0 (line 8) -1, buffer untouched, handler once -1, buffer untouched, handler reported
size 0x7fffffffffffffff, 0x8000000000000000, SIZE_MAX (lines 9 to 11) -1, buffer untouched, handler once -1 (size > SonyRsizeMax)
null buffer, size 16 or 0 (lines 16, 17) -1, handler once -1
null format (line 18) -1, buf[0] = 0, handler once -1, buf[0] = 0
"%d" with 42, sizes 16, 3, 2, 1 (lines 3 to 6) 2 (the full length; the text is truncated to fit for sizes 2 and 1), handler not called not run here
largest accepted size and smallest rejected size, bisected (run 2, line 64) accepted 0x1fffffffffffffff, rejected 0x2000000000000000 (the sizes next to it are on lines 65 to 69) rsizeMax = (size_t{1} << 61) - 1 = 0x1fffffffffffffff

So the threshold the console uses is exactly 2^61 - 1, as this PR has it; on main today RsizeMax is SIZE_MAX >> 1, so 0x7fffffffffffffff formats there but returns -1 on the console and here. Not measured: a title process, other firmware, the handler's message text, and what the console does when the handler ends the process instead of returning.

The probe sources and the raw output of both runs follow. The header comments had an internal probe number, which was removed; the code is unchanged, and the build IDs are the hashes of the original files.

run 1: probe.c
#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <ps5/kernel.h>   /* only for kernel_get_fw_version() */

#ifndef PROBE_NAME
#define PROBE_NAME "unnamed"
#endif
#ifndef PROBE_BUILD
#define PROBE_BUILD "unbuilt"
#endif
/* Self limit: on timeout the runner can only close the connection, not end the process on the console.
   The probe ends itself after at most PROBE_MAX_S seconds (the build script sets timeout - 10 s). */
#ifndef PROBE_MAX_S
#define PROBE_MAX_S 50
#endif

static void probe_alarm(int sig) {
  static const char msg[] = "TIMEOUT\tprobe self limit\n";
  (void)sig;
  (void)!write(1, msg, sizeof msg - 1);
  _exit(124);
}

static int cases = 0;

static void probe_header(void) {
  char utc[32];
  time_t now = time(0);
  struct tm tmv;
  gmtime_r(&now, &tmv);
  strftime(utc, sizeof utc, "%Y-%m-%dT%H:%M:%SZ", &tmv);
  printf("PROBE\t%s\tfw=0x%08x\tbuild=%s\tpid=%d\tutc=%s\n", PROBE_NAME, kernel_get_fw_version(), PROBE_BUILD,
         getpid(), utc);
  fflush(stdout);
}

/* CASE: id, description of the call, return value as long, errno (0 if not set), extra (hex/bytes). */
static void probe_case(const char* id, const char* call, long ret, int err, const char* extra) {
  printf("CASE\t%s\t%s\t%ld\t%d\t%s\n", id, call, ret, err, extra ? extra : "-");
  fflush(stdout);
  cases++;
}

static void probe_end(void) {
  printf("END\t%d\n", cases);
  fflush(stdout);
}

#include <dlfcn.h>
#include <setjmp.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>

static sigjmp_buf guard_env;
static volatile int guard_sig = 0;
static volatile int guard_active = 0;
static volatile int guard_hits = 0;
static void guard_handler(int s) {
  static const char msg[] = "FAULT\tprobe guard: fault outside a guarded call or too many faults\n";
  if(!guard_active || ++guard_hits > 8) {
    (void)!write(1, msg, sizeof msg - 1);
    _exit(125);
  }
  guard_sig = s;
  guard_active = 0;
  siglongjmp(guard_env, 1);
}
static void guard_arm(void) {
  struct sigaction sa;
  memset(&sa, 0, sizeof sa);
  sa.sa_handler = guard_handler;
  sigaction(SIGSEGV, &sa, 0);
  sigaction(SIGBUS, &sa, 0);
  sigaction(SIGABRT, &sa, 0);
}
#define CALL(rvar, evar, expr) do { errno = 0; guard_sig = 0; rvar = -1; if(sigsetjmp(guard_env, 1) == 0) { guard_active = 1; rvar = (expr); } guard_active = 0; evar = errno; } while(0)

/* Probe: vsnprintf_s of libSceLibcInternal.sprx (dlsym) on firmware 11.60 (libc.md:118 'snprintf_s and vsnprintf_s follow C11 K.3.5.3.5
   and K.3.5.3.12 ... a null buffer or format, size of 0 or above RSIZE_MAX, any %n and a null %s return a negative value and set buffer[0]
   to zero ... the constraint handler is not invoked, and the console's error value is unverified'). Prototype int vsnprintf_s(char*, size_t,
   const char*, va_list); a wrapper builds the va_list. A constraint handler that only counts calls is set when set_constraint_handler_s
   exists. The buffer is local, 16 bytes plus a 16 byte guard area filled with 0x7e. No %*d and no width. At most 40 calls, each guarded. */
#include <stdarg.h>
typedef int (*vs_fn)(char*, size_t, const char*, va_list);
typedef void (*handler_t)(const char*, void*, int);
typedef handler_t (*sch_fn)(handler_t);
static vs_fn vs;
static volatile int handler_calls = 0;
static void counting_handler(const char* msg, void* ptr, int err) { (void)msg; (void)ptr; (void)err; handler_calls++; }
static int wrap(char* buf, size_t n, const char* fmt, ...) {
  va_list ap;
  va_start(ap, fmt);
  int r = vs(buf, n, fmt, ap);
  va_end(ap);
  return r;
}
static char area[32];
static void cell(const char* id, const char* what, int use_null_buf, size_t n, const char* fmt, long arg) {
  memset(area, 0x7e, sizeof area);
  int r, e;
  handler_calls = 0;
  CALL(r, e, wrap(use_null_buf ? 0 : area, n, fmt, arg));
  char ex[160];
  snprintf(ex, sizeof ex, "rc=%d b0=0x%02x b1=0x%02x b2=0x%02x b3=0x%02x b15=0x%02x b16=0x%02x handler_calls=%d signal=%d", r, (unsigned char)area[0],
           (unsigned char)area[1], (unsigned char)area[2], (unsigned char)area[3], (unsigned char)area[15], (unsigned char)area[16], (int)handler_calls,
           (int)guard_sig);
  probe_case(id, what, guard_sig ? -1 : r, e, ex);
}
int main(void) {
  signal(SIGALRM, probe_alarm);
  alarm(PROBE_MAX_S);
  probe_header();
  guard_arm();
  void* h = dlopen("libSceLibcInternal.sprx", RTLD_LAZY);
  vs = (vs_fn)(h ? dlsym(h, "vsnprintf_s") : 0);
  sch_fn sch = (sch_fn)(h ? dlsym(h, "set_constraint_handler_s") : 0);
  char ex[8];
  snprintf(ex, sizeof ex, "%d%d%d", !!h, !!vs, !!sch);
  probe_case("0", "dlopen libSceLibcInternal.sprx, dlsym vsnprintf_s set_constraint_handler_s (1 yes, 0 no)", 0, 0, ex);
  if(!vs) { probe_end(); return 0; }
  if(sch) sch(counting_handler);
  cell("a.1", "vsnprintf_s(buf, 16, \"%d\", 42)", 0, 16, "%d", 42);
  cell("a.2", "vsnprintf_s(buf, 3, \"%d\", 42) exact fit", 0, 3, "%d", 42);
  cell("a.3", "vsnprintf_s(buf, 2, \"%d\", 42) truncation", 0, 2, "%d", 42);
  cell("a.4", "vsnprintf_s(buf, 1, \"%d\", 42) truncation", 0, 1, "%d", 42);
  cell("a.5", "vsnprintf_s(buf, 16, \"\")", 0, 16, "", 0);
  cell("b.1", "vsnprintf_s(buf, 0, \"%d\", 42)", 0, 0, "%d", 42);
  cell("b.2", "vsnprintf_s(buf, 0x7fffffffffffffff, \"%d\", 42)", 0, 0x7fffffffffffffffULL, "%d", 42);
  cell("b.3", "vsnprintf_s(buf, 0x8000000000000000, \"%d\", 42)", 0, 0x8000000000000000ULL, "%d", 42);
  cell("b.4", "vsnprintf_s(buf, SIZE_MAX, \"%d\", 42)", 0, (size_t)-1, "%d", 42);
  cell("c.1", "vsnprintf_s(buf, 16, \"%n\")", 0, 16, "%n", (long)(intptr_t)&area[24]);
  cell("c.2", "vsnprintf_s(buf, 16, \"a%nb\")", 0, 16, "a%nb", (long)(intptr_t)&area[24]);
  cell("c.3", "vsnprintf_s(buf, 16, \"%s\", NULL)", 0, 16, "%s", 0);
  cell("c.4", "vsnprintf_s(buf, 16, \"x%sy\", \"ab\")", 0, 16, "x%sy", (long)(intptr_t)"ab");
  cell("d.1", "vsnprintf_s(NULL, 16, \"%d\", 42)", 1, 16, "%d", 42);
  cell("d.2", "vsnprintf_s(NULL, 0, \"%d\", 42)", 1, 0, "%d", 42);
  memset(area, 0x7e, sizeof area);
  int r, e;
  handler_calls = 0;
  CALL(r, e, wrap(area, 16, (const char*)0, 0L));
  snprintf(ex, 1, "%s", "");
  char ex2[120];
  snprintf(ex2, sizeof ex2, "rc=%d b0=0x%02x b1=0x%02x handler_calls=%d signal=%d", r, (unsigned char)area[0], (unsigned char)area[1], (int)handler_calls, (int)guard_sig);
  probe_case("e", "vsnprintf_s(buf, 16, NULL format)", guard_sig ? -1 : r, e, ex2);
  probe_end();
  return 0;
}
run 1: raw output
PROBE	libc_vsnprintf_s_wrap	fw=0x11600005	build=a77f15551258	pid=132	utc=2026-11-14T08:37:21Z
CASE	0	dlopen libSceLibcInternal.sprx, dlsym vsnprintf_s set_constraint_handler_s (1 yes, 0 no)	0	0	111
CASE	a.1	vsnprintf_s(buf, 16, "%d", 42)	2	0	rc=2 b0=0x34 b1=0x32 b2=0x00 b3=0x7e b15=0x7e b16=0x7e handler_calls=0 signal=0
CASE	a.2	vsnprintf_s(buf, 3, "%d", 42) exact fit	2	0	rc=2 b0=0x34 b1=0x32 b2=0x00 b3=0x7e b15=0x7e b16=0x7e handler_calls=0 signal=0
CASE	a.3	vsnprintf_s(buf, 2, "%d", 42) truncation	2	0	rc=2 b0=0x34 b1=0x00 b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=0 signal=0
CASE	a.4	vsnprintf_s(buf, 1, "%d", 42) truncation	2	0	rc=2 b0=0x00 b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=0 signal=0
CASE	a.5	vsnprintf_s(buf, 16, "")	0	0	rc=0 b0=0x00 b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=0 signal=0
CASE	b.1	vsnprintf_s(buf, 0, "%d", 42)	-1	0	rc=-1 b0=0x7e b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=1 signal=0
CASE	b.2	vsnprintf_s(buf, 0x7fffffffffffffff, "%d", 42)	-1	0	rc=-1 b0=0x7e b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=1 signal=0
CASE	b.3	vsnprintf_s(buf, 0x8000000000000000, "%d", 42)	-1	0	rc=-1 b0=0x7e b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=1 signal=0
CASE	b.4	vsnprintf_s(buf, SIZE_MAX, "%d", 42)	-1	0	rc=-1 b0=0x7e b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=1 signal=0
CASE	c.1	vsnprintf_s(buf, 16, "%n")	-23	0	rc=-23 b0=0x00 b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=1 signal=0
CASE	c.2	vsnprintf_s(buf, 16, "a%nb")	-23	0	rc=-23 b0=0x00 b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=1 signal=0
CASE	c.3	vsnprintf_s(buf, 16, "%s", NULL)	-23	0	rc=-23 b0=0x00 b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=1 signal=0
CASE	c.4	vsnprintf_s(buf, 16, "x%sy", "ab")	4	0	rc=4 b0=0x78 b1=0x61 b2=0x62 b3=0x79 b15=0x7e b16=0x7e handler_calls=0 signal=0
CASE	d.1	vsnprintf_s(NULL, 16, "%d", 42)	-1	0	rc=-1 b0=0x7e b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=1 signal=0
CASE	d.2	vsnprintf_s(NULL, 0, "%d", 42)	-1	0	rc=-1 b0=0x7e b1=0x7e b2=0x7e b3=0x7e b15=0x7e b16=0x7e handler_calls=1 signal=0
CASE	e	vsnprintf_s(buf, 16, NULL format)	-1	0	rc=-1 b0=0x00 b1=0x7e handler_calls=1 signal=0
END	17
run 2: probe.c
#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <ps5/kernel.h>   /* only for kernel_get_fw_version() */

#ifndef PROBE_NAME
#define PROBE_NAME "unnamed"
#endif
#ifndef PROBE_BUILD
#define PROBE_BUILD "unbuilt"
#endif
/* Self limit: on timeout the runner can only close the connection, not end the process on the console.
   The probe ends itself after at most PROBE_MAX_S seconds (the build script sets timeout - 10 s). */
#ifndef PROBE_MAX_S
#define PROBE_MAX_S 50
#endif

static void probe_alarm(int sig) {
  static const char msg[] = "TIMEOUT\tprobe self limit\n";
  (void)sig;
  (void)!write(1, msg, sizeof msg - 1);
  _exit(124);
}

static int cases = 0;

static void probe_header(void) {
  char utc[32];
  time_t now = time(0);
  struct tm tmv;
  gmtime_r(&now, &tmv);
  strftime(utc, sizeof utc, "%Y-%m-%dT%H:%M:%SZ", &tmv);
  printf("PROBE\t%s\tfw=0x%08x\tbuild=%s\tpid=%d\tutc=%s\n", PROBE_NAME, kernel_get_fw_version(), PROBE_BUILD,
         getpid(), utc);
  fflush(stdout);
}

/* CASE: id, description of the call, return value as long, errno (0 if not set), extra (hex/bytes). */
static void probe_case(const char* id, const char* call, long ret, int err, const char* extra) {
  printf("CASE\t%s\t%s\t%ld\t%d\t%s\n", id, call, ret, err, extra ? extra : "-");
  fflush(stdout);
  cases++;
}

static void probe_end(void) {
  printf("END\t%d\n", cases);
  fflush(stdout);
}

#include <dlfcn.h>
#include <setjmp.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>

static sigjmp_buf guard_env;
static volatile int guard_sig = 0;
static volatile int guard_active = 0;
static volatile int guard_hits = 0;
static void guard_handler(int s) {
  static const char msg[] = "FAULT\tprobe guard: fault outside a guarded call or too many faults\n";
  if(!guard_active || ++guard_hits > 8) {
    (void)!write(1, msg, sizeof msg - 1);
    _exit(125);
  }
  guard_sig = s;
  guard_active = 0;
  siglongjmp(guard_env, 1);
}
static void guard_arm(void) {
  struct sigaction sa;
  memset(&sa, 0, sizeof sa);
  sa.sa_handler = guard_handler;
  sigaction(SIGSEGV, &sa, 0);
  sigaction(SIGBUS, &sa, 0);
  sigaction(SIGABRT, &sa, 0);
}
#define CALL(rvar, evar, expr) do { errno = 0; guard_sig = 0; rvar = -1; if(sigsetjmp(guard_env, 1) == 0) { guard_active = 1; rvar = (expr); } guard_active = 0; evar = errno; } while(0)

/* Probe: size threshold of vsnprintf_s of libSceLibcInternal.sprx (dlsym) on firmware 11.60 (libc.md:118 'size ... above RSIZE_MAX';
   follow-up of an earlier run in which size 0x7fffffffffffffff returned -1 and called the constraint handler, where AnyPS5 formats).
   Prototype int vsnprintf_s(char*, size_t, const char*, va_list). The output "42" is 2 bytes long, so no size writes beyond a 32 byte local
   buffer. Group a: sizes 2^k for k = 4..63 (rc and handler calls; 60 calls); b: bisection between the last accepted and the first rejected
   power of two (at most 64 steps, assumes the accepted sizes form a prefix, which group a shows); c: the sizes next to the threshold. */
#include <stdarg.h>
typedef int (*vs_fn)(char*, size_t, const char*, va_list);
typedef void (*handler_t)(const char*, void*, int);
typedef handler_t (*sch_fn)(handler_t);
static vs_fn vs;
static volatile int handler_calls = 0;
static void counting_handler(const char* msg, void* ptr, int err) { (void)msg; (void)ptr; (void)err; handler_calls++; }
static int wrap(char* buf, size_t n, const char* fmt, ...) {
  va_list ap;
  va_start(ap, fmt);
  int r = vs(buf, n, fmt, ap);
  va_end(ap);
  return r;
}
static char area[32];
static int try_size(size_t n, int* handler_out) {
  memset(area, 0x7e, sizeof area);
  int r, e;
  handler_calls = 0;
  CALL(r, e, wrap(area, n, "%d", 42));
  (void)e;
  if(handler_out) *handler_out = handler_calls;
  return guard_sig ? -1000 : r;
}
int main(void) {
  signal(SIGALRM, probe_alarm);
  alarm(PROBE_MAX_S);
  probe_header();
  guard_arm();
  void* h = dlopen("libSceLibcInternal.sprx", RTLD_LAZY);
  vs = (vs_fn)(h ? dlsym(h, "vsnprintf_s") : 0);
  sch_fn sch = (sch_fn)(h ? dlsym(h, "set_constraint_handler_s") : 0);
  char ex[100];
  snprintf(ex, sizeof ex, "%d%d%d", !!h, !!vs, !!sch);
  probe_case("0", "dlopen libSceLibcInternal.sprx, dlsym vsnprintf_s set_constraint_handler_s (1 yes, 0 no)", 0, 0, ex);
  if(!vs) { probe_end(); return 0; }
  if(sch) sch(counting_handler);
  size_t last_ok = 0, first_bad = 0;
  int hc;
  for(int k = 4; k <= 63; k++) {
    size_t n = (size_t)1 << k;
    int r = try_size(n, &hc);
    char id[16], w[48];
    snprintf(id, sizeof id, "a.%d", k);
    snprintf(w, sizeof w, "vsnprintf_s(buf, 1<<%d, \"%%d\", 42)", k);
    snprintf(ex, sizeof ex, "size=0x%llx rc=%d handler_calls=%d b0=0x%02x b1=0x%02x b2=0x%02x", (unsigned long long)n, r, hc, (unsigned char)area[0], (unsigned char)area[1], (unsigned char)area[2]);
    probe_case(id, w, r, 0, ex);
    if(r >= 0) last_ok = n;
    else if(!first_bad) first_bad = n;
  }
  snprintf(ex, sizeof ex, "last_ok=0x%llx first_bad=0x%llx", (unsigned long long)last_ok, (unsigned long long)first_bad);
  probe_case("a.s", "largest accepted and first rejected power of two", 0, 0, ex);
  if(last_ok && first_bad && first_bad > last_ok) {
    size_t lo = last_ok, hi = first_bad;
    int steps = 0;
    while(hi - lo > 1 && steps < 64) {
      size_t mid = lo + (hi - lo) / 2;
      if(try_size(mid, 0) >= 0) lo = mid; else hi = mid;
      steps++;
    }
    snprintf(ex, sizeof ex, "largest_accepted=0x%llx smallest_rejected=0x%llx steps=%d", (unsigned long long)lo, (unsigned long long)hi, steps);
    probe_case("b", "bisection between last accepted and first rejected size", 0, 0, ex);
    static const long long off[] = {-2, -1, 0, 1, 2};
    for(int i = 0; i < 5; i++) {
      size_t n = lo + (size_t)off[i];
      int r = try_size(n, &hc);
      char id[8], w[48];
      snprintf(id, sizeof id, "c.%d", i);
      snprintf(w, sizeof w, "vsnprintf_s(buf, largest_accepted%+lld)", off[i]);
      snprintf(ex, sizeof ex, "size=0x%llx rc=%d handler_calls=%d", (unsigned long long)n, r, hc);
      probe_case(id, w, r, 0, ex);
    }
  }
  probe_end();
  return 0;
}
run 2: raw output
PROBE	libc_vsnprintf_s_rsize	fw=0x11600005	build=8348e4c1a649	pid=136	utc=2026-11-14T09:37:10Z
CASE	0	dlopen libSceLibcInternal.sprx, dlsym vsnprintf_s set_constraint_handler_s (1 yes, 0 no)	0	0	111
CASE	a.4	vsnprintf_s(buf, 1<<4, "%d", 42)	2	0	size=0x10 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.5	vsnprintf_s(buf, 1<<5, "%d", 42)	2	0	size=0x20 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.6	vsnprintf_s(buf, 1<<6, "%d", 42)	2	0	size=0x40 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.7	vsnprintf_s(buf, 1<<7, "%d", 42)	2	0	size=0x80 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.8	vsnprintf_s(buf, 1<<8, "%d", 42)	2	0	size=0x100 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.9	vsnprintf_s(buf, 1<<9, "%d", 42)	2	0	size=0x200 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.10	vsnprintf_s(buf, 1<<10, "%d", 42)	2	0	size=0x400 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.11	vsnprintf_s(buf, 1<<11, "%d", 42)	2	0	size=0x800 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.12	vsnprintf_s(buf, 1<<12, "%d", 42)	2	0	size=0x1000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.13	vsnprintf_s(buf, 1<<13, "%d", 42)	2	0	size=0x2000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.14	vsnprintf_s(buf, 1<<14, "%d", 42)	2	0	size=0x4000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.15	vsnprintf_s(buf, 1<<15, "%d", 42)	2	0	size=0x8000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.16	vsnprintf_s(buf, 1<<16, "%d", 42)	2	0	size=0x10000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.17	vsnprintf_s(buf, 1<<17, "%d", 42)	2	0	size=0x20000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.18	vsnprintf_s(buf, 1<<18, "%d", 42)	2	0	size=0x40000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.19	vsnprintf_s(buf, 1<<19, "%d", 42)	2	0	size=0x80000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.20	vsnprintf_s(buf, 1<<20, "%d", 42)	2	0	size=0x100000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.21	vsnprintf_s(buf, 1<<21, "%d", 42)	2	0	size=0x200000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.22	vsnprintf_s(buf, 1<<22, "%d", 42)	2	0	size=0x400000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.23	vsnprintf_s(buf, 1<<23, "%d", 42)	2	0	size=0x800000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.24	vsnprintf_s(buf, 1<<24, "%d", 42)	2	0	size=0x1000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.25	vsnprintf_s(buf, 1<<25, "%d", 42)	2	0	size=0x2000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.26	vsnprintf_s(buf, 1<<26, "%d", 42)	2	0	size=0x4000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.27	vsnprintf_s(buf, 1<<27, "%d", 42)	2	0	size=0x8000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.28	vsnprintf_s(buf, 1<<28, "%d", 42)	2	0	size=0x10000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.29	vsnprintf_s(buf, 1<<29, "%d", 42)	2	0	size=0x20000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.30	vsnprintf_s(buf, 1<<30, "%d", 42)	2	0	size=0x40000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.31	vsnprintf_s(buf, 1<<31, "%d", 42)	2	0	size=0x80000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.32	vsnprintf_s(buf, 1<<32, "%d", 42)	2	0	size=0x100000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.33	vsnprintf_s(buf, 1<<33, "%d", 42)	2	0	size=0x200000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.34	vsnprintf_s(buf, 1<<34, "%d", 42)	2	0	size=0x400000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.35	vsnprintf_s(buf, 1<<35, "%d", 42)	2	0	size=0x800000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.36	vsnprintf_s(buf, 1<<36, "%d", 42)	2	0	size=0x1000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.37	vsnprintf_s(buf, 1<<37, "%d", 42)	2	0	size=0x2000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.38	vsnprintf_s(buf, 1<<38, "%d", 42)	2	0	size=0x4000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.39	vsnprintf_s(buf, 1<<39, "%d", 42)	2	0	size=0x8000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.40	vsnprintf_s(buf, 1<<40, "%d", 42)	2	0	size=0x10000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.41	vsnprintf_s(buf, 1<<41, "%d", 42)	2	0	size=0x20000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.42	vsnprintf_s(buf, 1<<42, "%d", 42)	2	0	size=0x40000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.43	vsnprintf_s(buf, 1<<43, "%d", 42)	2	0	size=0x80000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.44	vsnprintf_s(buf, 1<<44, "%d", 42)	2	0	size=0x100000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.45	vsnprintf_s(buf, 1<<45, "%d", 42)	2	0	size=0x200000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.46	vsnprintf_s(buf, 1<<46, "%d", 42)	2	0	size=0x400000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.47	vsnprintf_s(buf, 1<<47, "%d", 42)	2	0	size=0x800000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.48	vsnprintf_s(buf, 1<<48, "%d", 42)	2	0	size=0x1000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.49	vsnprintf_s(buf, 1<<49, "%d", 42)	2	0	size=0x2000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.50	vsnprintf_s(buf, 1<<50, "%d", 42)	2	0	size=0x4000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.51	vsnprintf_s(buf, 1<<51, "%d", 42)	2	0	size=0x8000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.52	vsnprintf_s(buf, 1<<52, "%d", 42)	2	0	size=0x10000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.53	vsnprintf_s(buf, 1<<53, "%d", 42)	2	0	size=0x20000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.54	vsnprintf_s(buf, 1<<54, "%d", 42)	2	0	size=0x40000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.55	vsnprintf_s(buf, 1<<55, "%d", 42)	2	0	size=0x80000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.56	vsnprintf_s(buf, 1<<56, "%d", 42)	2	0	size=0x100000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.57	vsnprintf_s(buf, 1<<57, "%d", 42)	2	0	size=0x200000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.58	vsnprintf_s(buf, 1<<58, "%d", 42)	2	0	size=0x400000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.59	vsnprintf_s(buf, 1<<59, "%d", 42)	2	0	size=0x800000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.60	vsnprintf_s(buf, 1<<60, "%d", 42)	2	0	size=0x1000000000000000 rc=2 handler_calls=0 b0=0x34 b1=0x32 b2=0x00
CASE	a.61	vsnprintf_s(buf, 1<<61, "%d", 42)	-1	0	size=0x2000000000000000 rc=-1 handler_calls=1 b0=0x7e b1=0x7e b2=0x7e
CASE	a.62	vsnprintf_s(buf, 1<<62, "%d", 42)	-1	0	size=0x4000000000000000 rc=-1 handler_calls=1 b0=0x7e b1=0x7e b2=0x7e
CASE	a.63	vsnprintf_s(buf, 1<<63, "%d", 42)	-1	0	size=0x8000000000000000 rc=-1 handler_calls=1 b0=0x7e b1=0x7e b2=0x7e
CASE	a.s	largest accepted and first rejected power of two	0	0	last_ok=0x1000000000000000 first_bad=0x2000000000000000
CASE	b	bisection between last accepted and first rejected size	0	0	largest_accepted=0x1fffffffffffffff smallest_rejected=0x2000000000000000 steps=60
CASE	c.0	vsnprintf_s(buf, largest_accepted-2)	2	0	size=0x1ffffffffffffffd rc=2 handler_calls=0
CASE	c.1	vsnprintf_s(buf, largest_accepted-1)	2	0	size=0x1ffffffffffffffe rc=2 handler_calls=0
CASE	c.2	vsnprintf_s(buf, largest_accepted+0)	2	0	size=0x1fffffffffffffff rc=2 handler_calls=0
CASE	c.3	vsnprintf_s(buf, largest_accepted+1)	-1	0	size=0x2000000000000000 rc=-1 handler_calls=1
CASE	c.4	vsnprintf_s(buf, largest_accepted+2)	-1	0	size=0x2000000000000001 rc=-1 handler_calls=1
END	68

AI-assisted (Claude Code).

@kali113

kali113 commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Second console measurement, on a newer firmware: it agrees with the tables above.

PS5, firmware 13.590.001. A payload called the system libSceLibcInternal.sprx functions by NID with a counting constraint handler installed:

  • snprintf_s: 0x1fffffffffffffff is accepted and 0x2000000000000000, 0x4000000000000000, 0x7fffffffffffffff, 0x8000000000000000, SIZE_MAX and 0 are refused, with handler "snprintf_s: bad argument", 22, return -1 and the buffer untouched. A null buffer gives the same, a null format gives "snprintf_s: bad format argument" with buffer[0] = 0.
  • %n: return -23, handler "printf_s: %n disallowed", 22. "ab%n" at size 32 leaves the bytes 00 62 and the next byte untouched, so the text is written without a terminator and only buffer[0] is cleared. "abcdef%n" at size 3 leaves 00 62, so the text is cut to size - 1 first.
  • Null %s (also %.2s): -23, handler "printf_s: bad %s argument". Null %ls and %S: -23, "printf_s: bad %ls argument". "ab[%s]" leaves 00 62 5b.
  • vsnprintf_s: identical, with its own name in the "bad argument" and "bad format argument" messages and the same "printf_s: ..." text for %n and null strings.
  • sscanf_s: %s with input abc and size 3 stores abc without a terminator and returns 0; size 4 stores abc\0 and returns 1; input abcdefgh with size 5 stores abcde and returns 0. %2c%c over wxyz with size 1 stores w, and the next %c reads x; width 3 with size 2 stores wx and the next reads y; size 0 stores nothing. %[abc] over abcabcX stores size characters for sizes 1 to 4 and returns 0. A null integer or %s destination calls the handler ("scanf_s: bad integer argument", "scanf_s: bad %c, %s, or %[ argument") and returns -23 when nothing was converted before it, or the count (1) when something was; a null input or format returns -1 with "sscanf_s: bad argument".

Not in the tables: sprintf_s and vsprintf_s behave differently and return 0 for every violation (including size 0, an oversized size, a null format or buffer and truncation, where the handler gets "sprintf_s: buffer overflow" with 34). That is covered by #12622 for the titles' libc.prx, not by this PR.

@DerKarussellbremser

Copy link
Copy Markdown
Contributor

Another data point, from a title's own module: the libc.prx bundled with PPSA10122 01.101.000 (SDK 5.00, snprintf_s at 0x5c690), run natively on Windows x86-64 with a recording handler installed through that module's set_constraint_handler_s. Buffers were filled with z and the %n target preset to -7. It agrees with the snprintf_s table above in every row I ran:

Case module
size 2^61 - 1 / 2^61 with "abc" 3, "abc" written / -1, "snprintf_s: bad argument", buffer untouched
null buffer, size 0 or 2^61 -1, "snprintf_s: bad argument", 22, null pointer, buffer untouched
null format, size 1 to 2^61 - 2 -1, buffer[0] = 0, "snprintf_s: bad format argument"
"ab%n", size 8 -23, bytes 00 62 7a… (output before it left unterminated, then buffer[0] = 0), "printf_s: %n disallowed", target still -7
null %s / null %ls -23, buffer[0] = 0, "printf_s: bad %s argument" / "printf_s: bad %ls argument"
errno unchanged in every case

One detail the table does not cover: with a null format and a size of exactly 2^61 - 1, the module reports "snprintf_s: bad argument" and leaves the buffer untouched, while 2^61 - 2 gives "bad format argument" and clears buffer[0]. Its sprintf_s and swprintf_s do the same at that size (on main they report "bad format argument" there); its snwprintf_s does not. I don't think any title passes that size, so it is only for completeness.

In the same run, strcpy_s, strncpy_s, strcat_s, strncat_s, strnlen_s, strtok_s, memcpy_s, memmove_s, memset_s, their wcs/wmem counterparts and snwprintf_s matched main in result, buffer, handler message and error, and errno over 9,838 directed cases. The only differences outside snprintf_s were calls where the module itself faults (memcpy_s/memmove_s with a null destination and a size of 2^61) and the size-2^61 - 1 detail above.

AI-assisted (Claude Code).

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — looks good

Nothing blocks this draft review; one optional consistency point is noted below.

What I ran

Reviewed head 16498b1a6a3393138771095c3d0c487f75098e2c using repo_read.py. No commands or tests were run; this review interface is read-only.

Read all seven changed files listed in manifest.json: WindowsFormatting.hpp, Formatting.cpp, Formatting.cpp tests, GuestScanCount.cpp, GuestStdioVariadic.cpp, GuestStrings.cpp, and libc.md. All were marked included. No exclusions were listed in the manifest; files.json was not available through the reader.

Results

Check Result Note
Changed code review passed Seven changed files read
Tests not run Read-only review interface
Console behavior not run Stream forms unmeasured on-console

Findings

Blocking

None.

Non-blocking

  • The secure stream wide %lc branch keeps the full parsed width and returns early when it exceeds the destination capacity (Formatting.cpp:431); unlike the narrow stream %c branch, it does not apply the low-32-bit width rule and clamp to capacity. The added wide-field tests cover sscanf_s, not the stream variant. Since the description explicitly says stream forms were not run on-console, consider adding a reference-based stream case or recording this as unverified if parity is intended.

Not verified

  • No build or tests were run.
  • PS5 console behavior was not run during this review. The description reports console measurements for formatting and string scanning, and contributor-run reference-module observations for stream scanning; those are author-reported evidence.
  • files.json could not be read through the provided reader.

To get this to a good state

Nothing is required. Optional: add a stream %lc width/capacity case or clarify the intended distinction from the narrow stream %c behavior.

@Queuse

Queuse commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

I closed #11332 as superseded by the merged #25797, which resolves #11292. The #9087-first coordination for my formatting draft is finished.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs libc needs rebase Conflicts with main, rebase needed

Projects

None yet

Development

Successfully merging this pull request may close these issues.