fix(libc): follow snprintf_s and sscanf_s constraints as measured on a PS5 #9087
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/9087"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by orezraey on 2026-10-21T12:01:33Z.
What
snprintf_s,vsnprintf_s,sscanf_sandvsscanf_sfollowed 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;
errnonever changes):mainbefore this PRRSIZE_MAX0x1fffffffffffffffpasses,0x2000000000000000fails)SIZE_MAX >> 1size0 or aboveRSIZE_MAX"snprintf_s: bad argument"(orvsnprintf_s: …), a null pointer and 22SIZE_MAX >> 1acceptedbuffer[0]= 0, handler"…: bad format argument"buffer[0]= 0, no handler%n/%hn(also after truncation)buffer[0]= 0; handler"printf_s: %n disallowed"; the pointer is not written%sargument (also%.0s)"printf_s: bad %s argument"%ls/%Sargument"printf_s: bad %ls argument"sscanf_s / vsscanf_s (both behave the same):
mainbefore this PRunsigned int%s/%[field ofsizeor more characterssizecharacters stored without a terminator; matching failure, returns the items assigned so farbuffer[0]= 0%cwith a width abovesizesizecharacters and succeeds, consuming only thosebuffer[0]= 0%ls/%l[and%lcwith a width abovesize(titles' ownlibc.prx, measured by JJenkx)%lsand%l[follow the narrow rules;%lcstoressizeunits and succeeds, but consumes the whole width%lcconsumed only the stored charactersRSIZE_MAX"scanf_s: bad %c, %s, or %[ size"%s/%c/%[destination"scanf_s: bad %c, %s, or %[ argument", checked before reading input (also on empty input)EOF, no handler%por floating-point destinationEOFand"x"gives 0, without the handlerEOF%nincluded) has completedEOFEOF, handler"sscanf_s: bad argument"/"vsscanf_s: bad argument"EOF, no handler""with"x%d")EOFfscanf_s / vfscanf_s / scanf_s: a literal mismatch at the end of input now returns the assignments, as
sscanf_sdoes: empty input with"x%2c%n"returns 0 and leaveserrno, the%ntarget and the destination untouched, following JJenkx's CPU-only run of two referencelibcmodules (earlier heads andmainreturnEOF).%%at the end of input still returnsEOF. A%cfield takes the same width rule and size clamp as insscanf_s:%8c%nonabcwith size 2 storesab, sets the count to 2 and leavescnext; with size 4 it storesabc; onabcdefwith size 4 it storesabcdand leavesenext (JJenkx's reference rows;mainreturned 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_sandignore_handler_sare exported, and passing NULL reinstalls the default.The formatter's terminator: to leave the partial output unterminated on a violation,
FormatOutputnow writes the terminator once at the end instead of after every piece. Every caller goes throughFormatWindows, 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:"<message>\n"before ending the process; AnyPS5's default now writes the message and returns, as thelibc.prxtitles ship does (#9935's change, which reachedmainwith #10270).%yis copied to the output by the console and still throws here.%hsargument was not measured.swscanf_s's size width (it still readsunsigned int) was not measured.Tests:
guest_formatting,guest_scan_count(also JJenkx's wide rows) andguest_stringscheck the measured cases, with the old expectations updated and size arguments passed assize_t.guest_scan_countfails if the -23 constant is changed.How the console was measured
libSceLibcInternal.sprxwas loaded withdlopen, and every function was taken from it withdlsym.~and integer destinations preset to -7.libcfmt3andlibcfmt4reinstall the default handler and end their own process with it, to see what it does.Console output (excerpt, copied unchanged)
Tested
1c3b118df8:main(0263899e99, with #13119) was merged in.Formatting.cppmet in two places: the%nbookkeeping keeps both #13119's ordinary rule and this PR's secure contiguous one, andsscanfuses #13119'sScansInProcesswith this PR's null secure name. As agreed with JJenkx, the shared stream%cloop now takes a%cwidth by its low 32 bits (zero or aboveINT_MAXreads one) and clamps a secure field to its size instead of failing before reading;guest_stdio_variadicgains five stream rows from JJenkx's matrix (%8c%nonabcwith sizes 2 and 4, onabcdefwith size 4,%2147483648cand%4294967298c), which fail when the clamp is removed.tests/Formatting.cppkeeps this PR's unterminated%scheck and #13119'sCheckOrdinaryCharacterScans;libc.mdkeeps this PR's entries, and #13119's sentence about the secure%cwidth and size is dropped since both paths now follow those references. At this headguest_formatting,guest_scan_count,guest_stdio_variadic,file_streamsandguest_stringspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL, GCC);check_conventionsreports no errors (onedebt-lengthwarning on alibc.mdentry this PR did not add).d44f653788:main(b8efa6292a, with #11907) was merged in. Onlycore/libs/tests/Formatting.cppmet, inCheckSecureFormat: it keeps this PR's measuredsnprintf_s/vsnprintf_schecks and addsmain's new cases,[%y][%-4k]printed literally (with no constraint call) and%hhnrefused with the buffer emptied and the destination untouched. At this headguest_formatting,guest_wide_formatting,guest_scan_count,guest_stdio_variadicandguest_stringspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL, GCC 16.2), andcheck_conventionsreports 0 errors.0f9bb22b03:main(c2eafe4461, with #9863 and #10270) was merged in. Onlylibc.mdmet: it keepsmain'swcsncat_sandset_constraint_handler_sentries (the default handler now writes the message and returns), #9863's short-field wording in the_WStoul/swscanf_sentry with this PR's measuredsscanf_scomparison, and this PR'ssnwprintf_ssentence.Formatting.cppnow usesSonyRsizeMaxfromSonyCrt.hpp(same 2^61 - 1) instead of its ownsecureSizeMax, as agreed with harisibrar1 on this PR. At this headguest_formatting,guest_scan_count,guest_stdio_variadic,guest_stringsandguest_safe_errorspass three runs in a row on Windows (MinGW, GCC 15.2) and on Linux (WSL, GCC 16.2);check_conventionsreports no errors (onedebt-lengthwarning on the long_WStoulentry).d826fd16d3:mainwas merged in, with #12428; the unknown-conversion exit now comes before the secure block.guest_formatting,guest_wide_formatting,guest_scan_count,guest_stdio_variadic,guest_safe_errorsandguest_stringspass three runs in a row on Windows (MinGW, GCC 15.2) and on Linux (WSL, GCC);check_conventionspasses. Disregard the Linux result recorded for24f4242cbd: another checkout changed the shared tree while that build ran. This Linux run replaces it, on a tree nothing else touched.24f4242cbd:main(1d91f2966d, with #12468) was merged in and the secure bounds were re-applied on itssourcescanner: forsscanf_sandvsscanf_s,%ls,%lcand%l[keep the firstsizecharacters without a terminator when they do not fit, and%lcconsumes the rest of its width, which now counts bytes as #12468's loop does. Stream forms keepmain's behaviour.libc.mdkeeps #12468'sscanf_swording and this PR's. At this headguest_formatting,guest_scan_count,guest_wide_formatting,guest_stdio_variadic,guest_strings,guest_wide_stringsandguest_safe_errorspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC);check_conventionsreports no errors.e16c92d39fmergesmain(93dbd0f82a, with #8397); only thesscanf_sdebt line met #8397's new_LDnormentry, 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), andcheck_conventionsreports no errors (onedebt-lengthwarning on alibc.mdentry this PR did not add).053ebd8a33:main(1ff6c8739b) was merged in. Onlylibc.mdmet, at thescanf_sandfreopen_sentries: it keeps this PR'sscanf_swording with JJenkx's end-of-input result andmain's newfreopen_sentry with its constraint handler calls. At this headguest_formatting,guest_scan_count,guest_wide_formatting,guest_stdio_variadic,guest_stringsandguest_safe_errorspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC);check_conventionspasses (the onedebt-lengthwarning on the_WStoulentry, as before).29d8de386f:main(3b32cc7b61, with #12420) was merged in. Onlylibc.mdmet, in the_WStoul/swscanf_sentry: it keeps #12420's scanset range, length and%pwording and this PR's measuredsscanf_scomparison (64-bit size, firstsizecharacters stored without a terminator). At this headguest_formatting,guest_scan_count,guest_wide_formatting,guest_stdio_variadic,guest_stringsandguest_safe_errorspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC);check_conventionspasses (the onedebt-lengthwarning on the_WStoulentry, as before).d00ac4ec91:main(0362b1521c, with #12933) was merged in. Onlylibc.mdmet: it keeps #12933's newdprintf/vdprintfentry and this PR's measuredsnprintf_s/vsnprintf_sentry, with the oldvsscanf_sentry still removed. At this headguest_formatting,guest_scan_count,guest_wide_formatting,guest_stdio_variadic,guest_stringsandguest_safe_errorspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC);check_conventionspasses (the onedebt-lengthwarning on the_WStoulentry, as before).4eaf64fee1:sscanf_s/vsscanf_stake a%cwidth by its low 32 bits and read one character when it is zero or aboveINT_MAX, following JJenkx's reference rows (%2147483648conabcstores one byte with size 2 or 4;%4294967298creads two).guest_scan_countgains those three rows, which fail on16a242bbaa. The stream scanner keepsmain's path until #13057 and #13119 land. At this headguest_formatting,guest_scan_count,guest_wide_formatting,guest_stdio_variadic,guest_stringsandguest_safe_errorspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC);check_conventionspasses (the onedebt-lengthwarning on the_WStoulentry, as before).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_variadicgains the empty-input"x%2c%n"case (0,errno97,%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_conventionspasses (the existing_WStouldebt-lengthwarning only).3b0fa2fc4d:main(157b02c4f1, with #11852) was merged in. OnlyFormatting.cppmet, insscanf: it keeps #11852's cut at aqlength directive (applied tosscanfandvsscanfonly, as onmain) and this PR'sScanGuestsignature with a null secure name. At this headguest_formatting,guest_scan_count,guest_stdio_variadic,guest_stringsandguest_safe_errorspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC);check_conventionspasses (the onedebt-lengthwarning on the_WStoulentry, as before).ec862a495a:%lcwith a width abovesizeconsumes the whole width, following JJenkx's run of titles'libc.prx(PPSA07923, PPSA05916).guest_scan_countgainsCheckWideFieldswith the eight rows of that table, and its two%lcrows fail onacb1ec494f. At this headguest_formatting,guest_scan_count,guest_stdio_variadic,guest_stringsandguest_safe_errorspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC);check_conventionspasses (the onedebt-lengthwarning on the_WStoulentry, as before).acb1ec494f:main(f80ce6cec1, with #11121) was merged in. Onlylibc.mdmet: it keeps this PR'ssnprintf_s/vsnprintf_sandset_constraint_handler_swording and its removal of the oldvsscanf_sentry, and main'slocaleconventry with its removal of thesetlocaleentry. At this headguest_formatting,guest_scan_count,guest_stdio_variadic,guest_stringsandguest_safe_errorspass three runs in a row on Windows (WinLibs GCC 15.2) and on Linux (WSL2, GCC);check_conventionspasses (the onedebt-lengthwarning on the_WStoulentry, as before).0055557985:main(5bdda3661e, with #10176 and #9973) was merged in. Onlylibc.mdmet: it keeps this PR's measuredsscanf_s/vsscanf_sand_WStoul/swscanf_sentries,main's firmware 13.60 export note onmemmem and memccpyand #9973's newfloating scan errnoentry. 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_conventionspasses (the onedebt-lengthwarning on the_WStoulentry, as before).2f05aac2d2:main(5b85225ef3, with #9527'sScanSource) was merged in5652af2d1a. This PR's measuredsscanf_s/vsscanf_srules were ported ontoScanSourceforStringSourceonly;StreamSourcekeepsmain'sfscanf_s/scanf_spath.2f05aac2d2makes #9527'sGuestStdioVariadicchecks expect the measuredsnprintf_s(-23 with a handler call) and undersizedsscanf_s%sresults 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 matchingscan|format|print|string|stdio|safe|constraint|bounds|crt|locale|widepass on Windows. Before that, head after mergingmainagain (9dbc017c71, with #9479):efeb582327; onlycore/libs/tests/Formatting.cppmet, keeping this PR's constraint-handler helpers and measuredsscanf_stoo-small%scheck together with #9479'sCheckIntegerScanWidthsand itsRunCheckscall. At this head the twelve tests below pass three runs in a row on Windows and on Linux (the Linuxpublic_headersaudit times out at 30 s on the WSL/mnt/ccheckout, unrelated to this change). Before that,main(ac65cf490e, with #9613) was merged inb824e3b277; only thestrndupandsnprintf_sdebt lines met, keeping #9613'sstrndupdisassembly reading and this PR's measuredsnprintf_sentry (the oldvsscanf_sline stays removed, as its measuredsscanf_sentry 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 #9360) was merged in6b9e2f1574; only thesnwprintf_sandswprintf_sdebt lines met, keeping this PR'ssnwprintf_swording andmain'sswprintf_slimit. Before that,main(f26434afa3, with #10706) was merged in7b400cbcfe. The tests take their declarations fromlibc/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_crtandguest_bounds_checkingpass three runs in a row on Windows (WinLibs GCC) and on Linux (WSL Ubuntu, GCC), which now also builds the#ifndef _WIN32wide scan path.public_headersaudit andcheck_conventionspass (onedebt-lengthwarning on the_WStoulentry, already 3083 characters onmain).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 _WIN32wide scan path inScanGuestwas changed with the narrow rules and only passed ag++syntax check, so this PR relies on the Linux CI job to build and run it.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)mainwith #10270; #7851 (hypermoist) addslibc.mdentries next to the ones this PR edits (merge order only); #12574 (JJenkx) editslibc.mdlines this PR changes (merge order only); #12627 (JJenkx) rewrites thesnwprintf_sandswprintf_sentries this PR edits inlibc.md(merge order only); #12598 (JJenkx) rewrites theqsort_sentry next to thelibc.mdentries this PR edits (merge order only); #9688, #9863, #10729, #11621, #11907, #12397, #12468, #12530, #12532 and #13119 have mergedImported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-21T18:36:44Z.
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.pyflags. 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?Imported from boykopovar/AnyPS5. Originally posted by orezraey on 2026-10-21T19:33:48Z.
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.
Imported from boykopovar/AnyPS5. Originally posted by EagleBearerYS on 2026-10-22T03:43:37Z.
@orezraey a merge-order note: #9479 (Windows
scanfinteger conversions) adds a check function afterCheckWidePrecisionincore/libs/tests/Formatting.cppand a call at the end ofRunChecks, 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 inFormatting.cppandWindowsFormatting.hpp, #9479's inWindowsScanning.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.Imported from boykopovar/AnyPS5. Originally posted by orezraey on 2026-10-22T03:50:34Z.
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.Imported from boykopovar/AnyPS5. Originally posted by JJenkx on 2026-10-22T04:28:12Z.
A data point for the
set_constraint_handler_sdebt line, from a different module than the one it cites. Your text describeslibSceLibcInternal.sprx(firmware 13.60), whose default handler writes the message and a newline, then ends the process.The
libc.prxthat PPSA13934 ships insce_module/behaves differently: its default handler returns. I read this from disassembly, not by measuring.NULLis passed.set_constraint_handler_s(ENLfKJEZTjE, 0x4360) storeshandler ? handler : 0x43b0. The slot's initial value is anR_X86_64_RELATIVErelocation with addend 0x43b0. That is neitherabort_handler_s(0x43e0) norignore_handler_s(0x4410).abort_handler_s(0x43e0) makes the same two calls, then callsabort(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.prxwrites the line tostderrand lets the_sfunction return its error. That matches thewcsrtombs_sdebt line ("writes the message and a newline tostderrbefore returning").main'sSonyDefaultConstraintHandlercallsstd::abort()without writing anything. The copies of PPSA07923 and PPSA05916 have the same default handler:fputsandfputcto_Stderr, thenret.Imported from boykopovar/AnyPS5. Originally posted by harisibrar1 on 2026-10-24T13:28:42Z.
Review: APPROVED
Checked against main
6cd36e6517and the libcfmt/libcfmt2/libcfmt3/libcfmt4 logs and probe sources in the linked gist:snprintf_s/vsnprintf_s/vsscanf_s/sscanf_scase throughFormatSecure,FormatOutputandScanGuestat this head, and each matches the console's return value, buffer bytes and handler message (including%*s/%ncounting as a completed conversion, the size check coming before the end-of-input check, and%nafter truncation leaving"\0b"). The branch still merges cleanly with current main.BoundsChecking.cppalready uses 2^61 - 1, and #10270 and #8965 measured the same limit,EINVALand a null handler pointer.snwprintf_s(FormattingWide.cpp:247, and its debt line sayingRSIZE_MAXis assumed to beSIZE_MAX >> 1) will now disagree withsnprintf_son the size limit. Could the debt line mention it, or could it get its own PR?SonyRsizeMaxtoSonyCrt.hpp, which this file already includes, so whichever lands second could reuse it instead of definingsecureSizeMaxagain."x" %s cap=SIZE_MAXactually runs"%*s %s"(libcfmt3_main.c:158), which is why it returns 0 rather than -23. Fixing the label would help later readers.Reviewed with AI assistance (Claude Code); the checks above were run locally on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-20T08:10:23Z.
Review: APPROVED
Reviewed — looks good
Nothing blocks this draft review; one optional consistency point is noted below.
What I ran
Reviewed head
16498b1a6a3393138771095c3d0c487f75098e2cusingrepo_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.cpptests,GuestScanCount.cpp,GuestStdioVariadic.cpp,GuestStrings.cpp, andlibc.md. All were marked included. No exclusions were listed in the manifest;files.jsonwas not available through the reader.Results
Findings
Blocking
None.
Non-blocking
%lcbranch keeps the full parsed width and returns early when it exceeds the destination capacity (Formatting.cpp:431); unlike the narrow stream%cbranch, it does not apply the low-32-bit width rule and clamp to capacity. The added wide-field tests coversscanf_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
files.jsoncould not be read through the provided reader.To get this to a good state
Nothing is required. Optional: add a stream
%lcwidth/capacity case or clarify the intended distinction from the narrow stream%cbehavior.View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.