Skip to content

fix(libc): match Windows snprintf overflow behavior - #3982

Closed
MarcZX10 wants to merge 3 commits into
boykopovar:mainfrom
MarcZX10:codex/carry-snprintf-overflow-3974
Closed

MarcZX10 wants to merge 3 commits into
boykopovar:mainfrom
MarcZX10:codex/carry-snprintf-overflow-3974

Conversation

@MarcZX10

@MarcZX10 MarcZX10 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What

  • Match FreeBSD's Windows snprintf/vsnprintf overflow behavior: sizes above INT_MAX + 1 clear the output, set EOVERFLOW, and return -1.
  • Add boundary coverage for INT_MAX, INT_MAX + 1, INT_MAX + 2, SIZE_MAX, null buffers, and preserved errno behavior.
  • Carry the implementation from issue #3974, retaining Hussein Kadhim's commit authorship.
  • On the oversized-size error path, a null buffer is checked before clearing; FreeBSD's reference writes *str = '\0' unconditionally. This is deliberate hardening for that error path, not a general claim that null buffers are accepted.

Tested

  • Linux x86-64, GCC 12.2 Release: built guest_formatting_tests; CTest guest_formatting passed (1/1). This does not exercise the Windows-only branch.
  • The issue author reports passing Windows-specific tests and boundary/differential checks in the issue.
  • tools/check_conventions.py --base upstream/main and git diff --check passed.

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; silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository
  • No new third-party code
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes

@LeandroLP23

Copy link
Copy Markdown
Contributor

Windows run (Windows 11 26300, WinLibs GCC 15.2.0 r7, Release, full build):

@Dextroid17 Dextroid17 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.

Verified against the reference: the boundary is FreeBSD's, exactly. The honest coverage picture is that nothing on this PR builds or runs it — and one sentence of the debt entry is not true for the wide-format route.

Head d5f16993, merged onto my checkout's upstream/main at 752db7da — 145 commits ahead of this PR's own GitHub base 0a8b1d32; Formatting.cpp is unchanged between the two, the test file and TechnicalDebt.md moved and both merged cleanly. The API reports MERGEABLE/CLEAN. This is the fix for #3974, whose own caveat — "Windows only; the Linux glibc path is not covered and was not built" — is the right frame for everything below.

The rule is right, checked against the source rather than the issue

FreeBSD 11.4 lib/libc/stdio/vsnprintf.c, vsnprintf_l:

	on = n;
	if (n != 0)
		n--;
	if (n > INT_MAX) {
		errno = EOVERFLOW;
		*str = '\0';
		return (EOF);
	}

It decrements before comparing, so the overflow point is size > INT_MAX + 1 — which is what size - 1 <= INT_MAX expresses — and the actions line up (*str = '\0', errno = EOVERFLOW, return -1 = EOF). I ran both predicates against each other over 0..199, INT_MAX-3 … INT_MAX+5, and the extremes (2^31, 2^31+1/2/3, 2^32-1, 2^63, 2^64-1): no mismatch on any input, INT_MAX + 1 allowed and INT_MAX + 2 refused, which is the pair your second commit's headline names. The size == 0 disjunct comes first so size - 1 never underflows — and it is load-bearing, since without it SIZE_MAX <= INT_MAX is false and size == 0 would read as an overflow.

The errno is the guest's, and 84 is this tree's established form for it

__error_nid_postfix() returns &errno (core/libs/prx/libc/src/Process.cpp:158-160), so the bare errno here is the guest's slot, and the repo already maps the host's EOVERFLOW onto the guest's 84 (core/libs/prx/libc/src/FileAndHeap.cpp:215 and :226, core/libs/prx/libkernel/File/src/Open.cpp:129-130) and names that value directly (libkernel/KernelErrors.hpp:91, libkernel/Pthread/Posix/Sem.cpp:21). A host macro would give the guest something other than 84 (75 on Linux, and the MS CRT's own value differs again), so the literal is the deliberate and correct form here.

One deliberate divergence worth a clause. FreeBSD writes *str = '\0' in that branch unconditionally; your helper guards the buffer first, so a guest passing (nullptr, INT_MAX + 2) gets -1 where the reference writes through a null pointer. That is a hardening rather than a port, and "as FreeBSD 11.4 does" reads as byte-for-byte — one clause ("ours also accepts a null buffer, where the reference writes through it") removes the puzzle.

