perf(libc): find strnlen terminators with memchr #17354

Merged
rocklouis055 merged 2 commits from upstream-pr/17354 into main 2026-11-17 10:55:44 +00:00
rocklouis055 commented 2026-11-08 18:30:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rocklouis055 on 2026-11-08T18:30:43Z.


What

strnlen checked one byte per step, and strnlen_s and strlcat call it. stpncpy copied and padded one byte at a time.

  • strnlen now finds the terminator with the host memchr. Since C11, memchr behaves as if it reads sequentially and stops at the first match, so it reads no further than the old loop did. The limit is clamped to the end of the address space, so a SIZE_MAX limit never makes the end pointer wrap. A zero limit returns before calling memchr.
  • stpncpy takes the length from strnlen, copies that prefix with one memmove and fills the rest with one memset. Overlapping buffers are undefined for stpncpy; memmove keeps that case well defined on the host. A zero count returns before any call.

The results are unchanged, and no exported functions or NIDs are added or changed.

Tested

Ubuntu 26.04, GCC 15.2, Release, -DBUILD_TESTING=ON. guest_strings, guest_bounded_search_guards, guest_strndup_guarded, guest_strncmp_boundary, guest_strncat_protected, guest_strnstr_boundary and guest_strncpy_protected pass.

The new guest_bounded_copy_blocks test runs 40000 random cases against a naive reference:

  • sources sit in a page with a PROT_NONE (PAGE_NOACCESS) page on both sides, often ending exactly at the guard page;
  • limits run up to 900 bytes;
  • sources are with and without a terminator inside the limit;
  • the whole destination page is checked, so a byte written past count fails;
  • it also covers null pointers with a zero count, and strnlen with SIZE_MAX.

Mutation check. Each change below makes the new test fail:

  • returning 0 when no terminator is found;
  • an off-by-one in the length;
  • searching one byte past the limit;
  • copying one byte too many;
  • padding one byte too few;
  • returning destination + count.

These still pass on glibc, because its memchr, memmove and memset already handle the cases:

  • removing the address-space clamp;
  • removing either zero-count early return.

They are kept for hosts whose functions are not as forgiving.

Windows: StringExtensions.cpp and the new test pass a syntax-only build for x86_64-windows-gnu (zig/clang). Not built with MinGW or run on Windows.

Performance: I have no title capture. I can't run a title, so there are no main/PR summary lines.

Micro-benchmark through the built libc.prx, at 4e20b1bf98 against main bfdb58119e. Medians of 31 samples, in ns per call. The limit is units + 1 on a string of a. "pad" copies an empty string, so the whole count is padding.

bytes strnlen strnlen_s stpncpy stpncpy pad
7 3.3 → 2.8 3.7 → 3.0 8.6 → 7.5 6.4 → 16.3
31 15.0 → 2.9 15.7 → 3.0 15.4 → 5.6 3.1 → 5.9
255 86 → 4.9 86 → 5.0 92 → 8.6 6.0 → 7.1
4095 1063 → 32 1062 → 32 1171 → 90 32 → 53
65535 16741 → 626 16730 → 626 18493 → 2401 1162 → 1159

The trade-off is stpncpy with an empty or very short source:

  • main's padding loop already compiles to a single memset;
  • this version first waits for memchr to return before it can start the memset;
  • that costs about +10 ns at 8 bytes and +3 ns at 32 bytes;
  • the 4 KiB row moves by +21 ns, partly because memset now starts one byte earlier, at a different alignment;
  • every case that copies characters is faster.

Order with other open PRs

  • #17326, #17336 and #17345 (mine) touch Strings.cpp and other places in libc/CMakeLists.txt. All four branches merge with each other cleanly (git merge-tree).
  • No other open PR changes StringExtensions.cpp. For every PR listed by pr_overlap on libc/CMakeLists.txt, git merge-tree shows the same conflicting files against this branch as against main.

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. This PR adds no unimplemented paths.
  • No notes, investigation .md files or images added to the repository
  • New third-party code is a submodule built from source. This PR adds no third-party code.
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5213947452 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17354). Originally posted by [rocklouis055](https://github.com/rocklouis055) on 2026-11-08T18:30:43Z. --- ### What `strnlen` checked one byte per step, and `strnlen_s` and `strlcat` call it. `stpncpy` copied and padded one byte at a time. - **`strnlen`** now finds the terminator with the host `memchr`. Since C11, `memchr` behaves as if it reads sequentially and stops at the first match, so it reads no further than the old loop did. The limit is clamped to the end of the address space, so a `SIZE_MAX` limit never makes the end pointer wrap. A zero limit returns before calling `memchr`. - **`stpncpy`** takes the length from `strnlen`, copies that prefix with one `memmove` and fills the rest with one `memset`. Overlapping buffers are undefined for `stpncpy`; `memmove` keeps that case well defined on the host. A zero count returns before any call. The results are unchanged, and no exported functions or NIDs are added or changed. ### Tested Ubuntu 26.04, GCC 15.2, Release, `-DBUILD_TESTING=ON`. `guest_strings`, `guest_bounded_search_guards`, `guest_strndup_guarded`, `guest_strncmp_boundary`, `guest_strncat_protected`, `guest_strnstr_boundary` and `guest_strncpy_protected` pass. The new `guest_bounded_copy_blocks` test runs 40000 random cases against a naive reference: - sources sit in a page with a `PROT_NONE` (`PAGE_NOACCESS`) page on both sides, often ending exactly at the guard page; - limits run up to 900 bytes; - sources are with and without a terminator inside the limit; - the whole destination page is checked, so a byte written past `count` fails; - it also covers null pointers with a zero count, and `strnlen` with `SIZE_MAX`. Mutation check. Each change below makes the new test fail: - returning 0 when no terminator is found; - an off-by-one in the length; - searching one byte past the limit; - copying one byte too many; - padding one byte too few; - returning `destination + count`. These still pass on glibc, because its `memchr`, `memmove` and `memset` already handle the cases: - removing the address-space clamp; - removing either zero-count early return. They are kept for hosts whose functions are not as forgiving. Windows: `StringExtensions.cpp` and the new test pass a syntax-only build for `x86_64-windows-gnu` (zig/clang). Not built with MinGW or run on Windows. **Performance:** I have no title capture. I can't run a title, so there are no `main`/PR summary lines. Micro-benchmark through the built `libc.prx`, at `4e20b1bf98` against main `bfdb58119e`. Medians of 31 samples, in ns per call. The limit is `units + 1` on a string of `a`. "pad" copies an empty string, so the whole count is padding. | bytes | strnlen | strnlen_s | stpncpy | stpncpy pad | |---|---|---|---|---| | 7 | 3.3 → 2.8 | 3.7 → 3.0 | 8.6 → 7.5 | 6.4 → 16.3 | | 31 | 15.0 → 2.9 | 15.7 → 3.0 | 15.4 → 5.6 | 3.1 → 5.9 | | 255 | 86 → 4.9 | 86 → 5.0 | 92 → 8.6 | 6.0 → 7.1 | | 4095 | 1063 → 32 | 1062 → 32 | 1171 → 90 | 32 → 53 | | 65535 | 16741 → 626 | 16730 → 626 | 18493 → 2401 | 1162 → 1159 | **The trade-off is `stpncpy` with an empty or very short source:** - main's padding loop already compiles to a single `memset`; - this version first waits for `memchr` to return before it can start the `memset`; - that costs about +10 ns at 8 bytes and +3 ns at 32 bytes; - the 4 KiB row moves by +21 ns, partly because `memset` now starts one byte earlier, at a different alignment; - every case that copies characters is faster. ### Order with other open PRs - #17326, #17336 and #17345 (mine) touch `Strings.cpp` and other places in `libc/CMakeLists.txt`. All four branches merge with each other cleanly (`git merge-tree`). - No other open PR changes `StringExtensions.cpp`. For every PR listed by `pr_overlap` on `libc/CMakeLists.txt`, `git merge-tree` shows the same conflicting files against this branch as against `main`. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except technical debt - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's technical debt file. This PR adds no unimplemented paths. - [x] No notes, investigation `.md` files or images added to the repository - [x] New third-party code is a submodule built from source. This PR adds no third-party code. - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes (Claude Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
gabichuuuuu commented 2026-11-08 19:17:31 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by gabichuuuuu on 2026-11-08T19:17:31Z.

Review: COMMENTED


Windows run of head 4e20b1bf98, merged onto main 9fabd4aa7e. To save builds, this ran in one tree together with 11 other open PRs that touch different code (four libc string speed-ups and eight test-only PRs); all merged cleanly. Setup: Windows 11, WinLibs GCC 15.2 (x86_64-ucrt-posix-seh), Release, BUILD_TESTING=ON, i7-12800H.

  • guest_bounded_copy_blocks with --repeat until-fail:5: 5 / 5 pass.
  • Extra differential check, not part of this PR. I wrote a fuzz test that compares strnlen, stpncpy, memrchr, memccpy, wcslen, wcschr, wcsrchr, wmemchr, wcsnlen_s, wcscmp, wcsncmp and wmemcmp with byte-by-byte reference loops. It runs 400,000 rounds with random lengths, alphabets and odd or even alignments. Half of the strings end right before a PAGE_NOACCESS page, and memrchr also starts right after one, so any read past the bounds faults. With this PR's code (all four speed-ups together), 5,600,000 checks agree and nothing faults.
  • With main's Strings.cpp and StringExtensions.cpp, the same tests and the fuzz pass too, so the new test pins the result of strnlen and stpncpy, not the speed-up. That's expected for a speed change, but it means the new code paths are covered only by the equivalence checks.

I didn't measure the speed.

From reading: strnlen now relies on memchr not reading past the first match when limit is larger than the string. The page-guard rows of the fuzz exercise exactly that with UCRT's memchr, and it holds there.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5819285484 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17354#pullrequestreview-5819285484). Originally posted by [gabichuuuuu](https://github.com/gabichuuuuu) on 2026-11-08T19:17:31Z. **Review:** COMMENTED --- Windows run of head `4e20b1bf98`, merged onto `main` `9fabd4aa7e`. To save builds, this ran in one tree together with 11 other open PRs that touch different code (four libc string speed-ups and eight test-only PRs); all merged cleanly. Setup: Windows 11, WinLibs GCC 15.2 (`x86_64-ucrt-posix-seh`), Release, `BUILD_TESTING=ON`, i7-12800H. - `guest_bounded_copy_blocks` with `--repeat until-fail:5`: 5 / 5 pass. - **Extra differential check, not part of this PR.** I wrote a fuzz test that compares `strnlen`, `stpncpy`, `memrchr`, `memccpy`, `wcslen`, `wcschr`, `wcsrchr`, `wmemchr`, `wcsnlen_s`, `wcscmp`, `wcsncmp` and `wmemcmp` with byte-by-byte reference loops. It runs 400,000 rounds with random lengths, alphabets and odd or even alignments. Half of the strings end right before a `PAGE_NOACCESS` page, and `memrchr` also starts right after one, so any read past the bounds faults. With this PR's code (all four speed-ups together), 5,600,000 checks agree and nothing faults. - With `main`'s `Strings.cpp` and `StringExtensions.cpp`, the same tests and the fuzz pass too, so the new test pins the result of `strnlen` and `stpncpy`, not the speed-up. That's expected for a speed change, but it means the new code paths are covered only by the equivalence checks. I didn't measure the speed. From reading: `strnlen` now relies on `memchr` not reading past the first match when `limit` is larger than the string. The page-guard rows of the fuzz exercise exactly that with UCRT's `memchr`, and it holds there.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!17354
No description provided.