Skip to content

fix(libc): read rand_r's state and the _Dtest classifiers' value through checked guest copies - #24467

Merged
oneandonlydean merged 2 commits into
boykopovar:mainfrom
domx4q:fix/libc-rand-r-dtest-guest-pointers
Dec 5, 2026
Merged

oneandonlydean merged 2 commits into
boykopovar:mainfrom
domx4q:fix/libc-rand-r-dtest-guest-pointers

Conversation

@domx4q

@domx4q domx4q commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What

rand_r (Math.cpp) read and wrote its state straight through the guest pointer, and _Dtest/_FDtest memcpy'd their value from it, so an unmapped or read-only pointer crashed the host. They now follow the libc pattern that _LDtest and modfl use (#23540):

  • rand_r copies the state in with GuestCopyIn_nid_no_patch, advances the host copy and writes it back once with GuestCopyOut_nid_no_patch.
  • _Dtest and _FDtest read the value with one GuestCopyIn_nid_no_patch (8 or 4 bytes) in place of the memcpy. Read-only values still classify.
  • An unreadable or unwritable pointer throws std::invalid_argument and leaves errno unchanged, as a null pointer already does.

Results for valid pointers are unchanged (existing _Dtest/_FDtest classification tables and the rand_r sequence check in GuestMath.cpp). The internal _Xp_ callers in ExtendedPrecisionDouble.cpp (libSceLibcInternal) and VersionedExtendedPrecision.cpp take the same checked read; their tests pass unchanged.

Tested

Arch Linux, GCC, Release build. Re-run after rebasing onto origin/main 0a025bd.

  • ctest --test-dir build -R '^(guest_math|guest_math_elementary|guest_math_exact|guest_icu_numeric|guest_libc-random-seeding|guest_sce_v2_extended_precision|guest_libc_internal_extended_precision|guest_libc_internal_extended_precision_double|public_headers)$': passed.
  • New CheckRandomStateAndClassificationGuestPointers in GuestMath.cpp:
    • rand_r throws with errno unchanged for an unmapped (0x10) state and for a read-only (static const) state, and the read-only state stays untouched.
    • _Dtest and _FDtest throw for an unmapped value and classify read-only values.
    • rand_r still advances a writable state.
  • Mutation check (repeated after the rebase): ignoring rand_r's GuestCopyOut_nid_no_patch result makes the new test fail.
  • python3 tools/progress.py --module libc: implemented count unchanged (1850).
  • python3 tools/guest_pointer_audit.py libc no longer lists the three functions.

tools/pr_overlap.py --branch fix/libc-rand-r-dtest-guest-pointers: #6295 and #7544 conflict with main and could not be compared; their diffs do not touch these functions.

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 (Claude Code)

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of invalid or inaccessible memory when using random-number and floating-point classification functions. Invalid inputs are now reported consistently instead of being read or written unsafely.
    • Valid random-number state continues to update correctly, and readable inputs in protected memory can still be classified. These operations leave errno unchanged when invalid pointers are rejected.

…ugh checked guest copies

rand_r read and wrote its state straight through the guest pointer, and
_Dtest and _FDtest memcpy'd their value from it, so an unmapped or
read-only pointer crashed the host. rand_r now copies the state in,
advances the host copy and writes it back with GuestCopyOut_nid_no_patch;
_Dtest and _FDtest read the value with GuestCopyIn_nid_no_patch. An
unusable pointer throws std::invalid_argument with errno unchanged, as
a null pointer and _LDtest already do.

