Skip to content

fix(libc): read narrow sscanf scansets by the titles' rules on Linux and macOS too - #25527

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
mnoori11:fix/libc-sscanf-scanset-title-rules
Nov 29, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
mnoori11:fix/libc-sscanf-scanset-title-rules

Conversation

@mnoori11

@mnoori11 mnoori11 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

What

Since #18765, every Linux sscanf and vsscanf runs through ScanSource, as sscanf_s and vsscanf_s already did. Only Windows rewrote a narrow %[...] scanset there with the titles' rules (Formatting.cpp:379-384). Linux and macOS passed the raw set to the host scanner, so glibc's range rules applied:

  • %[z-a] on "za" returned 1, where the titles return 0.
  • %[a-a-c] read "b".
  • %[a-c-e] refused "-".
  • %[a--] read "-".

Linux was also inconsistent with itself, since %l[z-a] and swscanf already return 0 for the first case.

The rules are the ones #12428 (7ca0981) measured with sscanf and sscanf_s against the libc.prx of PPSA07923 and PPSA05916, and recorded in the libc debt entry for narrow scansets:

  • X-Y is a range when a - follows a member and is not last.
  • A reversed range matches nothing.
  • A - first, last or after a range is a member.
  • A ] that opens the set can start a range.

FreeBSD's __sccl reads a-c-e as a..e, like glibc. The title measurement is the reference here, and Windows already follows it.

Scope: on Linux and macOS this changes only the string forms, sscanf, vsscanf, sscanf_s and vsscanf_s. The stream forms do not change: fscanf, vfscanf, scanf, vscanf, their _s forms, and the 16-bit wide stream path. Windows does not change.

TitleScanset moves unchanged from the Windows-only WindowsScanning.hpp into ScanWideField.hpp, which every host includes. ScanSource applies it on Windows as before, and elsewhere only when the source is a string (TSource::Contiguous, true only for StringSource).

Streams are left alone for two reasons:

  • TitleScanset never lists byte 0. A negated set on a stream would then stop at a NUL byte that glibc and FreeBSD's __sccl read through.
  • No stream scan was measured on a console.

A string source cannot hold a NUL before its end: StringSource::Peek returns EOF at the terminator, and the host scanner gets a NUL-terminated string, so the missing NUL member cannot matter there. The rewritten set lists each member byte once, with ] first and ^ and - last, so the host scanner has no range left to interpret. For string sources, InWideScanset and the capped _s overflow probe ("%1" + specifier) get the same explicit list as on Windows.

The debt fragment moves the "fscanf formats without a narrow %c use glibc" sentence into a new entry for stream scansets on Linux and macOS. It changes "On Windows, scansets follow those titles" to name the string forms and Windows. The changed entry is 997 characters.

#18768 edits ScanSource a few lines above this block (scan lengths). The lines are adjacent, but the two PRs change different behaviour. Open #9340 decodes %l[ members as UTF-8 inside InWideScanset. After this change, on Linux and macOS string sources it would get the rewritten byte list, as on Windows today, and its decoder, which rejects a specifier that is not UTF-8, would reject any set with a non-ASCII member, because the rewritten list is sorted by byte (%l[\xc3\xa9] becomes [\xa9\xc3]). #9087, #18380 and #18405 also edit Formatting.cpp without touching the scanset block: #9087 adds sscanf_s constraint checks in ScanSource (it branches on TSource::Contiguous too), and #18380 and #18405 change which Windows formats are scanned in-process.

Tested

Linux (WSL2, kernel 6.6.87.2), x86-64, glibc 2.39, Release build.

guest_formatting:

  • The #ifdef _WIN32 block that holds fix(libc): match bundled narrow scansets and scan directive parsing #12428's scanset table, the length and unknown-conversion rows, and the %*d rows now runs on every host.
  • New table rows cover ], ^ and - members, 0x80-0xff ranges and a negated a-c-e. There are also two capped vsscanf_s rows.
  • On main with the new test, a row-by-row run showed these fix(libc): match bundled narrow scansets and scan directive parsing #12428 rows wrong for both sscanf and vsscanf_s: %[z-a], %[a-a-c] (two rows), %[a-c-e] and %[a--].
  • Of the new rows, %[^a-c-e] fails on main for both functions, and the two capped %[a-c-e] rows (only vsscanf_s) fail as well.
  • The new ]^-, ^a-z and 0x80-0xff rows pass on main too. They guard the rewritten list's encoding.

file_streams:

  • New check: a stream holding a\0b\n read with %[^\n] through fscanf_s, vfscanf_s, fscanf with a narrow %c, and fscanf with %l[^\n]. It consumes all three bytes, as on main.
  • It fails on the first version of this branch, which applied the rewrite to streams.
  • It runs on Linux and macOS only. On Windows the rewrite already applied to streams on main, so by the code that row stops at the NUL. That result is not pinned here.

This PR:

  • guest_formatting, guest_wide_formatting and file_streams pass.
  • The full ctest run on the final head fails only the machine's known failures (WSL2: no GPU, so Vulkan falls back to lavapipe, and the 6.6 kernel lacks asynchronous userfaultfd write protection).

A host check on glibc 2.39 ran sscanf with "%1" plus the rewritten set of 200,000 random scansets on every byte from 1 to 255. It found 0 differences from the titles' membership, so glibc reads the rewritten list literally. macOS was not run. FreeBSD-derived __sccl also takes a leading ] and a - before the closing ] as members, and builds a byte table, so it reads the list the same way.

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 and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved scanset handling for leading ] and ^, negated sets, ranges, and high-byte values across scanning paths.
    • Scans that match input containing an embedded NUL now preserve the matched data and append a terminator.
    • Secure scanset scans with limited destination capacity now correctly distinguish matching input from input that exceeds the scanset.
  • Documentation
    • Expanded notes on differences in scanset behavior across platforms and scanning functions.

@PrivacyOnion PrivacyOnion 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 on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against b3e66a4cc1:

  • Conventions: tools/check_conventions.py passed.
  • Build: file_streams_tests, guest_formatting_tests built cleanly.
  • CTest (file_streams, guest_formatting, guest_sprintf_s_constraints):
    1/3 Test #1415: guest_sprintf_s_constraints ......   Passed    0.00 sec
    2/3 Test #1403: file_streams .....................   Passed    0.14 sec
    3/3 Test #1414: guest_formatting .................   Passed    0.20 sec
    100% tests passed, 0 tests failed out of 3
    
  • Negative control: with core/libs/prx/libc/include/ScanWideField.hpp, core/libs/prx/libc/include/WindowsScanning.hpp, core/libs/prx/libc/src/Formatting.cpp reverted to main and the new tests kept, the suite fails:
    1/3 Test #1414: guest_formatting .................Subprocess aborted***Exception:   0.26 sec
    2/3 Test #1415: guest_sprintf_s_constraints ......   Passed    0.00 sec
    3/3 Test #1403: file_streams .....................   Passed    0.30 sec
    67% tests passed, 1 tests failed out of 3
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified TitleScanset logic in ScanWideField.hpp: correctly parses negated sets, range notation X-Y (including boundary conditions end - member > 2), empty/complement handling, and character ordering according to title specifications.
    • Verified Formatting.cpp ScanSource integration: titleRules evaluates to true on Windows and TSource::Contiguous (StringSource) on non-Windows, correctly restricting the title scanset rewrite to string streams while stream-based scans preserve host behavior as documented.
    • Verified WindowsScanning.hpp refactoring: TitleScanset was moved cleanly to ScanWideField.hpp without regressions or changes to Windows argument scanning.
    • Verified docs/dev/debt/changes/fix-libc-sscanf-scanset-title-rules.md technical debt fragment matches required syntax and accurately records the narrow stream vs string scanset differences.
    • Verified unit tests in Formatting.cpp and FileStreams.cpp: correctly assert TitleScanset behavior on Linux/macOS and stream scanset behavior across narrow/wide/secure paths without state leaks or undefined behavior.

Looks Good To Me

@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

The change applies the title scanset rules to contiguous string scans on Linux and macOS while leaving stream scans unchanged; the inspected implementation and tests support the stated behavior.

What I ran

  • Reviewed head b3e66a4cc18775aba83eb0e8549199f11c037a61 and the prepared diff. No commands or tests were run.

Results

Check Result Note
Changed code review passed Implementation and changed tests inspected
Build and tests not run No local execution

Findings

Blocking

None.

Non-blocking

None.

Not verified

  • Build and runtime results, including the author-reported tests and macOS behavior, were not independently verified.
  • All six changed files listed in the manifest were read. files.json was unavailable; no excluded-file list was reviewed.

To get this to a good state

Nothing is required.

@JJenkx

JJenkx commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Windows check of head b3e66a4cc1, merged onto main 526b7b19d0 (9071120272, clean merge).

Setup: Windows 11 Enterprise 22621, WinLibs GCC 15.2 UCRT, Release.

  • file_streams, guest_formatting, guest_sprintf_s_constraints: pass in each of 3 runs, none skipped.

AI-assisted: yes.

@github-actions

github-actions Bot commented Nov 23, 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 8150 core/libs/tests/FileStreams.cpp
PR 9087 core/libs/prx/libc/src/Formatting.cpp
core/libs/tests/Formatting.cpp
PR 9340 core/libs/prx/libc/include/ScanWideField.hpp
core/libs/prx/libc/src/Formatting.cpp
core/libs/tests/Formatting.cpp
PR 11332 core/libs/prx/libc/src/Formatting.cpp
core/libs/tests/Formatting.cpp
PR 24406 core/libs/prx/libc/src/Formatting.cpp

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

Tested on macOS, which the description lists as changed but did not test.

Setup: Apple M4, macOS 27.0.1, Apple clang 21.0.0, x86_64 Release under Rosetta 2. Head b3e66a4cc1 merged cleanly onto main 44eccbf1b0 plus #17425, #11049, #25331 and #26739 (without #26739 libc does not compile on macOS).

Test This PR Its tests with Formatting.cpp, ScanWideField.hpp and WindowsScanning.hpp from main
guest_formatting passed, 3 of 3 runs fails in the scanset table (Formatting.cpp:868-877, 24 failed checks)
file_streams the new CheckStreamScansetReadsNul passes; the test still aborts at the float-scan check below same

file_streams aborts on this Mac at the %64f %1c%n matching-failure check (FileStreams.cpp:1295 on main, 1339 with this PR), for the same 8 inputs with and without this PR, so the failure is not from this change. #21720 targets that check. To see past it I made Require report and continue in a local copy only: the only failing check is that one, on both trees.

AI-assisted: yes (Claude Code)

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Nov 26, 2026
…and macOS too

sscanf, vsscanf, sscanf_s and vsscanf_s rewrote a %[...] scanset by
the rules measured on the titles' libc.prx only on Windows. On Linux
and macOS the raw set went to the host scanner, whose range rules
differ: %[z-a] on "za" returned 1 where the titles' rule gives 0,
%[a-a-c] on "b" returned 1 (0), %[a-c-e] on "-d" returned 0 (1) and
%[a--] on "-" returned 1 (0).

The string forms now use the same rewrite on every host. TitleScanset
moves unchanged into the header every host includes. The stream forms
on Linux and macOS keep the host scanner's scansets as before: the
rules were measured with the string forms only, and a negated set
there reads through a NUL byte, which the rewritten list would stop
at. A stream test pins that.

The narrow scanset debt entry names the string forms and Windows, and
a new entry records the stream forms on Linux and macOS.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@mnoori11
mnoori11 force-pushed the fix/libc-sscanf-scanset-title-rules branch from b3e66a4 to 88fe8ea Compare November 29, 2026 01:37
@coderabbitai