Finding — the entry's Linux sentence is not true for the wide-format route

The new debt entry says "On Linux the limit is whatever the host glibc applies". That holds only for the narrow path: snprintf_nid_postfix (core/libs/prx/libc/src/Formatting.cpp:311-317) and vsnprintf_nid_postfix (:407-419) send any format carrying a wide conversion to LibcDetail::FormatWindows, where glibc is not involved and there is no size check — FormatOutput validates the output length, not size (WindowsFormatting.hpp:161-165, ctor at :64). So a guest calling snprintf(buf, INT_MAX + 2, "%ls") on Linux is neither refused with EOVERFLOW — which the console, being FreeBSD-derived, does for that format too — nor handled by glibc. Suggested clause: "…whatever the host glibc applies for the narrow formats; a wide conversion goes to the guest formatter instead, so glibc's limit does not apply to it".

Coverage, as it actually is — and this is the part I would put in the description

Nothing on this PR builds or runs guest_formatting: gh pr checks 3982 reports linux and windows as skipping, both gated to push/workflow_dispatch with full set only for manual dispatch (build.yml:193, :240), and the one PR-time job, relinker, configures -DANYPS5_RELINKER_ONLY=ON, where CMakeLists.txt:71-73 returns before core/libs/prx/libc — the target does not exist in that build at all. What has run the boundary is @LeandroLP23's manual Windows build reported below (3/3 on this base, and guest_formatting aborts with Formatting.cpp reverted), plus the predicate comparison above. My local run — ctest --test-dir build -R '^guest_formatting$' → 1/1 Passed, and nm -C build/tests/guest_formatting_tests | grep -c ExceedsIntMax → 0 — is a non-regression result only, because the new checks sit inside #ifdef _WIN32 (core/libs/tests/Formatting.cpp:136-158).

Also checked, and it holds up

  • Every call site is covered: snprintf directly (Formatting.cpp:277, asserted at test :150, :155, :157) and vsnprintf through FormatList (test :153), whose SIZE_MAX probe exercises the second entry point.
  • sprintf/vsprintf have no size argument to guard, and the entry documents snprintf_s/vsnprintf_s as unlimited — so the scope statement is honest rather than an omission.
  • Author preserved: the commit is Hussein Kadhim's, carried by this PR (gh pr view 3982 --json commits).
  • Context for a reviewer reading the thread: the combined-run failure @LeandroLP23 reports together with #3987 comes from #3987's test still expecting the old %1$d/%'d behaviour, not from this change.

Not verified, so it is not claimed: the console's own libc.prx — as #3974 says, the code is assumed shared with FreeBSD and unchecked on a title — and Windows execution by me; the Windows evidence in this thread is @LeandroLP23's manual build, not mine.

Hermes Agent 🤖 at your service

@oneandonlydean

Copy link
Copy Markdown
Collaborator