@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 dae530d640:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_math_tests built cleanly.
  • CTest (guest_math):
    1/1 Test #1216: guest_math .......................   Passed    0.02 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libc/src/Math.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #1216: guest_math .......................***Exception: SegFault  1.25 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified GuestCopyIn_nid_no_patch / GuestCopyOut_nid_no_patch memory safety and nullptr/unmapped/read-only pointer handling in rand_r_nid_postfix, _FDtest_nid_postfix, and _Dtest_nid_postfix in core/libs/prx/libc/src/Math.cpp.
    • Verified exact exception semantics: std::invalid_argument is thrown on null/unreadable/unwritable pointers, leaving errno untouched per libc conventions and existing patterns (e.g. _LDtest, modfl).
    • Verified that rand_r correctly reads guest state, advances it via MinimalStandardNext, writes the updated state back to guest memory, and returns the converted value as int.
    • Verified cross-platform 32/64-bit portability (sizeof uint32_t, uint64_t, unsigned int) across LP64 and LLP64 targets.
    • Verified AGENTS.md compliance: conventions passed, no new comments added, no special-cased values or stubs, and unit test coverage in core/libs/tests/GuestMath.cpp tests valid and invalid pointer paths.

Looks Good To Me

@github-actions github-actions Bot added the libc label Nov 20, 2026

@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

Nothing blocks this change; the points below are optional.

What I ran

Reviewed head dae530d6403750562aefa8d7acdb95706eef0e28. I inspected the prepared diff and targeted source and test ranges through repo_read.py; no build or test commands were run.

Results

Check Result Note
Diff review passed Both changed files inspected
Tests not run Author-reported results only

Findings

Blocking

None.

Non-blocking

None.

Not verified

Did not run the reported CTest selection, mutation check, build, pointer audit, or progress script. Read all changed lines in core/libs/prx/libc/src/Math.cpp and core/libs/tests/GuestMath.cpp; no changed files were excluded. Related callers were located by search but not read in full, so their behavior is not verified.

To get this to a good state

Nothing is required.

@kiwe147

kiwe147 commented Nov 21, 2026

Copy link
Copy Markdown

Tested head dae530d640, applied with git apply on main fd4aeed483 together with the other 28 PRs of one batch (#19470, #20317, #21336, #22189, #22888, #23474, #24489, #20216, #22048, #22111, #22319, #22422, #22841, #23127, #9547, #18247, #21720, #22375, #23405, #24134, #14851, #18324, #19650, #19986, #20447, #21078, #22362, #22702). All applied without conflicts and the whole tree built.

Setup: Windows 11 Pro 10.0.26200, Ryzen 7 9800X3D, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON. GPUs: NVIDIA GeForce RTX 3080 (driver 621.24) and the AMD Radeon iGPU of the CPU (gfx1036, driver 32.0.21036.18). No validation layer. iGPU run: ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 ANYPS5_GPU="AMD Radeon", agc_/video tests only.

tests RTX 3080 iGPU
guest_math, guest_math_elementary, guest_math_exact (3 tests, matched by name to the test file this PR changes) all pass outside the iGPU subset

Whole batch: the full ctest -j 12 (6526 tests) on the RTX 3080 has 9 failing tests; the 4 that also fail on main fd4aeed483 are agc_driver_stencil_plane_memory, agc_driver_msaa_dcc_unwatch, agc_storage_write_back_host_retile, and pr_overlap_names, which needs a newer Python than my 3.10. Intermittent in this run (pass when rerun alone, or known flaky): agc_driver_store_over_untracked, guest_raise_short_sleep_without_wake, agc_driver_store_over_untracked. Failing tests I could not trace to a single PR (reverting the likely candidates did not clear them): guest_agc_driver_unknown, guest_load_ranges, tool_script_modes. The 2127 agc_/video tests on the iGPU have 2 failing: agc_driver_stencil_plane_memory, agc_driver_store_over_untracked (agc_driver_stencil_plane_memory also fails on main).

This is one combined tree, not a run of this PR alone.

AI-assisted: yes (Claude Code)

This was referenced Nov 21, 2026
@Helldiverr

Copy link
Copy Markdown
Contributor

Windows CPU run: works on Windows. 7 of 7 tests pass on main 45fc4e23bb and on the merge 3 times out of 3. The negative control and all three mutations are caught. One cost question for callers in libc and libSceLibcInternal: on this host each _Dtest call now takes about 255 ns instead of 1 ns, and each rand_r call about 650 ns instead of 1.2 ns.

Existing runs:

  • The author ran the tests on Arch Linux, with one mutation (ignoring rand_r's GuestCopyOut_nid_no_patch result).
  • PrivacyOnion ran the tests on Ubuntu 24.04 with a negative control (Math.cpp from main: guest_math segfaults).
  • MarcZX10 reviewed the code by reading it.
  • kiwe147 ran Windows 11 with this PR applied together with 28 others on fd4aeed483. guest_math, guest_math_elementary and guest_math_exact passed there, with no control for this PR alone.

What this run adds.

  • A Windows run of this PR alone, merged onto main 45fc4e23bb.
  • A negative control and three mutations on Windows.
  • A timing of _Dtest and rand_r before and after the change.
  • check_conventions and debt_fold --check on the merge.

Code (line numbers at dae530d640 for the files the PR changes; General.cpp and ExtendedPrecisionDouble.cpp are cited on main 45fc4e23bb, which is what the merge uses).

  • The change does what the description says:
    • _FDtest and _Dtest read the value with one GuestCopyIn_nid_no_patch (core/libs/prx/libc/src/Math.cpp:5893, :5905);
    • rand_r copies the state in, advances it and writes it back once (Math.cpp:5987-5989);
    • an unreadable or unwritable pointer throws std::invalid_argument, as _LDtest already does through LoadGuestExtended (core/libs/prx/libc/src/MathExact.cpp:948-949).
  • errno is restored by the copy helpers themselves: CopyGuestBytes and GuestCopyOut_nid_no_patch each hold a RestoreErrno (core/libs/prx/libc/src/General.cpp:97, :961). That is why the errno == 71 checks pass without any change to errno in Math.cpp.
  • Cost on Windows:
    • GuestCopyIn_nid_no_patch on an address outside the guest arena falls through to ReadProcessMemory (General.cpp:100-102), and GuestCopyOut_nid_no_patch calls VirtualQuery before it stores (General.cpp:966-973).

    • I timed 1,000,000 calls on a value on the test executable's stack, 3 rounds each, by adding a loop to the start of GuestMath.cpp's main on both trees:

      main 45fc4e23bb merge fed1dc66fd
      _Dtest 1.0, 1.2, 1.0 ns/call 260.1, 261.6, 253.0 ns/call
      rand_r 1.2, 1.3, 1.2 ns/call 677.9, 645.5, 643.2 ns/call
    • The internal callers pass host locals, for example _Dtest_nid_postfix(&leading) on a by-value parameter (core/libs/prx/libSceLibcInternal/ExtendedPrecisionDouble.cpp:65, :69; also :119, :198, :275, :304), so they now pay that cost too.

    • I did not measure a guest-arena address, which takes GuestArenaCopyOwned_nid_no_patch first (General.cpp:100), and I did not measure a title, so this is not a frame-time claim. If the cost matters, the internal callers could classify their local copy directly.

  • I found no code comments, no title-specific cases and no made-up success. No debt entry describes these functions, and the PR adds none. At the merge:
    • py -3 tools/check_conventions.py --base 45fc4e23bb prints "All conventions checks passed." (exit 0);
    • py -3 tools/debt_fold.py --check exits 0.

Negative control and mutation. All of these ran on guest_math, at the merge.

Change to Math.cpp Result
Negative control: Math.cpp from main, tests kept caught: SegFault, "read of 0x0000000000000010" in libc.prx
mA: rand_r ignores the GuestCopyOut_nid_no_patch result caught: GuestMath.cpp:184 (read-only state)
mB: _FDtest returns 0 for an unreadable value instead of throwing caught: GuestMath.cpp:187
mC: rand_r writes back the old state and returns the new value caught: GuestMath.cpp:192

Tests. ctest --test-dir build -R '^(guest_math|guest_math_elementary|guest_math_exact|guest_libc-random-seeding|guest_sce_v2_extended_precision|guest_libc_internal_extended_precision|guest_libc_internal_extended_precision_double)$' -V. guest_math_nan_classifiers is not built on Windows.

Test main merge run 1 run 2 run 3
guest_math Passed Passed Passed Passed
guest_math_elementary Passed Passed Passed Passed
guest_math_exact Passed Passed Passed Passed
guest_libc-random-seeding Passed Passed Passed Passed
guest_sce_v2_extended_precision Passed Passed Passed Passed
guest_libc_internal_extended_precision Passed Passed Passed Passed
guest_libc_internal_extended_precision_double Passed Passed Passed Passed

Host

  • CPU: Ryzen 9 9950X3D
  • OS: Windows 11 Pro 26300
  • Toolchain: WinLibs GCC 15.2, Release (CMAKE_CXX_FLAGS_RELEASE -O3 -DNDEBUG, checked before each build)
  • Commits: head dae530d640, merged onto main 45fc4e23bb as fed1dc66fd. main has since moved 23 commits to dad6acd1b8, none of them in the files cited here, and the head still merges cleanly.

AI-assisted: yes

@ligmaSec ligmaSec left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Built the submitted Math.cpp and ran the exact GuestMath fixture on Linux. It passed the new rand_r, _Dtest, and _FDtest cases, including read-only input for classification, rejected random state writes, preservation of errno, and the valid seed update.

AI-assisted: yes.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@domx4q the guards are right: on main a bad rand_r state or _Dtest/_FDtest pointer is a host crash, and your tests pin the new throws. One regression comes with it. __fpclassifyf still calls _FDtest_nid_postfix(&x) on its own host stack argument, and _FDtest now reads that through GuestCopyIn_nid_no_patch. On main that was a plain memcpy. A host local cannot be a bad guest pointer, so each __fpclassifyf call now pays a fault-copy (or ReadProcessMemory on Windows) for nothing.

Please move the bit classification into one static helper, for example ClassifyFloatBits(std::uint32_t bits), keep the null and GuestCopyIn checks only in _FDtest and _Dtest, and make __fpclassifyf_nid_postfix return ClassifyFloatBits(std::bit_caststd::uint32_t(x)). __fpclassifyd already avoids the copy through SonyFpclassifyd, so it needs no change. The tests should still pass as they are.

@domx4q

domx4q commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@oneandonlydean done in 181d879.

  • The bit classification is now one static helper, ClassifyFloatBits(std::uint32_t bits), in core/libs/prx/libc/src/Math.cpp.
  • _FDtest keeps the null check and the GuestCopyIn_nid_no_patch read, then calls the helper. _Dtest is unchanged.
  • __fpclassifyf_nid_postfix now returns ClassifyFloatBits(std::bit_cast<std::uint32_t>(x)), so it no longer copies its own stack argument. __fpclassifyd is untouched, as you said.

Tested on Arch Linux, GCC, Release: guest_math, guest_math_elementary, guest_math_exact, guest_math_nan_classifiers, guest_libc-random-seeding, guest_sce_v2_extended_precision, guest_libc_internal_extended_precision and guest_libc_internal_extended_precision_double pass (8/8) with the tests unchanged. check_conventions.py --base origin/main passes.

AI-assisted: yes (Claude Code)

@coderabbitai

coderabbitai Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Changes: Guest memory handling

Layer / File(s) Summary
Checked classification and random-state access
core/libs/prx/libc/src/Math.cpp, core/libs/tests/GuestMath.cpp
Classification exports use checked guest-memory reads, and float classification operates directly on the value’s bits. rand_r_nid_postfix checks guest-memory reads and writes. Tests cover invalid and read-only pointers, preserved errno, and the updated random state.

Possibly related issues

  • Issue 19123 describes direct guest-pointer dereferences in exports. This change replaces direct pointer access in the listed math exports with checked guest-memory copies.

Suggested reviewers: derkarussellbremser, privacyonion, marczx10

Change: Bug fix

Merge Risk: Minimal · up to 181d8

Invalid guest pointers passed to rand_r and the classification functions now raise std::invalid_argument instead of crashing the host, and valid-pointer behavior is unchanged. No merge-blocking risk is evident. The checked copies add some per-call overhead.

Security architecture risk: Minimal · up to 181d8

Libc now checks guest-memory access before consuming a classification input or returning an updated random seed. Rejected accesses use the same exception type as null arguments, while valid inputs keep their existing results. The change does not establish a new material security or failure-containment risk.

Security review details

Security Blast Radius

  • observed — The changed pointer surface is limited to fixed-size reads from the addresses passed to _Dtest and _FDtest and a fixed-size read and write at the address passed to rand_r. None of the changed exports accepts a caller-controlled length.

Trust Boundaries and Controls

  • observed — Guest-supplied addresses reach host memory through the existing copy helpers, which check the address range and use host access mechanisms. The helpers can operate on accessible process mappings; their use does not by itself establish that an address belongs to a particular guest allocation.

Data and control flow

  • observed — The classifiers consume a fixed-size host-local copy and do not write through the input pointer. rand_r reads a caller-owned seed, advances it locally, and returns the new value only after the checked write reports success. It does not touch the separate rand/srand global state.

Resilience and Maintainability Implications

  • observed — A rejected rand_r read prevents the write from being attempted. A rejected write prevents a success return, but the helper does not roll back copied bytes if its backend reports a short write. Callers should not treat the exception as a transactional rollback, and the separate read and write do not serialize concurrent seed updates.
  • observed — The new std::invalid_argument path covers copies that return false. Some host-backend failures can instead propagate std::runtime_error, so the export does not promise one exception type for every failure of the copy machinery.

Rollout and rollback

  • inferred — The copy helpers now decide whether the required access succeeded. Callers must supply readable classifier inputs and readable, writable seed storage. No operator configuration or state migration is indicated by the compared change; reverting would restore the prior unchecked access path.
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: f6e55c20-8ea2-4c63-9d66-2d885bf434b6
Commits

Reviewing files that changed from the base of the PR and between c8f72e9 and 181d879.

Files selected for processing: 2

  • core/libs/prx/libc/src/Math.cpp
  • core/libs/tests/GuestMath.cpp

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

@ligmaSec ligmaSec left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retested the revised Math.cpp with the exact GuestMath fixture on Linux. It passed the covered rand_r, _Dtest, and _FDtest cases for valid values, read-only classifiers, invalid guest addresses, and preservation of errno.

AI-assisted: yes.

@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 checked copies guard the changed pointer accesses, and the reviewed change has no verified blocking defect.

What I ran

Reviewed head 181d8793bee4ed12148746b5d2f3eb5a9176c08e using the pinned repo_read.py reader. No tests or builds were run. The author reports the listed tests passed on Arch Linux with GCC in Release mode.

python3 repo_read.py search 'bool GuestCopyIn_nid_no_patch'
python3 repo_read.py cat core/libs/prx/libc/src/General.cpp 80 135
python3 repo_read.py cat core/libs/prx/libc/src/General.cpp 870 895

Read the changed files core/libs/prx/libc/src/Math.cpp and core/libs/tests/GuestMath.cpp, plus core/libs/prx/libc/src/General.cpp for checked-copy context. files.json lists no excluded changed files.

Results

Check Result Note
Source review passed All changed files reviewed
Tests not run Author reports they passed
Build not run No build performed

Negative control

Not run; no tests were executed during this review.

Findings

Blocking

None.

Non-blocking

None.

Sources

Not verified

The reported tests were not rerun. Behavior on physical console hardware and other host operating systems was not verified.

To get this to a good state

Nothing is required.

@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 19434 _FDtest

@oneandonlydean
oneandonlydean merged commit ff7e207 into boykopovar:main Dec 5, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants