Skip to content

feat(libc): implement the remaining C11 Annex K bounds-checking functions - #7841

Merged
adriadam10 merged 4 commits into
boykopovar:mainfrom
hypermoist:feat/libc-annex-k-remaining
Oct 21, 2026
Merged

adriadam10 merged 4 commits into
boykopovar:mainfrom
hypermoist:feat/libc-annex-k-remaining

Conversation

@hypermoist

@hypermoist hypermoist commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds the eight C11 Annex K exports that libc was still missing, in a new src/BoundsChecking.cpp: abort_handler_s, bsearch_s, wcstok_s, wctomb_s, wcrtomb_s, mbstowcs_s, mbsrtowcs_s and gets_s.

Each one follows the console's own checks, messages and error codes (read from the console disassembly). Violations go through the existing SonyInvokeConstraintHandler as (message, NULL, error), the same way the console's helper calls the handler:

  • bsearch_s: "bsearch_s: bad argument" when nmemb or size exceeds RSIZE_MAX (2^61 - 1), or key/base/compar is null. A zero nmemb returns NULL without a violation. The search is FreeBSD's bsearch loop, so the same element is returned among equal ones and compar is called the same number of times.
  • wcstok_s: "bad argument", "missing token" (also for *s1max == 0) and "missing delimiter", with *s1max decremented exactly like the console's.
  • wctomb_s, wcrtomb_s: argument checks per the console (including which failures clear s[0] and set *retval = -1). A temporary buffer and the "buffer too small"/ERANGE violation apply only when MB_CUR_MAX > smax. A character the locale can't encode returns EILSEQ without calling the handler.
  • mbstowcs_s, mbsrtowcs_s: count when dst is null, convert up to min(len, dstmax) characters, report "buffer overflow" / "buffer too small" (ERANGE, dst[0] cleared) when dstmax fills, and update *src the way the console does (NULL after the terminator, the stop position otherwise, untouched when counting or when len is 0).
  • gets_s: "zero buffer size", "bad argument", and "short buffer" (ERANGE), after which the rest of the line is discarded and s[0] cleared. End of file before any character clears s[0] and returns NULL.
  • abort_handler_s: writes the message and a newline to the guest stderr, then aborts.

The multibyte functions convert through the existing wcrtomb, wctomb and mbrtowc, so they follow the C locale those implement. That locale is single-byte here, so a character above 0xFF is EILSEQ in wctomb_s/wcrtomb_s, each byte is one wide character in mbstowcs_s/mbsrtowcs_s, and the wcrtomb_s too-small path and the EILSEQ paths of the two string functions are not reached. A docs/dev/debt/libc.md entry records this; #8855 moves the locale to the console's UTF-8.

Tested

Linux (CachyOS, GCC Release): new guest_bounds_checking test (stdin is redirected to a scratch file for gets_s). The libc/guest tests pass, except guest_kernel_fcntl, which failed once under ctest -j16 and passes on its own; it's unrelated. All eight NIDs are in the patched libc.prx. tools/check_conventions.py passes, and tools/pr_overlap.py --branch reports no line overlap.

Differential test against the console: a retail libc.prx (J03848509) was mapped into a Linux process with a recording handler in its constraint-handler slot. bsearch_s (300,000 random sorted arrays, keys and bad arguments) and wcstok_s (300,000 full tokenizing sequences with random strings, delimiter sets, s1max values and bad arguments) matched this implementation exactly: return values, *s1max, the context pointer, buffer contents, the number of comparator calls, and every handler call's message, pointer and error. The multibyte functions and gets_s read locale state through TLS or call stdio on the console, so they couldn't run in the harness. They are ports of the disassembled control flow and are covered by the unit test.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed 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

…ions

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

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Progress report (05f9995 → 7b336be)

📈 System libraries: 62.29% (+0.04%, +8 implemented functions)

✅ 8 implemented
Library Name
libc abort_handler_s_nid_postfix
libc bsearch_s_nid_postfix
libc gets_s_nid_postfix
libc mbsrtowcs_s_nid_postfix
libc mbstowcs_s_nid_postfix
libc wcrtomb_s_nid_postfix
libc wcstok_s_nid_postfix
libc wctomb_s_nid_postfix

@github-actions

github-actions Bot commented Oct 19, 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 3965 core/libs/prx/libc/CMakeLists.txt
docs/dev/debt/libc.md
PR 4627 core/libs/prx/libc/CMakeLists.txt
PR 5021 core/libs/prx/libc/CMakeLists.txt
docs/dev/debt/libc.md
PR 6044 core/libs/prx/libc/CMakeLists.txt
PR 6469 docs/dev/debt/libc.md
PR 6819 core/libs/prx/libc/CMakeLists.txt
docs/dev/debt/libc.md
PR 6879 docs/dev/debt/libc.md
PR 7081 core/libs/prx/libc/CMakeLists.txt
docs/dev/debt/libc.md
PR 7201 core/libs/prx/libc/CMakeLists.txt
PR 7447 core/libs/prx/libc/CMakeLists.txt
docs/dev/debt/libc.md
PR 7648 docs/dev/debt/libc.md
PR 7715 core/libs/prx/libc/CMakeLists.txt
docs/dev/debt/libc.md
PR 8150 core/libs/prx/libc/CMakeLists.txt
docs/dev/debt/libc.md
PR 8520 core/libs/prx/libc/CMakeLists.txt
docs/dev/debt/libc.md
PR 8546 docs/dev/debt/libc.md
PR 8550 docs/dev/debt/libc.md
PR 8658 core/libs/prx/libc/CMakeLists.txt