Conflicts with main in core/libs/tests/Formatting.cpp (after #3978); please rebase. While there, ExceedsIntMax doesn't need the #ifdef _WIN32: on Linux a format with a wide conversion already goes to FormatWindows with no size check, and with the check on both hosts the Linux sentence in the TechnicalDebt entry can go.

@MarcZX10
MarcZX10 force-pushed the codex/carry-snprintf-overflow-3974 branch from d5f1699 to ad24886 Compare October 12, 2026 17:00
@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 12, 2026
@MarcZX10
MarcZX10 force-pushed the codex/carry-snprintf-overflow-3974 branch from ad24886 to fea57fa Compare October 12, 2026 18:36
@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 12, 2026
@MarcZX10
MarcZX10 force-pushed the codex/carry-snprintf-overflow-3974 branch from fea57fa to e0ca58e Compare October 12, 2026 18:47
@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 12, 2026
@MarcZX10

Copy link
Copy Markdown
Contributor Author

Thanks for the source-level review and boundary comparison. I agree the debt wording should distinguish the narrow Linux path from the wide-conversion path, and the description should call out the deliberate null-buffer hardening difference from FreeBSD. The Windows run reported above confirms the focused boundary test catches the regression on the PR code; the Linux run remains a non-regression check only. I will update the wording to make those limits explicit.

@Dextroid17

Copy link
Copy Markdown
Contributor

Thanks — the rebase reads clean from here too. Head e0ca58e5, force-pushed 18:47:56Z onto main 1acfa7f7 (main has since moved 21 commits, to 3e0e01f3, and the API still reports MERGEABLE/CLEAN), so the conflict in core/libs/tests/Formatting.cpp @oneandonlydean flagged is gone. Every PR-time check is green — conventions, eligibility, relinker on ubuntu/windows/macos, write-watch — with linux/windows still skipping, since full builds are dispatch-only.

One thing that carries across the force-push: ExceedsIntMax is byte-identical between the head I reviewed (d5f16993) and e0ca58e5, so the boundary comparison still describes the current code. Re-ran it against FreeBSD 11.4's decrement-then-compare over 213 inputs (0..199, INT_MAX-3 … INT_MAX+5, 1<<31 +0..3, 0xffffffff, 1<<63, SIZE_MAX): 0 mismatches; largest size allowed 2147483648 (INT_MAX + 1), smallest refused 2147483649 (INT_MAX + 2).

For the record the two wording edits are two different edits, and the second is @oneandonlydean's from the rebase comment:

  • Debt wording (from my review). docs/dev/debt/libc.md still says "…On Linux the limit is whatever the host glibc applies…". Splitting narrow from wide is the right fix: on Linux snprintf_nid_postfix (Formatting.cpp:363-366) hands any format carrying a wide conversion to LibcDetail::FormatWindows, where glibc is not in the picture and no size check runs — so glibc's limit does not govern that route.
  • The #ifdef (oneandonlydean's). The guard is still Windows-only throughout: the helper at Formatting.cpp:34-41, the Windows snprintf_nid_postfix at :328 (inside the block opened at :310), vsnprintf_nid_postfix's Windows arm at :463, and the checks at tests/Formatting.cpp:179-201. If you take their suggestion — check before the wide-format dispatch on both hosts — the Linux sentence becomes deletable rather than narrowable, and the two asks collapse into one. Keeping libc: snprintf and vsnprintf on Windows accept buffer sizes above INT_MAX+1 where FreeBSD returns -1 with EOVERFLOW; fix branch ready #3974's "Windows only" scope is also defensible, but then the entry's Linux sentence and the #ifdef have to be made to agree.

Nothing else is outstanding from my side; the null-buffer hardening clause in the description is the only other wording point.

Hermes Agent 🤖 at your service

husseinkad and others added 3 commits October 12, 2026 20:29
FreeBSD's vsnprintf sets EOVERFLOW, writes an empty string and returns -1 when
the size exceeds INT_MAX. The Windows implementation formatted into the buffer
and returned the length instead.

(cherry picked from commit 646312b)
FreeBSD's vsnprintf subtracts the terminator before comparing with INT_MAX, so
only sizes above INT_MAX + 1 fail with EOVERFLOW.

(cherry picked from commit 0f9fc58)
@MarcZX10
MarcZX10 force-pushed the codex/carry-snprintf-overflow-3974 branch from e0ca58e to e3bf942 Compare October 12, 2026 20:30
@MarcZX10

Copy link
Copy Markdown
Contributor Author

I updated the debt entry to scope the Linux glibc limit to narrow formats and note the guest formatter path for wide conversions (e3bf9429). The description now also states the null-buffer behavior specifically for the oversized-size error path and distinguishes it from FreeBSD. I left the implementation unchanged; the broader Linux guard suggestion would change behavior and needs separate evidence.

@Dextroid17

Copy link
Copy Markdown
Contributor

Both updates read as described, and I would keep the implementation where it is — here is the measurement behind that call.

Read at e3bf9429. The debt entry (docs/dev/debt/libc.md) now splits the two Linux routes and the code agrees: snprintf_nid_postfix (core/libs/prx/libc/src/Formatting.cpp:363-369) hands a format carrying a guest wide conversion to LibcDetail::FormatWindows and everything else to std::vsnprintf, and vsnprintf_nid_postfix splits the same way on its Linux arm (:466-473). On the guest-formatter route the only length guard is on the output, not on size (WindowsFormatting.hpp:95-98 constructor, :100-102 in Append). The description clause is narrowed to the right spot as well: ExceedsIntMax (Formatting.cpp:35-40) tests if (buffer) before it clears, where FreeBSD 11.4 writes *str = '\0' unconditionally.

Enabling the guard on Linux is new Linux behaviour, not extra coverage — with the threshold stated precisely. ExceedsIntMax returns false for size - 1 <= INT_MAX, so it fires from INT_MAX + 2 upward and INT_MAX + 1 stays a deliberate no-op (that is the commit this PR carries). On the Linux narrow route the host checks nothing about size. Measured here (CachyOS, glibc 2.44), calling vsnprintf — the function Formatting.cpp:366 calls — with "%d", 1:

size = INT_MAX       ret=1   errno 0   buffer written
size = INT_MAX + 1   ret=1   errno 0   buffer written
size = INT_MAX + 2   ret=1   errno 0   buffer written
size = INT_MAX + 3   ret=1   errno 0   buffer written

So a Linux guest gets a normal formatted write-back at each of those sizes today, and with the guard on, INT_MAX + 2 and above would return -1 with EOVERFLOW (84) instead. That is a behaviour change on a route #3974 explicitly leaves out — its own caveat is "Windows only; the Linux glibc path is not covered and was not built" — so keeping it out of this PR is right, and it is now a visible separate question rather than one this PR has to answer. (glibc does fail with EOVERFLOW when the output would exceed INT_MAX, but that is the output length, not size.)

One consequence for the wording. "Narrow formats retain the host glibc limit" reads as though glibc enforces something on size, and on this host nothing does, at any size I tested. Neither Linux route applies the check the Windows route now applies: the narrow formats reach the host vsnprintf, and a format containing a guest wide conversion reaches the guest formatter, which bounds the output length rather than size. A clause along those lines would record the state as it is — your wording call, and it does not change the merge decision.

Everything else from the review stands: the predicate comparison against FreeBSD 11.4's decrement-then-compare, the call-site coverage, and the coverage caveat — the relinker job's configure returns before core/libs, so guest_formatting is not a target in that build at all, and the boundary evidence is @LeandroLP23's Windows build plus the predicate differential rather than a PR-time run.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

What shows that the console's snprintf has this check? Its printf family is Dinkumware's (_Printf), not FreeBSD's vfprintf.c, so the FreeBSD 11.4 comparison doesn't cover it. Keeping the check to Windows also leaves the guest's result depending on the host. With a console result, or a title that passes a size above INT_MAX, this can go in on both hosts; otherwise I'll close it.

@Dextroid17

Copy link
Copy Markdown
Contributor

You're right that nothing I measured shows the console's snprintf has this check. The 213-input comparison is against FreeBSD 11.4's decrement-then-compare, and that is the only reference it covers.

You say the console's printf family is Dinkumware's _Printf, not FreeBSD's vfprintf.c. I haven't verified that, and I haven't checked whether the console's snprintf has this check, so the console-side claim is unverified. Please treat the FreeBSD match as a reference comparison only, not evidence of console behaviour.

I'm leaving the implementation as it is until there is evidence either way.

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

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
#4548 core/libs/tests/Formatting.cpp L5
#4995 core/libs/tests/Formatting.cpp L188
docs/dev/debt/libc.md L22

@adriadam10

Copy link
Copy Markdown
Collaborator

Closing, since the premise doesn't hold on the console.

@oneandonlydean asked what shows that the console's snprintf has this check. I disassembled snprintf (eLdDw6l0-bU) in the libc.prx shipped by a real title (Astro's Playroom):

  • It does if (size != 0) size--; and calls _Printf with that size. There is no comparison against INT_MAX and no errno write.
  • The output callback only copies min(remaining, n) bytes.
  • _Printf has no EOVERFLOW (84) store, and its only 0x7fffffff comparisons are in width/precision parsing.

So a size above INT_MAX + 1 is not an error there; the FreeBSD 11.4 vsnprintf.c comparison doesn't apply, because the console's printf family is Dinkumware's. Making this Windows-only would also make the guest result depend on the host.

Welcome to reopen with a console result or a title that passes such a size.

@adriadam10 adriadam10 closed this Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants