fix(libc): leave strtok_r's and wcstok's state at the terminator and a static empty string as titles' libc.prx does #11871

Merged
JJenkx merged 3 commits from upstream-pr/11871 into main 2026-10-29 12:50:00 +00:00
JJenkx commented 2026-10-27 10:56:29 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by JJenkx on 2026-10-27T10:56:29Z.


What

strtok_r sets the saved pointer to NULL after the last token and when no token is left, following FreeBSD 11.4 (#4625). The libc.prx that titles ship does neither:

  • After a last token that ends the string ("last", or "x:y" with empty delimiters), it leaves the saved pointer at the string's terminator. A later strtok_r(NULL, …) continues from there. If the caller has written over that terminator, it returns the new text: after "last", writing x over the old NUL makes the next call return "x".
  • When no token is left ("", ",", ",,,", or after the last token of ",a,,b,"), it points the saved pointer at a static empty string inside the library, the same address every time. That string lies in a read-only segment (PT_LOAD R--) of all eleven measured titles, for both functions, so here it is a const array, and a write through the pointer faults as it would on the console. Later calls keep returning NULL and leave it there.

A title that reads *saveptr after the last token gets an empty string on the console and a NULL dereference here.

strtok_r now does the same as the titles' copy. strtok, which runs strtok_r on a thread-local state, follows. A NULL *saveptr with a NULL string still returns NULL.

wcstok had the same NULL ends. The titles' copy behaves exactly as its strtok_r does, measured for "last", the overwritten terminator, ",," and ",a,", and the second commit makes wcstok follow.

This reverses the saved-pointer part of #4625, which followed FreeBSD without a console measurement. @QRMOE, for your review, since this changes what your tests checked.

Tested

Windows 11 Enterprise 10.0.22621, Ryzen 9 5950X, WinLibs GCC 15.2.0 UCRT r7, Ninja, Release, BUILD_TESTING=ON, main 3fea2a937b.

  • Comparison: a scratch loader runs the decrypted libc.prx of PPSA07923 and PPSA13934 natively.
    • Every case above was measured on both titles. The empty-string address is the same within each title and holds a NUL.
    • On 100,000 random strings and delimiter sets, the tokens match main everywhere. Only the saved pointer at the end differs.
  • guest_strings: #4625's checks now expect the measured pointers:
    • the static empty string after exhaustion, and the same address on later calls;
    • second + 3 after "y";
    • the terminator after "last", then the "x" token and its new terminator after the old NUL is overwritten.
    • errno is still preserved.
  • guest_wide_strings: the wcstok checks expect the same:
    • the static empty string after exhaustion, for only-delimiter and empty input;
    • tail + 3 and whole + 4 after a last token that ends the string.
    • after the old terminator of tail is overwritten, a resumed call returns the new x token at tail + 3 and leaves the state at tail + 4, as on the titles' copy.
  • guest_strings and guest_wide_strings pass in three runs out of three on the exact head d96d96e28a.
  • Negative control: with main's StringExtensions.cpp and Strings.cpp and these tests, both abort (exit 0xc0000409).
  • python tools/check_conventions.py --base origin/main and git diff --check pass.
  • Linux follow-up: guest_strings and guest_wide_strings pass three runs each at exact head d96d96e28a; environment and results. Not tested: a console or macOS.

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: none
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

AI-assisted (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5032720674 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11871). Originally posted by [JJenkx](https://github.com/JJenkx) on 2026-10-27T10:56:29Z. --- ### What `strtok_r` sets the saved pointer to NULL after the last token and when no token is left, following FreeBSD 11.4 (#4625). The `libc.prx` that titles ship does neither: - **After a last token that ends the string** (`"last"`, or `"x:y"` with empty delimiters), it leaves the saved pointer at the string's terminator. A later `strtok_r(NULL, …)` continues from there. If the caller has written over that terminator, it returns the new text: after `"last"`, writing `x` over the old NUL makes the next call return `"x"`. - **When no token is left** (`""`, `","`, `",,,"`, or after the last token of `",a,,b,"`), it points the saved pointer at a static empty string inside the library, the same address every time. That string lies in a read-only segment (`PT_LOAD` `R--`) of all eleven measured titles, for both functions, so here it is a `const` array, and a write through the pointer faults as it would on the console. Later calls keep returning NULL and leave it there. A title that reads `*saveptr` after the last token gets an empty string on the console and a NULL dereference here. `strtok_r` now does the same as the titles' copy. `strtok`, which runs `strtok_r` on a thread-local state, follows. A NULL `*saveptr` with a NULL string still returns NULL. `wcstok` had the same NULL ends. The titles' copy behaves exactly as its `strtok_r` does, measured for `"last"`, the overwritten terminator, `",,"` and `",a,"`, and the second commit makes `wcstok` follow. This reverses the saved-pointer part of #4625, which followed FreeBSD without a console measurement. @QRMOE, for your review, since this changes what your tests checked. ### Tested Windows 11 Enterprise 10.0.22621, Ryzen 9 5950X, WinLibs GCC 15.2.0 UCRT r7, Ninja, Release, `BUILD_TESTING=ON`, `main` 3fea2a937b. - **Comparison:** a scratch loader runs the decrypted `libc.prx` of PPSA07923 and PPSA13934 natively. - Every case above was measured on both titles. The empty-string address is the same within each title and holds a NUL. - On 100,000 random strings and delimiter sets, the tokens match `main` everywhere. Only the saved pointer at the end differs. - **`guest_strings`:** #4625's checks now expect the measured pointers: - the static empty string after exhaustion, and the same address on later calls; - `second + 3` after `"y"`; - the terminator after `"last"`, then the `"x"` token and its new terminator after the old NUL is overwritten. - `errno` is still preserved. - **`guest_wide_strings`:** the `wcstok` checks expect the same: - the static empty string after exhaustion, for only-delimiter and empty input; - `tail + 3` and `whole + 4` after a last token that ends the string. - after the old terminator of `tail` is overwritten, a resumed call returns the new `x` token at `tail + 3` and leaves the state at `tail + 4`, as on the titles' copy. - `guest_strings` and `guest_wide_strings` pass in three runs out of three on the exact head `d96d96e28a`. - **Negative control:** with `main`'s `StringExtensions.cpp` and `Strings.cpp` and these tests, both abort (exit 0xc0000409). - `python tools/check_conventions.py --base origin/main` and `git diff --check` pass. - **Linux follow-up:** `guest_strings` and `guest_wide_strings` pass three runs each at exact head `d96d96e28a`; [environment and results](https://github.com/boykopovar/AnyPS5/pull/11871#issuecomment-6452387018). **Not tested:** a console or macOS. ### 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](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source: none - [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 AI-assisted (Claude Code).
QRMOE commented 2026-10-27 11:39:18 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by QRMOE on 2026-10-27T11:39:18Z.

Review: COMMENTED


Thanks for measuring this. #4625 followed FreeBSD 11.4 with no console data, so the titles' libc.prx should win. The token-for-token match on 100,000 inputs and the negative control make it convincing. On main, nothing outside the two implementations and their tests calls strtok_r or wcstok, so no other code relied on the NULL state.

One question: is the titles' empty string in a writable segment of libc.prx (.data/.bss) or a read-only one? static char exhausted[] = "" is writable here. A title that writes through *saveptr after the string is used up, as in your overwritten-terminator case, would change the shared string for every later call. On the console that write might fault instead. If the address you measured falls in read-only data, a const array cast to char* would match it more closely.

Nit: the firstState < first || firstState >= first + sizeof(first) check, and the same check on tokens in GuestWideStrings.cpp, compare pointers into different objects, which C++ leaves unspecified. std::less<> keeps them well-defined.

I read the diff but didn't run it; I'm going on your three-of-three runs.

AI-assisted: yes (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5666457316 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11871#pullrequestreview-5666457316). Originally posted by [QRMOE](https://github.com/QRMOE) on 2026-10-27T11:39:18Z. **Review:** COMMENTED --- Thanks for measuring this. #4625 followed FreeBSD 11.4 with no console data, so the titles' `libc.prx` should win. The token-for-token match on 100,000 inputs and the negative control make it convincing. On `main`, nothing outside the two implementations and their tests calls `strtok_r` or `wcstok`, so no other code relied on the NULL state. One question: is the titles' empty string in a writable segment of `libc.prx` (`.data`/`.bss`) or a read-only one? `static char exhausted[] = ""` is writable here. A title that writes through `*saveptr` after the string is used up, as in your overwritten-terminator case, would change the shared string for every later call. On the console that write might fault instead. If the address you measured falls in read-only data, a `const` array cast to `char*` would match it more closely. Nit: the `firstState < first || firstState >= first + sizeof(first)` check, and the same check on `tokens` in `GuestWideStrings.cpp`, compare pointers into different objects, which C++ leaves unspecified. `std::less<>` keeps them well-defined. I read the diff but didn't run it; I'm going on your three-of-three runs. AI-assisted: yes (Claude Code).
MarcZX10 commented 2026-10-27 11:40:01 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-27T11:40:01Z.

Review: DISMISSED


Please add a wcstok regression for the observed overwritten-terminator continuation. The wide-string test currently checks that last points at tail + 3 after the final token, but it never overwrites that terminator and resumes with text == nullptr. GuestStrings.cpp covers that observable case for strtok_r; wcstok has a separate implementation, so its corresponding behavior is not protected by a test. Please extend the tail case to overwrite the terminator, resume, and assert the returned token and updated state.

Validation on head 771ea0b3ae35ddd162725873f81d1f7ae7988319:

  • Built guest_string_tests and guest_wide_string_tests from a clean Linux Release build using the pinned submodules.
  • Native CTest: guest_wide_strings passed. guest_strings stopped at the host CPU guard (this E5-1620 v2 lacks the required AVX2/FMA/LZCNT/BMI features).
  • Ran both exact-head executables under qemu-x86_64 -cpu Haswell; both exited successfully. This is emulated execution, not a hardware run.
  • python3 tools/check_conventions.py --base refs/review/upstream-main and git diff --check refs/review/upstream-main...HEAD passed.
  • Hosted Ubuntu, Windows, and conventions checks pass; the macOS jobs remain pending.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5666464934 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11871#pullrequestreview-5666464934). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-27T11:40:01Z. **Review:** DISMISSED --- Please add a `wcstok` regression for the observed overwritten-terminator continuation. The wide-string test currently checks that `last` points at `tail + 3` after the final token, but it never overwrites that terminator and resumes with `text == nullptr`. `GuestStrings.cpp` covers that observable case for `strtok_r`; `wcstok` has a separate implementation, so its corresponding behavior is not protected by a test. Please extend the `tail` case to overwrite the terminator, resume, and assert the returned token and updated state. Validation on head `771ea0b3ae35ddd162725873f81d1f7ae7988319`: - Built `guest_string_tests` and `guest_wide_string_tests` from a clean Linux Release build using the pinned submodules. - Native CTest: `guest_wide_strings` passed. `guest_strings` stopped at the host CPU guard (this E5-1620 v2 lacks the required AVX2/FMA/LZCNT/BMI features). - Ran both exact-head executables under `qemu-x86_64 -cpu Haswell`; both exited successfully. This is emulated execution, not a hardware run. - `python3 tools/check_conventions.py --base refs/review/upstream-main` and `git diff --check refs/review/upstream-main...HEAD` passed. - Hosted Ubuntu, Windows, and conventions checks pass; the macOS jobs remain pending.
MarcZX10 commented 2026-10-29 10:10:39 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T10:10:39Z.

Review: APPROVED


Re-reviewed exact head d96d96e28a595cff2312d4113530dbb8e0eb2663. The follow-up addresses the outstanding points: the exhausted-string behavior is supported by title libc.prx mappings reported as read-only across eleven titles; the out-of-object checks now use std::less<>; and wcstok has the overwritten-terminator continuation regression. Current main has a clean merge preview. Its changes in Strings.cpp and the two tests are in other routines, not these tokenization paths; current-main conventions and git diff --check pass. The author reports three repeated Linux runs of both string tests at this head; I did not rerun them locally. No remaining blocker found; approved.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5696022363 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/11871#pullrequestreview-5696022363). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-29T10:10:39Z. **Review:** APPROVED --- Re-reviewed exact head `d96d96e28a595cff2312d4113530dbb8e0eb2663`. The follow-up addresses the outstanding points: the exhausted-string behavior is supported by title `libc.prx` mappings reported as read-only across eleven titles; the out-of-object checks now use `std::less<>`; and `wcstok` has the overwritten-terminator continuation regression. Current `main` has a clean merge preview. Its changes in `Strings.cpp` and the two tests are in other routines, not these tokenization paths; current-main conventions and `git diff --check` pass. The author reports three repeated Linux runs of both string tests at this head; I did not rerun them locally. No remaining blocker found; approved.
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!11871
No description provided.