@fogydes fogydes 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 the diff and test design:

  • BoundsChecking.cpp: Cleanly implements the remaining C11 Annex K bounds-checking interfaces (abort_handler_s, bsearch_s, gets_s, mbsrtowcs_s, mbstowcs_s, wcrtomb_s, wcstok_s, wctomb_s) respecting runtime-constraint handlers and bounds parameters.
  • GuestBoundsChecking.cpp: Unit tests verify search comparators with context, wide-to-multibyte and multibyte-to-wide conversions with null/non-null states, tokenization with delimiter state, and temporary file reading with buffer bounds enforcement.
  • Properly configures configure_windows_unwind and DLL path prepending for Windows in CMakeLists.txt.
  • Zero comments added in code; Conventional Commits title; all CI checks pass.

Ready to merge.

AI-assisted: yes

@adriadam10 adriadam10 self-assigned this Oct 19, 2026
@Athen2045

Athen2045 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Windows run of 2c1f967 merged onto main 3611cda (Windows 11 26300, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON):

  • Build: clean, with no warnings in BoundsChecking.cpp.
  • guest_bounds_checking: passes, 5 out of 5 repeated runs, including the gets_s cases that read the scratch file through the guest __stdinp.
  • abort_handler_s isn't called by the test, so I called it from a small harness (not committed). The harness loads the patched libc.prx, resolves SmYrO79NzeI and calls it in a child process.
    • ("bsearch_s: bad argument", NULL, 22): the first stderr line is exactly bsearch_s: bad argument.
    • ("", NULL, 22): the first line is empty.
    • In both cases libc's Windows crash report follows (FATAL: abort() (SIGABRT) ...), and the process exits with 0xc0000409, the same as the other abort() paths on Windows.
  • Full suite (select_tests.py ctest ... --timeout 120): 1709 of 1714 pass. The same 5 tests fail on main on this machine: conventions_env_reference, conventions_blob_reads, windows_import_modules, agc_driver_msaa_dcc_clear_4 and agc_driver_pass_input_hazard. guest_kernel_fcntl passed in the parallel run.

AI-assisted: yes (Claude Code). The results above were run on this machine.

Edit: corrected the base commit from 585075c to 3611cda, the main these runs were actually built on. The results are unchanged.

@Chuk49 Chuk49 mentioned this pull request Oct 20, 2026
12 tasks done
@nikowolf123

Copy link
Copy Markdown
Contributor

The PR adds no docs/dev/debt/libc.md entry for a gap its description names. wctomb_s, wcrtomb_s, mbstowcs_s and mbsrtowcs_s convert through this libc's single-byte C locale (___mb_cur_max returns 1). CONTRIBUTING.md asks for gaps like this (what differs from the console, what is unverified) to go in the debt file. The sibling wcsrtombs_s entry records the same gap. Ghost of Yotei imports mbstowcs_s (tdcAqgCS+uI in #8383), so a title already uses one of these functions.

What this means at this head:

  • wctomb_s(&status, buf, 4, 0x263A) returns 86 with status == -1, and GuestBoundsChecking.cpp#L133 asserts it. libc.md#L93 records a PS5 measurement where the system libSceLibcInternal locale encodes U+263A as E2 98 BA. The locale of the libc.prx that titles bundle was not measured.
  • mbstowcs_s turns the UTF-8 bytes E2 98 BA into three wide characters (0xE2, 0x98, 0xBA). A UTF-8 locale gives one.
  • The wcrtomb_s "buffer too small" branch at BoundsChecking.cpp#L157 needs MB_CUR_MAX > smax, but smax is at least 1 there. The EILSEQ branches at #L184, #L198, #L232 and #L246 need mbrtowc to fail, but it returns only 0 or 1 for a non-null source. No input reaches these ported paths, so the test can't cover them.

I'd add a line in the style of the wcsrtombs_s one, for example:

- [wctomb_s, wcrtomb_s, mbstowcs_s and mbsrtowcs_s](../../../core/libs/prx/libc/src/BoundsChecking.cpp) (libc) follow the console's `libc.prx`, but convert in the single-byte C locale of `wctomb`, `wcrtomb` and `mbrtowc` (`MB_CUR_MAX` 1): a character above 0xFF is `EILSEQ` in `wctomb_s` and `wcrtomb_s`, and each byte is one wide character in `mbstowcs_s` and `mbsrtowcs_s`. The locale of a title's `libc.prx` was not measured. The `wcrtomb_s` path where a character does not fit `smax` and the `EILSEQ` paths of `mbstowcs_s` and `mbsrtowcs_s` are not reached

@hypermoist

Copy link
Copy Markdown
Contributor Author

Thanks @nikowolf123. I added your line to docs/dev/debt/libc.md right after the wcsrtombs_s entry, word for word, in 6f77c09, and merged current main. It records the single-byte C-locale conversion, the unmeasured locale of a title's libc.prx, and the wcrtomb_s/EILSEQ paths the test cannot reach.

For context: on the firmware's libc the C locale is UTF-8 with MB_CUR_MAX 3, so U+263A becomes E2 98 BA, matching the libc.md#L93 measurement. I have a separate branch that moves mbrtowc/wcrtomb and friends to that. It will be a follow-up PR and will update this entry when it lands, so this PR keeps its current scope.

Thanks also @Athen2045 for the Windows run.

@github-actions github-actions Bot added the docs label Oct 21, 2026
@adriadam10

Copy link
Copy Markdown
Collaborator

Re-checked the new head: the code and test are unchanged, and the added docs/dev/debt/libc.md entry records the single-byte locale gap of the Annex K conversions as @nikowolf123 asked; merged.

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.

5 participants