coderabbitai Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Changes: Scanset handling

Layer / File(s) Summary
Scanset title generation and source selection
core/libs/prx/libc/include/ScanWideField.hpp, core/libs/prx/libc/include/WindowsScanning.hpp, core/libs/prx/libc/src/Formatting.cpp
TitleScanset is added to the shared header and removed from WindowsScanning.hpp. ScanSource uses it on Windows or for contiguous sources. Other non-Windows non-contiguous sources retain the literal scanset text.
Scanset regression coverage and documentation
core/libs/tests/Formatting.cpp, core/libs/tests/FileStreams.cpp, docs/dev/debt/changes/fix-libc-sscanf-scanset-title-rules.md
Formatting tests cover scanset syntax, byte ranges, and secure destination capacity. Non-Windows stream tests cover scansets reading embedded NUL bytes. The debt document records scanner and platform differences.

Suggested reviewers: jjenkx, cocoa55

Change: Bug fix

Merge Risk: Minimal · up to 88fe8

This change makes Linux and macOS string-form sscanf scansets follow the same rules as the console titles. No concrete defect was found, and Linux and Windows test runs were reported as passing. The risk of merging is minimal.

Security architecture risk: Minimal · up to 88fe8

The change affects which bytes existing string scanners match, without adding a way to call them or changing stream behavior. The review did not establish a new security risk.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The new reachability is limited to invoking the existing normalization helper from non-Windows string scans. It changes matching over caller-provided input and destinations, not access to host streams or the authority with which those streams are used.

Trust Boundaries and Controls

  • observed — The scanner locates the closing bracket before normalization. The helper emits a single bracket expression with special characters placed inside it, and the host-format parser skips that expression as a unit. The existing narrow secure path still derives the host width from destination capacity and uses the same scanset for its overflow check.
Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 09be4f58-d69b-4f62-8379-95cd5850ef39
Commits

Reviewing files that changed from the base of the PR and between ffc6f26 and 88fe8ea.

Files selected for processing: 6

  • core/libs/prx/libc/include/ScanWideField.hpp
  • core/libs/prx/libc/include/WindowsScanning.hpp
  • core/libs/prx/libc/src/Formatting.cpp
  • core/libs/tests/FileStreams.cpp
  • core/libs/tests/Formatting.cpp
  • docs/dev/debt/changes/fix-libc-sscanf-scanset-title-rules.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@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 — no blocking findings

The inspected implementation rewrites narrow scansets for contiguous string sources and preserves host scanning for streams; I could not run the reported tests in this review session.

What I ran

Reviewed head 88fe8ea8e9f008a5b5685a2645368d97c3407877 from the prepared diff and pinned source context using repo_read.py. No test commands were run.

Results

Check Result Note
Diff and source review passed All six changed files were included and read
Tests not run Only author-reported results are available

Findings

Blocking

None.

Non-blocking

  • The description reports Linux testing but no macOS run. The host scanner behavior on macOS remains unconfirmed.

Sources

Not verified

  • Did not run guest_formatting, guest_wide_formatting, file_streams, or ctest; the pass/failure summary in the description is author-reported.
  • macOS behavior and physical-console behavior were not run or confirmed.
  • Read the description, commits, manifest, diff, and all six changed files: core/libs/prx/libc/include/ScanWideField.hpp, core/libs/prx/libc/include/WindowsScanning.hpp, core/libs/prx/libc/src/Formatting.cpp, core/libs/tests/FileStreams.cpp, core/libs/tests/Formatting.cpp, and docs/dev/debt/changes/fix-libc-sscanf-scanset-title-rules.md. The reader's file list showed all six as included; no changed file was excluded.

To get this to a good state

Nothing is required. Optionally run the reported tests on macOS to confirm the host scanner handles the rewritten scanset list as expected.

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