perf(libc): search memrchr by block and memccpy with memchr #17345

Merged
rocklouis055 merged 2 commits from upstream-pr/17345 into main 2026-11-18 00:53:42 +00:00
rocklouis055 commented 2026-11-08 18:22:53 +00:00 (Migrated from github.com)

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


What

memrchr and memccpy handled one byte per step.

  • memrchr scans backward in 16-byte aligned blocks with SSE2. It starts at the block that holds the last byte, masks bytes past the end and before the start, and returns the highest match. Aligned loads stay inside the pages that hold the buffer. The loading helper is marked no_sanitize("address"), as in GuestAllocations.cpp. Builds without __SSE2__ (the Emscripten test build compiles this file), and ranges that would wrap the address space, keep main's loop.
  • memccpy finds the stop byte with the host memchr and then copies the prefix in one memmove. Since C11, memchr behaves as if it reads sequentially and stops at the first match. So like the old loop, it reads no further than the stop byte. Overlapping buffers are undefined for memccpy; memmove keeps that case well defined on the host.

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_memrchr, guest_memccpy_bounds, guest_bounded_search_guards, guest_strings and guest_string_compare pass.

The new guest_memrchr_blocks test runs 40000 random cases against naive references:

  • inputs sit in a page with a PROT_NONE (PAGE_NOACCESS) page on both sides;
  • inputs start near the front guard, end near the back guard, or sit anywhere in the page;
  • lengths 0–700 over a four-byte alphabet;
  • c values that need the unsigned char conversion.

For memccpy, the test checks the return value and the whole destination page, so a byte written past the stop byte fails.

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

  • not masking bytes past the end;
  • an off-by-one in that mask;
  • not masking bytes before the start;
  • treating the start block as a full block;
  • the wrong byte from the match bit (in both returns);
  • the wrong last byte;
  • copying one byte too few or too many;
  • the wrong count when the stop byte is absent.

Removing the n == 0 early return in memccpy still passes, because memchr and memmove already accept a zero count.

Windows: Strings.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 22f330a971 against main bfdb58119e. Medians of 31 samples, in ns per call, on a buffer of a without the target byte:

bytes memrchr memccpy
7 2.8 → 3.7 9.5 → 9.5
31 15.0 → 3.0 15.4 → 4.6
255 82 → 7.0 84 → 6.0
4095 1046 → 111 1040 → 73
65535 16594 → 1708 16385 → 2292

memrchr on 7 bytes costs about +0.9 ns. Every other case is equal or faster.

Order with other open PRs

  • #17326 and #17336 (mine) change other functions and other places in Strings.cpp and libc/CMakeLists.txt. All three branches merge with each other cleanly in any order (git merge-tree).
  • For every other PR listed by pr_overlap, 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:5213890786 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17345). Originally posted by [rocklouis055](https://github.com/rocklouis055) on 2026-11-08T18:22:53Z. --- ### What `memrchr` and `memccpy` handled one byte per step. - **`memrchr`** scans backward in 16-byte aligned blocks with SSE2. It starts at the block that holds the last byte, masks bytes past the end and before the start, and returns the highest match. Aligned loads stay inside the pages that hold the buffer. The loading helper is marked `no_sanitize("address")`, as in `GuestAllocations.cpp`. Builds without `__SSE2__` (the Emscripten test build compiles this file), and ranges that would wrap the address space, keep main's loop. - **`memccpy`** finds the stop byte with the host `memchr` and then copies the prefix in one `memmove`. Since C11, `memchr` behaves as if it reads sequentially and stops at the first match. So like the old loop, it reads no further than the stop byte. Overlapping buffers are undefined for `memccpy`; `memmove` keeps that case well defined on the host. 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_memrchr`, `guest_memccpy_bounds`, `guest_bounded_search_guards`, `guest_strings` and `guest_string_compare` pass. The new `guest_memrchr_blocks` test runs 40000 random cases against naive references: - inputs sit in a page with a `PROT_NONE` (`PAGE_NOACCESS`) page on both sides; - inputs start near the front guard, end near the back guard, or sit anywhere in the page; - lengths 0–700 over a four-byte alphabet; - `c` values that need the `unsigned char` conversion. For `memccpy`, the test checks the return value and the whole destination page, so a byte written past the stop byte fails. Mutation check. Each change below makes the new test fail: - not masking bytes past the end; - an off-by-one in that mask; - not masking bytes before the start; - treating the start block as a full block; - the wrong byte from the match bit (in both returns); - the wrong last byte; - copying one byte too few or too many; - the wrong count when the stop byte is absent. Removing the `n == 0` early return in `memccpy` still passes, because `memchr` and `memmove` already accept a zero count. Windows: `Strings.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 `22f330a971` against main `bfdb58119e`. Medians of 31 samples, in ns per call, on a buffer of `a` without the target byte: | bytes | memrchr | memccpy | |---|---|---| | 7 | 2.8 → 3.7 | 9.5 → 9.5 | | 31 | 15.0 → 3.0 | 15.4 → 4.6 | | 255 | 82 → 7.0 | 84 → 6.0 | | 4095 | 1046 → 111 | 1040 → 73 | | 65535 | 16594 → 1708 | 16385 → 2292 | `memrchr` on 7 bytes costs about +0.9 ns. Every other case is equal or faster. ### Order with other open PRs - #17326 and #17336 (mine) change other functions and other places in `Strings.cpp` and `libc/CMakeLists.txt`. All three branches merge with each other cleanly in any order (`git merge-tree`). - For every other PR listed by `pr_overlap`, `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:32 +00:00 (Migrated from github.com)

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

Review: COMMENTED


Windows run of head 22f330a971, 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_memrchr_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 memrchr and memccpy, 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: memccpy now copies with memmove after a memchr. That differs from the old byte loop only when the buffers overlap, which is undefined for memccpy, so it's fine.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5819285574 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17345#pullrequestreview-5819285574). Originally posted by [gabichuuuuu](https://github.com/gabichuuuuu) on 2026-11-08T19:17:32Z. **Review:** COMMENTED --- Windows run of head `22f330a971`, 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_memrchr_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 `memrchr` and `memccpy`, 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: `memccpy` now copies with `memmove` after a `memchr`. That differs from the old byte loop only when the buffers overlap, which is undefined for `memccpy`, so it's fine.
MarcZX10 commented 2026-11-17 10:19:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-17T10:19:45Z.

Review: COMMENTED


Reviewed — no blocking findings

Nothing blocks this; the points below are optional.

What I ran

Head 82e042f83b76618fcc789d7791593cc1311c9d88, base main. No build, no tests, no compiler. Reading only, through the repository reader (repo_read.py):

python3 repo_read.py cat core/libs/prx/libc/src/Strings.cpp 1 40
python3 repo_read.py cat core/libs/prx/libc/src/Strings.cpp 176 215
python3 repo_read.py search no_sanitize core

The changed hunks in diff.patch were read in full for both reviewed files.

Results

Check Result Note
Changed hunks, Strings.cpp passed No defect found in the code
Changed hunks, CMakeLists.txt passed Same shape as the adjacent test in the diff
Includes for SSE2 and <bit> passed Present in the file head
no_sanitize claim in the description passed GuestAllocations.cpp uses the same attribute
Build and test run not run No build in this pass
New test GuestMemrchrBlocks.cpp not run Excluded by rule, see Not verified

Findings

Blocking

None.

Non-blocking

  • core/libs/prx/libc/src/Strings.cpp:301: FindLastByte has no [[gnu::no_sanitize("address")]], while the sibling FindLastUnit (line 181) does. The raw loads happen in MatchBytes (line 296), which has the attribute, so this is probably fine. ASan was not run to confirm it.
  • core/libs/prx/libc/src/Strings.cpp:301-317: the block walk duplicates the shape of FindLastUnit. This is a style point only; the logic in FindLastByte checks out for the cases I traced (single byte, match in the start block, match in an earlier block, and the wrap guard in memrchr_nid_postfix at line 631).

Not verified

  • core/libs/tests/GuestMemrchrBlocks.cpp was not read. It is in the excluded list because the rule *lock* matches the word "Blocks" in its name. This is a side effect of the rule, not a repository problem. The 40000-case test, the mutation claims, and the test behaviour are therefore not verified.
  • The new CMake test target (core/libs/prx/libc/CMakeLists.txt:582-590) was read as a diff hunk only.
  • The benchmark table in the description: not run.
  • The description's claim that memchr reads no further than the stop byte: this rests on the C standard wording. The real implementation's reads were not checked.
  • The overlap claims with #17326, #17336 and other open PRs: not checked.
  • Windows, Emscripten and MinGW builds: not run.
  • Hosted CI for this head: not inspected.

Files read: core/libs/prx/libc/CMakeLists.txt (diff hunks only), core/libs/prx/libc/src/Strings.cpp (diff hunks and two head ranges). Files excluded: core/libs/tests/GuestMemrchrBlocks.cpp.

To get this to a good state

Nothing is required. The points under Findings are optional.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5936644343 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17345#pullrequestreview-5936644343). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-17T10:19:45Z. **Review:** COMMENTED --- # Reviewed — no blocking findings Nothing blocks this; the points below are optional. ## What I ran Head `82e042f83b76618fcc789d7791593cc1311c9d88`, base `main`. No build, no tests, no compiler. Reading only, through the repository reader (`repo_read.py`): ```sh python3 repo_read.py cat core/libs/prx/libc/src/Strings.cpp 1 40 python3 repo_read.py cat core/libs/prx/libc/src/Strings.cpp 176 215 python3 repo_read.py search no_sanitize core ``` The changed hunks in `diff.patch` were read in full for both reviewed files. ## Results | Check | Result | Note | |---|---|---| | Changed hunks, `Strings.cpp` | passed | No defect found in the code | | Changed hunks, `CMakeLists.txt` | passed | Same shape as the adjacent test in the diff | | Includes for SSE2 and `<bit>` | passed | Present in the file head | | `no_sanitize` claim in the description | passed | `GuestAllocations.cpp` uses the same attribute | | Build and test run | not run | No build in this pass | | New test `GuestMemrchrBlocks.cpp` | not run | Excluded by rule, see Not verified | ## Findings **Blocking** None. **Non-blocking** - `core/libs/prx/libc/src/Strings.cpp:301`: `FindLastByte` has no `[[gnu::no_sanitize("address")]]`, while the sibling `FindLastUnit` (line 181) does. The raw loads happen in `MatchBytes` (line 296), which has the attribute, so this is probably fine. ASan was not run to confirm it. - `core/libs/prx/libc/src/Strings.cpp:301-317`: the block walk duplicates the shape of `FindLastUnit`. This is a style point only; the logic in `FindLastByte` checks out for the cases I traced (single byte, match in the start block, match in an earlier block, and the wrap guard in `memrchr_nid_postfix` at line 631). ## Not verified - `core/libs/tests/GuestMemrchrBlocks.cpp` was not read. It is in the excluded list because the rule `*lock*` matches the word "Blocks" in its name. This is a side effect of the rule, not a repository problem. The 40000-case test, the mutation claims, and the test behaviour are therefore not verified. - The new CMake test target (`core/libs/prx/libc/CMakeLists.txt:582-590`) was read as a diff hunk only. - The benchmark table in the description: not run. - The description's claim that `memchr` reads no further than the stop byte: this rests on the C standard wording. The real implementation's reads were not checked. - The overlap claims with #17326, #17336 and other open PRs: not checked. - Windows, Emscripten and MinGW builds: not run. - Hosted CI for this head: not inspected. Files read: `core/libs/prx/libc/CMakeLists.txt` (diff hunks only), `core/libs/prx/libc/src/Strings.cpp` (diff hunks and two head ranges). Files excluded: `core/libs/tests/GuestMemrchrBlocks.cpp`. ## To get this to a good state Nothing is required. The points under Findings are optional.
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!17345
No description provided.