fix(libc): match lgamma's signgam for -0 and its errno at poles as measured on a PS5 #7544

Closed
ionut27001 wants to merge 1 commit from upstream-pr/7544 into main
ionut27001 commented 2026-10-18 13:01:55 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ionut27001 on 2026-10-18T13:01:55Z.


What

lgamma(-0) now leaves 1 in signgam, as the console's libSceLibcInternal.sprx does when called from a payload process on a PS5 (firmware 12.70); whether a title's own libc.prx does the same is unverified. Before, it left -1, following FreeBSD 11's e_lgamma_r.c.

Input Console signgam (libSceLibcInternal.sprx) main before this PR
-0 1 -1
+0, poles (-1, -2, -2^52), ±infinity, NaN 1 1 (unchanged)
-0x1p-80, the smallest negative subnormal -1 -1 (unchanged)
negative non-integers from -0.75 to -30.25 in steps of 0.5 -1 when the floor is odd, else 1 same (unchanged)

The return value is unchanged. On the console lgamma(-0) returns +infinity, like lgamma(0). For ±2^-1074 the console's value differs from the one here: 0x40875427f6acad6f (about 746.52), where this code returns -log(|x|) (about 744.44). p14 ran under the console's starting MXCSR 0x9fc0 (flush-to-zero and denormals-are-zero) and did not measure that input under 0x1f80, so this PR leaves the value alone and records it in the debt entry. The entry also records that, of the other 84 measured inputs, 32 come out 1 or 2 ulps away from the console's results with the host lgamma of this Windows build, lgamma(-2.5) 12 ulps away and lgamma(-2.75) 96 ulps away (this sentence said 66 inputs before; the 84 count both probes).

Only the special case for zero is removed. Zero now goes through the same rule as every other input, which gives 1 for both zeros. The existing test asserted -1 for -0; it now asserts 1.

errno. The console's lgamma also sets errno to ERANGE (34) after a pole and leaves it alone otherwise, an overflow included. The Windows build passed on the host's errno, which differs, as a reviewer noticed:

Input (errno set to 0 before the call) Console host lgamma of this Windows build (WinLibs GCC 15.2.0)
0, -0, -1, -2, -2^52, -1e306 (poles) 34 (ERANGE) 33 (EDOM)
1e306 (the result overflows) 0 34 (ERANGE)
±infinity, NaN 0 0

lgamma now saves errno, calls the host lgamma for the value and the floating-point flags as before, and then sets ERANGE for a pole (a zero or a negative integer) or puts the saved errno back. The host column comes from a small test program built with the same toolchain; the test checks the console's errno for each input above.

docs/dev/debt/libc.md: the lgamma and signgam entry said the rule was taken from the FreeBSD source and not measured. Since the sign and errno behaviour now follows the measurement, the entry is cut to what is still open: the host lgamma values that differ by a few ulps, the ±2^-1074 result measured under the console's starting MXCSR 0x9fc0 (0x1f80 not measured), and the assumption that a title's own libc.prx behaves like the console's libSceLibcInternal.sprx.

How the console was measured

Setup:

  • The console runs firmware 12.70 and is jailbroken.
  • Probes are ELF payloads built with ps5-payload-dev/sdk v0.44 and clang 18.1.8.
  • They were started through a payload manager, so they ran in a payload process, not in a title.

Method:

  • The resolve lines show that the called lgamma and the signgam read are the ones libSceLibcInternal.sprx exports.
  • p11 set signgam to 12345 before each call, so signgam=1 after lgamma(-0) is a value the call wrote.
  • Sources and the full logs are in the attached lgamma-probes.zip.
Console output (excerpt, lines copied unchanged)
p11: meta fw=0x12700001 pid=122 sdk=v0.44 compiler=Clang 18.1.8 built=Oct 18 2026 01:17:43
p14: meta fw=0x12700001 pid=126 sdk=v0.44 compiler=Clang 18.1.8 built=Oct 18 2026 01:52:17
p14: meta mxcsr_at_start=0x9fc0

p11: resolve sym=lgamma module=libSceLibcInternal.sprx same_as_called=yes
p11: resolve sym=signgam module=libSceLibcInternal.sprx same_as_called=yes

p11: case lgamma x=0x8000000000000000 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4
p11: case lgamma x=000000000000000000 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4
p11: case lgamma x=0xbff0000000000000 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4
p11: case lgamma x=0xc000000000000000 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4
p11: case lgamma x=0xff76c8e5ca239029 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4
p11: case lgamma x=0x7f76c8e5ca239029 result=0x7ff0000000000000 signgam=1 errno=0 fe=0x28
p11: case lgamma x=0x7ff0000000000000 result=0x7ff0000000000000 signgam=1 errno=0 fe=0
p11: case lgamma x=0xbfe0000000000000 result=0x3ff43f89a3f0edd6 signgam=-1 errno=0 fe=0x20
p11: case lgamma x=0xc004000000000000 result=0xbfaccbf9f5ed0f1c signgam=-1 errno=0 fe=0x20
p11: case lgamma x=0xfff0000000000000 result=0x7ff0000000000000 signgam=1 errno=0 fe=0
p11: case lgamma x=0x7ff8000000000000 result=0x7ff8000000000000 signgam=1 errno=0 fe=0
p14: case signgam_initial value=0
p14: case lgamma x=0xbaf0000000000000 result=0x404bb9d3beb8c86b signgam=-1 errno=0
p14: case lgamma x=0x0000000000000001 result=0x40875427f6acad6f signgam=1 errno=0
p14: case lgamma x=0x8000000000000001 result=0x40875427f6acad6f signgam=-1 errno=0
p14: case lgamma x=0xc330000000000000 result=0x7ff0000000000000 signgam=1 errno=34
p14: case lgamma x=0xc32fffffffffffff result=0xc38185966f2b4f12 signgam=1 errno=0
p14: case lgamma_sweep x=0xc03e400000000000 result=0xc052816ef5b73299 signgam=-1 errno=0

The pNN: prefix names the probe; the rest of each line is copied unchanged.

The p14 sweep has 60 lines, from -0.75 to -30.25. Every one matches the floor rule.

Overlaps:

  • None open that implement the same functions. #6158 and #6044, listed here before, are closed, and the jrand48/mrand48 and strtod PRs mentioned here earlier have landed.

Tested

Build: Windows 11 x86-64, full build with WinLibs MinGW-w64 GCC 15.2.0 (posix-seh, ucrt, r7) and -DBUILD_TESTING=ON.

Tests (earlier base 9f5d4bd92): with this branch rebased onto main 9f5d4bd92, guest_math and the other guest_* tests pass: 494 of 495, and guest_video_out_wqhd_detection_no_vulkan is skipped on this machine. That is the second of two full runs; the first, right after the build, timed out in two tests this PR does not touch (guest_pthread_rwlock, guest_fstatfs). With the final test, guest_math passed 3 runs in a row. Old code, new test: with Math.cpp reverted to main and the new tests kept, guest_math aborts. With only the new errno lines removed from lgamma, it aborts too.

Rebase (2026-10-26): rebased onto main f95acfc948. The only conflict was in docs/dev/debt/libc.md, next to the lgamma entry, which main had not changed. The entry is now cut to what is still open (the host lgamma values off by a few ulps, the ±2^-1074 result, and the untested MXCSR case), under the 1,000-character limit, because the sign and errno behaviour it described is what this PR implements. On that base, Windows 11 with WinLibs GCC 15.2.0: guest_math passes twice, and with Math.cpp restored from main it fails. The branch merges cleanly with the newer main fd0da73ec5, whose Math.cpp and GuestMath.cpp changes it was not re-run with.

Console: behaviour measured on a PS5 (firmware 12.70), as described above.

Not tested here: Linux (a reviewer reported a Linux run of head ac0a04e180, which has the errno change, in the comments), and no title.

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

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4909297157 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7544). Originally posted by [ionut27001](https://github.com/ionut27001) on 2026-10-18T13:01:55Z. --- ### What `lgamma(-0)` now leaves 1 in `signgam`, as the console's `libSceLibcInternal.sprx` does when called from a payload process on a PS5 (firmware 12.70); whether a title's own `libc.prx` does the same is unverified. Before, it left -1, following FreeBSD 11's `e_lgamma_r.c`. | Input | Console `signgam` (`libSceLibcInternal.sprx`) | `main` before this PR | |---|---|---| | -0 | 1 | -1 | | +0, poles (-1, -2, -2^52), ±infinity, NaN | 1 | 1 (unchanged) | | -0x1p-80, the smallest negative subnormal | -1 | -1 (unchanged) | | negative non-integers from -0.75 to -30.25 in steps of 0.5 | -1 when the floor is odd, else 1 | same (unchanged) | The return value is unchanged. On the console `lgamma(-0)` returns +infinity, like `lgamma(0)`. For ±2^-1074 the console's value differs from the one here: 0x40875427f6acad6f (about 746.52), where this code returns -log(|x|) (about 744.44). p14 ran under the console's starting MXCSR 0x9fc0 (flush-to-zero and denormals-are-zero) and did not measure that input under 0x1f80, so this PR leaves the value alone and records it in the debt entry. The entry also records that, of the other 84 measured inputs, 32 come out 1 or 2 ulps away from the console's results with the host `lgamma` of this Windows build, `lgamma(-2.5)` 12 ulps away and `lgamma(-2.75)` 96 ulps away (this sentence said 66 inputs before; the 84 count both probes). Only the special case for zero is removed. Zero now goes through the same rule as every other input, which gives 1 for both zeros. The existing test asserted -1 for -0; it now asserts 1. **`errno`.** The console's `lgamma` also sets `errno` to `ERANGE` (34) after a pole and leaves it alone otherwise, an overflow included. The Windows build passed on the host's `errno`, which differs, as a reviewer noticed: | Input (`errno` set to 0 before the call) | Console | host `lgamma` of this Windows build (WinLibs GCC 15.2.0) | |---|---|---| | 0, -0, -1, -2, -2^52, -1e306 (poles) | 34 (`ERANGE`) | 33 (`EDOM`) | | 1e306 (the result overflows) | 0 | 34 (`ERANGE`) | | ±infinity, NaN | 0 | 0 | `lgamma` now saves `errno`, calls the host `lgamma` for the value and the floating-point flags as before, and then sets `ERANGE` for a pole (a zero or a negative integer) or puts the saved `errno` back. The host column comes from a small test program built with the same toolchain; the test checks the console's `errno` for each input above. `docs/dev/debt/libc.md`: the `lgamma and signgam` entry said the rule was taken from the FreeBSD source and not measured. Since the sign and `errno` behaviour now follows the measurement, the entry is cut to what is still open: the host `lgamma` values that differ by a few ulps, the ±2^-1074 result measured under the console's starting MXCSR 0x9fc0 (0x1f80 not measured), and the assumption that a title's own `libc.prx` behaves like the console's `libSceLibcInternal.sprx`. #### How the console was measured **Setup:** - The console runs firmware 12.70 and is jailbroken. - Probes are ELF payloads built with [ps5-payload-dev/sdk](https://github.com/ps5-payload-dev/sdk) v0.44 and clang 18.1.8. - They were started through a payload manager, so they ran in a payload process, not in a title. **Method:** - The `resolve` lines show that the called `lgamma` and the `signgam` read are the ones `libSceLibcInternal.sprx` exports. - p11 set `signgam` to 12345 before each call, so `signgam=1` after `lgamma(-0)` is a value the call wrote. - Sources and the full logs are in the attached [lgamma-probes.zip](https://github.com/user-attachments/files/33628307/lgamma-probes.zip). <details><summary>Console output (excerpt, lines copied unchanged)</summary> ``` p11: meta fw=0x12700001 pid=122 sdk=v0.44 compiler=Clang 18.1.8 built=Oct 18 2026 01:17:43 p14: meta fw=0x12700001 pid=126 sdk=v0.44 compiler=Clang 18.1.8 built=Oct 18 2026 01:52:17 p14: meta mxcsr_at_start=0x9fc0 p11: resolve sym=lgamma module=libSceLibcInternal.sprx same_as_called=yes p11: resolve sym=signgam module=libSceLibcInternal.sprx same_as_called=yes p11: case lgamma x=0x8000000000000000 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4 p11: case lgamma x=000000000000000000 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4 p11: case lgamma x=0xbff0000000000000 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4 p11: case lgamma x=0xc000000000000000 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4 p11: case lgamma x=0xff76c8e5ca239029 result=0x7ff0000000000000 signgam=1 errno=34 fe=0x4 p11: case lgamma x=0x7f76c8e5ca239029 result=0x7ff0000000000000 signgam=1 errno=0 fe=0x28 p11: case lgamma x=0x7ff0000000000000 result=0x7ff0000000000000 signgam=1 errno=0 fe=0 p11: case lgamma x=0xbfe0000000000000 result=0x3ff43f89a3f0edd6 signgam=-1 errno=0 fe=0x20 p11: case lgamma x=0xc004000000000000 result=0xbfaccbf9f5ed0f1c signgam=-1 errno=0 fe=0x20 p11: case lgamma x=0xfff0000000000000 result=0x7ff0000000000000 signgam=1 errno=0 fe=0 p11: case lgamma x=0x7ff8000000000000 result=0x7ff8000000000000 signgam=1 errno=0 fe=0 p14: case signgam_initial value=0 p14: case lgamma x=0xbaf0000000000000 result=0x404bb9d3beb8c86b signgam=-1 errno=0 p14: case lgamma x=0x0000000000000001 result=0x40875427f6acad6f signgam=1 errno=0 p14: case lgamma x=0x8000000000000001 result=0x40875427f6acad6f signgam=-1 errno=0 p14: case lgamma x=0xc330000000000000 result=0x7ff0000000000000 signgam=1 errno=34 p14: case lgamma x=0xc32fffffffffffff result=0xc38185966f2b4f12 signgam=1 errno=0 p14: case lgamma_sweep x=0xc03e400000000000 result=0xc052816ef5b73299 signgam=-1 errno=0 ``` The `pNN:` prefix names the probe; the rest of each line is copied unchanged. The p14 sweep has 60 lines, from -0.75 to -30.25. Every one matches the floor rule. </details> **Overlaps:** - None open that implement the same functions. #6158 and #6044, listed here before, are closed, and the jrand48/mrand48 and strtod PRs mentioned here earlier have landed. ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> **Build:** Windows 11 x86-64, full build with WinLibs MinGW-w64 GCC 15.2.0 (posix-seh, ucrt, r7) and `-DBUILD_TESTING=ON`. **Tests (earlier base `9f5d4bd92`):** with this branch rebased onto `main` 9f5d4bd92, `guest_math` and the other `guest_*` tests pass: 494 of 495, and `guest_video_out_wqhd_detection_no_vulkan` is skipped on this machine. That is the second of two full runs; the first, right after the build, timed out in two tests this PR does not touch (`guest_pthread_rwlock`, `guest_fstatfs`). With the final test, `guest_math` passed 3 runs in a row. **Old code, new test:** with `Math.cpp` reverted to `main` and the new tests kept, `guest_math` aborts. With only the new `errno` lines removed from `lgamma`, it aborts too. **Rebase (2026-10-26):** rebased onto `main` f95acfc948. The only conflict was in `docs/dev/debt/libc.md`, next to the lgamma entry, which main had not changed. The entry is now cut to what is still open (the host `lgamma` values off by a few ulps, the ±2^-1074 result, and the untested MXCSR case), under the 1,000-character limit, because the sign and `errno` behaviour it described is what this PR implements. On that base, Windows 11 with WinLibs GCC 15.2.0: `guest_math` passes twice, and with `Math.cpp` restored from `main` it fails. The branch merges cleanly with the newer `main` fd0da73ec5, whose `Math.cpp` and `GuestMath.cpp` changes it was not re-run with. **Console:** behaviour measured on a PS5 (firmware 12.70), as described above. **Not tested here:** Linux (a reviewer reported a Linux run of head `ac0a04e180`, which has the `errno` change, in the comments), and no title. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [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 - [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 🤖 Generated with [Claude Code](https://claude.com/claude-code)
wachi35676 commented 2026-10-19 01:09:50 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by wachi35676 on 2026-10-19T01:09:50Z.


Ran this on both hosts (Windows 11 with WinLibs GCC 15.2.0 (full build), and WSL Ubuntu 24.04 with GCC 13.3, base a373e85e5). guest_math passes on both, and aborts on both with Math.cpp reverted; the description lists Linux as not tested.

I called the guest lgamma with p11's and p14's inputs on both hosts.

  • signgam now matches the console log for every input, including -0 (1).
  • Return bits match for ±0, the poles, ±infinity, NaN and ±0x1p-80 (0x404bb9d3beb8c86b).
  • ±2^-1074 gives 0x40874385446d71c3 on both hosts, against the console's 0x40875427f6acad6f, as the debt entry says.

The console's -0 result matches FreeBSD msun from before r271722 (2014-09-17, "lgamma_r(-0, &signgamp) should set signgamp = -1"). 10.0.0's e_lgamma_r.c sets *signgamp = 1 and returns for ±0 before any sign handling. 11.x sets *signgamp = 1-2*((uint32_t)hx>>31) first (11.4 e_lgamma_r.c#L216). That may be worth one clause in the debt entry.

Two things in the attached p11 log that this PR doesn't cover:

  • p11's lgammaf writes signgam (1 for -0, -1 for -2.5f). #6158's lgammaf (std::lgamma(x)) doesn't touch signgam.
  • After a pole, the console's errno is 34 (ERANGE). Here the guest errno is 34 on Linux but 33 (EDOM) on the Windows build, both before and after this PR.

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

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6257514182 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7544#issuecomment-6257514182). Originally posted by [wachi35676](https://github.com/wachi35676) on 2026-10-19T01:09:50Z. --- Ran this on both hosts (Windows 11 with WinLibs GCC 15.2.0 (full build), and WSL Ubuntu 24.04 with GCC 13.3, base `a373e85e5`). `guest_math` passes on both, and aborts on both with `Math.cpp` reverted; the description lists Linux as not tested. I called the guest `lgamma` with p11's and p14's inputs on both hosts. - `signgam` now matches the console log for every input, including -0 (1). - Return bits match for ±0, the poles, ±infinity, NaN and ±0x1p-80 (`0x404bb9d3beb8c86b`). - ±2^-1074 gives `0x40874385446d71c3` on both hosts, against the console's `0x40875427f6acad6f`, as the debt entry says. The console's -0 result matches FreeBSD msun from before r271722 (2014-09-17, "lgamma_r(-0, &signgamp) should set signgamp = -1"). 10.0.0's [`e_lgamma_r.c`](https://github.com/freebsd/freebsd-src/blob/release/10.0.0/lib/msun/src/e_lgamma_r.c#L214-L217) sets `*signgamp = 1` and returns for ±0 before any sign handling. 11.x sets `*signgamp = 1-2*((uint32_t)hx>>31)` first ([11.4 `e_lgamma_r.c#L216`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/lib/msun/src/e_lgamma_r.c#L216)). That may be worth one clause in the debt entry. Two things in the attached p11 log that this PR doesn't cover: - p11's `lgammaf` writes `signgam` (1 for -0, -1 for -2.5f). #6158's `lgammaf` (`std::lgamma(x)`) doesn't touch `signgam`. - After a pole, the console's `errno` is 34 (`ERANGE`). Here the guest `errno` is 34 on Linux but 33 (`EDOM`) on the Windows build, both before and after this PR. AI-assisted: yes (Claude Code); results above were run on this machine.
thepoppfish commented 2026-10-25 09:37:38 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by thepoppfish on 2026-10-25T09:37:38Z.

Review: COMMENTED


Reviewed exact head ac0a04e18012866fb909f718caa18aff76cc358f, including the newer errno change. This adds independent Windows validation beyond the older-version report above.

Windows 11 build 26200, MSYS2 UCRT64 GCC 16.2.0-6, CMake 4.3.1, Ninja 1.13.2:

  • The complete, unmodified repository GuestMath.cpp passes in an out-of-tree native harness, then passes three consecutive repeats (0.02 s each), and a final replay (0.03 s).
  • An additional probe checks 152 cases: the 16 special/representative inputs listed below plus the 60-value negative non-integer sweep, each starting with errno 0 and 12345. Both zeros give signgam 1; poles set ERANGE; non-poles preserve the prior errno, including positive overflow. All pass, including three repeats.
  • Three controls replace only the lgamma implementation in a scratch copy of the exact-head Math.cpp, keeping the submitted test: reverting both changes, only the zero-sign change, or only the errno change makes guest_math fail. The extra probe independently fails in 14, 2 and 14 cases, respectively. In the sign-only control, exactly the two -0 cases retain signgam -1. In the errno-only control, Windows gives EDOM at each pole and ERANGE on positive overflow instead of preserving errno.
  • The current-main conventions checker (b2c7a388406614fb3bc6723a6717a37196d617b8) reports zero errors and one debt-length warning: the changed lgamma entry is 2445 characters. Whitespace check passes.

The source change matches the published p11/p14 excerpt for the tested sign/errno cases. I did not independently measure a PS5, execute the attached payloads, verify retail libc equivalence, or resolve the explicitly documented subnormal return-value and host-ULP differences. This is target-level Windows validation, not a full shared-libc/product build, Linux/macOS run, sanitizer run, title run or cross-PR composition check.

The final harness compiles the actual Math.cpp, FloatBuiltins.cpp, Strings.cpp, IntegerBuiltins.cpp, RuntimeSupport.cpp and HostEntropy.cpp plus the complete actual GuestMath.cpp, with no LTO. Support.cpp supplies only __error returning the host errno pointer as Process.cpp does, a throwing NotImplemented helper, and Windows abort-report UI suppression. It does not replace math, conversion, floating-point environment or errno behavior.

Leaving this comment-only because git merge-tree --write-tree --name-only origin/main HEAD against main b2c7a388406614fb3bc6723a6717a37196d617b8 conflicts in docs/dev/debt/libc.md; the C++ source and test merge automatically. Please rebase and trim the changed debt entry to the remaining gaps, keeping the detailed measurement report here in the PR. No implementation defect found in this focused review.

AI-assisted: yes, OpenAI Codex. Commands and complete local harness follow so the validation can be replayed without modifying the PR checkout.

Replay on Windows with a MinGW GCC toolchain on PATH

Use the exact PR checkout as REPO; place these files in a separate directory. CMake locates g++, Ninja and objcopy through PATH. Python is needed only for the negative controls, which also need Git on PATH. The script uses the checkout's HEAD parent for the original function and verifies that each executable fails for all three controls.

cmake -S . -B build16 -G Ninja '-DCMAKE_CXX_COMPILER=g++.exe' '-DCMAKE_BUILD_TYPE=Release' '-DREPO=C:/path/to/exact-pr-checkout'
cmake --build build16 -j 3
ctest --test-dir build16 --output-on-failure --repeat until-fail:3

For negative_controls.py, put the exact checkout at ../review-7544 relative to the harness, as in the default CMake setting (or change the script's repo assignment). Run python negative_controls.py.

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)
project(AnyPS5LgammaReview LANGUAGES CXX)
enable_testing()
set(REPO "${CMAKE_CURRENT_LIST_DIR}/../review-7544" CACHE PATH "Exact PR checkout")
set(MATH_SOURCE "${REPO}/core/libs/prx/libc/src/Math.cpp" CACHE FILEPATH "Math source under test")
set(TEST_SOURCE "${REPO}/core/libs/tests/GuestMath.cpp" CACHE FILEPATH "Test source under test")
add_executable(guest_math
    "${MATH_SOURCE}"
    "${REPO}/core/libs/prx/libc/src/FloatBuiltins.cpp"
    "${REPO}/core/libs/prx/libc/src/Strings.cpp"
    "${REPO}/core/libs/prx/libc/src/IntegerBuiltins.cpp"
    "${REPO}/core/libs/prx/libc/src/RuntimeSupport.cpp"
    "${REPO}/core/libs/prx/libc/src/HostEntropy.cpp"
    "${TEST_SOURCE}"
    Support.cpp)
target_compile_features(guest_math PRIVATE cxx_std_20)
target_include_directories(guest_math PRIVATE "${REPO}/core/libs")
target_compile_options(guest_math PRIVATE -O1 -g -Wall -Wextra -ffunction-sections -fdata-sections)
target_link_options(guest_math PRIVATE -Wl,--gc-sections)
add_custom_command(TARGET guest_math POST_BUILD
    COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:guest_math>" VERBATIM)
add_test(NAME guest_math COMMAND guest_math)
set_tests_properties(guest_math PROPERTIES TIMEOUT 30)
add_executable(lgamma_probe "${MATH_SOURCE}" LgammaProbe.cpp Support.cpp)
target_compile_features(lgamma_probe PRIVATE cxx_std_20)
target_include_directories(lgamma_probe PRIVATE "${REPO}/core/libs")
target_compile_options(lgamma_probe PRIVATE -O1 -g -Wall -Wextra -ffunction-sections -fdata-sections)
target_link_options(lgamma_probe PRIVATE -Wl,--gc-sections)
add_custom_command(TARGET lgamma_probe POST_BUILD
    COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:lgamma_probe>" VERBATIM)
add_test(NAME lgamma_probe COMMAND lgamma_probe)
set_tests_properties(lgamma_probe PROPERTIES TIMEOUT 30)

Support.cpp

#include "prx/libc/include/General.hpp"
#include <cerrno>
#include <cstdlib>
#include <stdexcept>

[[maybe_unused]] const unsigned int abortFlags = _set_abort_behavior(0, _CALL_REPORTFAULT);

extern "C" int* APS5_VABI __error_nid_postfix() {
    return &errno;
}

extern "C" [[noreturn]] void NotImplemented_nid_no_patch(const char* name) {
    throw std::runtime_error(name);
}

LgammaProbe.cpp

#include "prx/libc/include/General.hpp"
#include <bit>
#include <cerrno>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <initializer_list>

extern "C" int signgam_nid_postfix;
extern "C" double APS5_VABI lgamma_nid_postfix(double);

int main() {
    struct Case { std::uint64_t bits; bool pole; int sign; };
    const Case cases[] = {
        {0x0000000000000000ull, true, 1}, {0x8000000000000000ull, true, 1},
        {0xbff0000000000000ull, true, 1}, {0xc000000000000000ull, true, 1},
        {0xc330000000000000ull, true, 1}, {0xff76c8e5ca239029ull, true, 1},
        {0x3fe0000000000000ull, false, 1}, {0xc004000000000000ull, false, -1},
        {0xc32fffffffffffffull, false, 1}, {0x7f76c8e5ca239029ull, false, 1},
        {0x7ff0000000000000ull, false, 1}, {0xfff0000000000000ull, false, 1},
        {0x7ff8000000000000ull, false, 1}, {0xbaf0000000000000ull, false, -1},
        {0x0000000000000001ull, false, 1}, {0x8000000000000001ull, false, -1}
    };
    int failures = 0;
    int checked = 0;
    for (const int previous : {0, 12345}) {
        for (const auto& test : cases) {
            errno = previous;
            signgam_nid_postfix = 12345;
            const double result = lgamma_nid_postfix(std::bit_cast<double>(test.bits));
            const int error = errno;
            if (error != (test.pole ? ERANGE : previous) || signgam_nid_postfix != test.sign ||
                (test.pole && (!std::isinf(result) || std::signbit(result)))) {
                std::fprintf(stderr, "bits=%016llx previous=%d errno=%d sign=%d result=%a\n",
                    static_cast<unsigned long long>(test.bits), previous, error, signgam_nid_postfix, result);
                ++failures;
            }
            ++checked;
        }
        for (int step = 0; step < 60; ++step) {
            const double value = -0.75 - step * 0.5;
            const int expected = step % 4 == 0 || step % 4 == 3 ? -1 : 1;
            errno = previous;
            signgam_nid_postfix = 12345;
            lgamma_nid_postfix(value);
            if (errno != previous || signgam_nid_postfix != expected) {
                std::fprintf(stderr, "sweep=%a previous=%d errno=%d sign=%d expected=%d\n",
                    value, previous, errno, signgam_nid_postfix, expected);
                ++failures;
            }
            ++checked;
        }
    }
    std::printf("%d lgamma cases, %d failures\n", checked, failures);
    return failures != 0;
}

negative_controls.py

from pathlib import Path
import subprocess

root = Path(__file__).resolve().parent
repo = root / '../review-7544'
source = (repo / 'core/libs/prx/libc/src/Math.cpp').read_text()
old = subprocess.run(['git', '-C', str(repo), 'show', 'HEAD^:core/libs/prx/libc/src/Math.cpp'],
                     capture_output=True, text=True, encoding='utf-8', check=True).stdout
start = 'double APS5_VABI lgamma_nid_postfix(double x) {'

def body(text):
    begin = text.index(start)
    return text[begin:text.index('\n}', begin) + 2]

fixed = body(source)
previous = body(old)
controls = {
    'old': source.replace(fixed, previous),
    'old-sign': source.replace('    signgam_nid_postfix = x < 0 && whole != x',
                              '    if (x == 0) signgam_nid_postfix = std::signbit(x) ? -1 : 1;\n    else signgam_nid_postfix = x < 0 && whole != x'),
    'old-errno': source.replace('    const int saved_errno = errno;\n    const double result = std::lgamma(x);\n    errno = std::isfinite(x) && x <= 0 && whole == x ? ERANGE : saved_errno;\n    return result;',
                               '    return std::lgamma(x);')
}
for name, content in controls.items():
    assert content != source
    math = root / f'Math-{name}.cpp'
    math.write_text(content)
    build = root / f'build16-{name}'
    commands = [
        ['cmake', '-S', str(root), '-B', str(build), '-G', 'Ninja', '-DCMAKE_CXX_COMPILER=g++.exe',
         '-DCMAKE_BUILD_TYPE=Release', f'-DMATH_SOURCE={math}'],
        ['cmake', '--build', str(build), '-j', '3']
    ]
    with (root / f'{name}-build.log').open('w', encoding='utf-8') as log:
        for command in commands:
            subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True, timeout=120)
    for executable in ('guest_math.exe', 'lgamma_probe.exe'):
        result = subprocess.run([str(build / executable)], capture_output=True, text=True, timeout=30)
        (root / f'{name}-{executable}.log').write_text(result.stdout + result.stderr)
        assert result.returncode != 0, (name, executable, result.stdout, result.stderr)
        print(name, executable, 'fails as expected', result.returncode,
              result.stdout.strip() or result.stderr[:150], flush=True)

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5642534574 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7544#pullrequestreview-5642534574). Originally posted by [thepoppfish](https://github.com/thepoppfish) on 2026-10-25T09:37:38Z. **Review:** COMMENTED --- Reviewed exact head `ac0a04e18012866fb909f718caa18aff76cc358f`, including the newer errno change. This adds independent Windows validation beyond the older-version report above. Windows 11 build 26200, MSYS2 UCRT64 GCC 16.2.0-6, CMake 4.3.1, Ninja 1.13.2: - The complete, unmodified repository `GuestMath.cpp` passes in an out-of-tree native harness, then passes three consecutive repeats (0.02 s each), and a final replay (0.03 s). - An additional probe checks 152 cases: the 16 special/representative inputs listed below plus the 60-value negative non-integer sweep, each starting with errno 0 and 12345. Both zeros give signgam 1; poles set ERANGE; non-poles preserve the prior errno, including positive overflow. All pass, including three repeats. - Three controls replace only the lgamma implementation in a scratch copy of the exact-head Math.cpp, keeping the submitted test: reverting both changes, only the zero-sign change, or only the errno change makes `guest_math` fail. The extra probe independently fails in 14, 2 and 14 cases, respectively. In the sign-only control, exactly the two -0 cases retain signgam -1. In the errno-only control, Windows gives EDOM at each pole and ERANGE on positive overflow instead of preserving errno. - The current-main conventions checker (`b2c7a388406614fb3bc6723a6717a37196d617b8`) reports zero errors and one debt-length warning: the changed lgamma entry is 2445 characters. Whitespace check passes. The source change matches the published p11/p14 excerpt for the tested sign/errno cases. I did not independently measure a PS5, execute the attached payloads, verify retail libc equivalence, or resolve the explicitly documented subnormal return-value and host-ULP differences. This is target-level Windows validation, not a full shared-libc/product build, Linux/macOS run, sanitizer run, title run or cross-PR composition check. The final harness compiles the actual Math.cpp, FloatBuiltins.cpp, Strings.cpp, IntegerBuiltins.cpp, RuntimeSupport.cpp and HostEntropy.cpp plus the complete actual GuestMath.cpp, with no LTO. Support.cpp supplies only __error returning the host errno pointer as Process.cpp does, a throwing NotImplemented helper, and Windows abort-report UI suppression. It does not replace math, conversion, floating-point environment or errno behavior. Leaving this comment-only because `git merge-tree --write-tree --name-only origin/main HEAD` against main `b2c7a388406614fb3bc6723a6717a37196d617b8` conflicts in `docs/dev/debt/libc.md`; the C++ source and test merge automatically. Please rebase and trim the changed debt entry to the remaining gaps, keeping the detailed measurement report here in the PR. No implementation defect found in this focused review. AI-assisted: yes, OpenAI Codex. Commands and complete local harness follow so the validation can be replayed without modifying the PR checkout. <details><summary>Replay on Windows with a MinGW GCC toolchain on PATH</summary> Use the exact PR checkout as REPO; place these files in a separate directory. CMake locates g++, Ninja and objcopy through PATH. Python is needed only for the negative controls, which also need Git on PATH. The script uses the checkout's HEAD parent for the original function and verifies that each executable fails for all three controls. ```powershell cmake -S . -B build16 -G Ninja '-DCMAKE_CXX_COMPILER=g++.exe' '-DCMAKE_BUILD_TYPE=Release' '-DREPO=C:/path/to/exact-pr-checkout' cmake --build build16 -j 3 ctest --test-dir build16 --output-on-failure --repeat until-fail:3 ``` For `negative_controls.py`, put the exact checkout at `../review-7544` relative to the harness, as in the default CMake setting (or change the script's repo assignment). Run `python negative_controls.py`. `CMakeLists.txt` ```cmake cmake_minimum_required(VERSION 3.20) project(AnyPS5LgammaReview LANGUAGES CXX) enable_testing() set(REPO "${CMAKE_CURRENT_LIST_DIR}/../review-7544" CACHE PATH "Exact PR checkout") set(MATH_SOURCE "${REPO}/core/libs/prx/libc/src/Math.cpp" CACHE FILEPATH "Math source under test") set(TEST_SOURCE "${REPO}/core/libs/tests/GuestMath.cpp" CACHE FILEPATH "Test source under test") add_executable(guest_math "${MATH_SOURCE}" "${REPO}/core/libs/prx/libc/src/FloatBuiltins.cpp" "${REPO}/core/libs/prx/libc/src/Strings.cpp" "${REPO}/core/libs/prx/libc/src/IntegerBuiltins.cpp" "${REPO}/core/libs/prx/libc/src/RuntimeSupport.cpp" "${REPO}/core/libs/prx/libc/src/HostEntropy.cpp" "${TEST_SOURCE}" Support.cpp) target_compile_features(guest_math PRIVATE cxx_std_20) target_include_directories(guest_math PRIVATE "${REPO}/core/libs") target_compile_options(guest_math PRIVATE -O1 -g -Wall -Wextra -ffunction-sections -fdata-sections) target_link_options(guest_math PRIVATE -Wl,--gc-sections) add_custom_command(TARGET guest_math POST_BUILD COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:guest_math>" VERBATIM) add_test(NAME guest_math COMMAND guest_math) set_tests_properties(guest_math PROPERTIES TIMEOUT 30) add_executable(lgamma_probe "${MATH_SOURCE}" LgammaProbe.cpp Support.cpp) target_compile_features(lgamma_probe PRIVATE cxx_std_20) target_include_directories(lgamma_probe PRIVATE "${REPO}/core/libs") target_compile_options(lgamma_probe PRIVATE -O1 -g -Wall -Wextra -ffunction-sections -fdata-sections) target_link_options(lgamma_probe PRIVATE -Wl,--gc-sections) add_custom_command(TARGET lgamma_probe POST_BUILD COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:lgamma_probe>" VERBATIM) add_test(NAME lgamma_probe COMMAND lgamma_probe) set_tests_properties(lgamma_probe PROPERTIES TIMEOUT 30) ``` `Support.cpp` ```cpp #include "prx/libc/include/General.hpp" #include <cerrno> #include <cstdlib> #include <stdexcept> [[maybe_unused]] const unsigned int abortFlags = _set_abort_behavior(0, _CALL_REPORTFAULT); extern "C" int* APS5_VABI __error_nid_postfix() { return &errno; } extern "C" [[noreturn]] void NotImplemented_nid_no_patch(const char* name) { throw std::runtime_error(name); } ``` `LgammaProbe.cpp` ```cpp #include "prx/libc/include/General.hpp" #include <bit> #include <cerrno> #include <cmath> #include <cstdint> #include <cstdio> #include <initializer_list> extern "C" int signgam_nid_postfix; extern "C" double APS5_VABI lgamma_nid_postfix(double); int main() { struct Case { std::uint64_t bits; bool pole; int sign; }; const Case cases[] = { {0x0000000000000000ull, true, 1}, {0x8000000000000000ull, true, 1}, {0xbff0000000000000ull, true, 1}, {0xc000000000000000ull, true, 1}, {0xc330000000000000ull, true, 1}, {0xff76c8e5ca239029ull, true, 1}, {0x3fe0000000000000ull, false, 1}, {0xc004000000000000ull, false, -1}, {0xc32fffffffffffffull, false, 1}, {0x7f76c8e5ca239029ull, false, 1}, {0x7ff0000000000000ull, false, 1}, {0xfff0000000000000ull, false, 1}, {0x7ff8000000000000ull, false, 1}, {0xbaf0000000000000ull, false, -1}, {0x0000000000000001ull, false, 1}, {0x8000000000000001ull, false, -1} }; int failures = 0; int checked = 0; for (const int previous : {0, 12345}) { for (const auto& test : cases) { errno = previous; signgam_nid_postfix = 12345; const double result = lgamma_nid_postfix(std::bit_cast<double>(test.bits)); const int error = errno; if (error != (test.pole ? ERANGE : previous) || signgam_nid_postfix != test.sign || (test.pole && (!std::isinf(result) || std::signbit(result)))) { std::fprintf(stderr, "bits=%016llx previous=%d errno=%d sign=%d result=%a\n", static_cast<unsigned long long>(test.bits), previous, error, signgam_nid_postfix, result); ++failures; } ++checked; } for (int step = 0; step < 60; ++step) { const double value = -0.75 - step * 0.5; const int expected = step % 4 == 0 || step % 4 == 3 ? -1 : 1; errno = previous; signgam_nid_postfix = 12345; lgamma_nid_postfix(value); if (errno != previous || signgam_nid_postfix != expected) { std::fprintf(stderr, "sweep=%a previous=%d errno=%d sign=%d expected=%d\n", value, previous, errno, signgam_nid_postfix, expected); ++failures; } ++checked; } } std::printf("%d lgamma cases, %d failures\n", checked, failures); return failures != 0; } ``` `negative_controls.py` ```python from pathlib import Path import subprocess root = Path(__file__).resolve().parent repo = root / '../review-7544' source = (repo / 'core/libs/prx/libc/src/Math.cpp').read_text() old = subprocess.run(['git', '-C', str(repo), 'show', 'HEAD^:core/libs/prx/libc/src/Math.cpp'], capture_output=True, text=True, encoding='utf-8', check=True).stdout start = 'double APS5_VABI lgamma_nid_postfix(double x) {' def body(text): begin = text.index(start) return text[begin:text.index('\n}', begin) + 2] fixed = body(source) previous = body(old) controls = { 'old': source.replace(fixed, previous), 'old-sign': source.replace(' signgam_nid_postfix = x < 0 && whole != x', ' if (x == 0) signgam_nid_postfix = std::signbit(x) ? -1 : 1;\n else signgam_nid_postfix = x < 0 && whole != x'), 'old-errno': source.replace(' const int saved_errno = errno;\n const double result = std::lgamma(x);\n errno = std::isfinite(x) && x <= 0 && whole == x ? ERANGE : saved_errno;\n return result;', ' return std::lgamma(x);') } for name, content in controls.items(): assert content != source math = root / f'Math-{name}.cpp' math.write_text(content) build = root / f'build16-{name}' commands = [ ['cmake', '-S', str(root), '-B', str(build), '-G', 'Ninja', '-DCMAKE_CXX_COMPILER=g++.exe', '-DCMAKE_BUILD_TYPE=Release', f'-DMATH_SOURCE={math}'], ['cmake', '--build', str(build), '-j', '3'] ] with (root / f'{name}-build.log').open('w', encoding='utf-8') as log: for command in commands: subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True, timeout=120) for executable in ('guest_math.exe', 'lgamma_probe.exe'): result = subprocess.run([str(build / executable)], capture_output=True, text=True, timeout=30) (root / f'{name}-{executable}.log').write_text(result.stdout + result.stderr) assert result.returncode != 0, (name, executable, result.stdout, result.stderr) print(name, executable, 'fails as expected', result.returncode, result.stdout.strip() or result.stderr[:150], flush=True) ``` </details>
MarcZX10 commented 2026-11-23 02:41:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T02:41:16Z.

Review: COMMENTED


Reviewed — no blocking findings

The changed lgamma logic and its tests were reviewed at head 92365e35a4cac04a651731dc1fb0cdd4fb52851b; no concrete defect was found, but tests were not run and the complete changed files were not read.

What I ran

Read the prepared description, commits, manifest, diff, and targeted ranges from all three changed files using repo_read.py’s review reader. No build or tests were run.

Results

Check Result Note
Changed logic review passed Targeted hunks and context read
Build and tests not run No test execution available
Changed file completeness not run Full files were not read

Negative control

Not run; no test execution was available.

Findings

Blocking

None found in the changed hunks reviewed.

Non-blocking

None.

Sources

Reviewed the changed hunks at core/libs/prx/libc/src/Math.cpp:725-730, core/libs/tests/GuestMath.cpp:1805-1817, and docs/dev/debt/libc.md:117 in the prepared diff and pinned-head reader output.

Not verified

Build and test results, including the author-reported runs, were not independently verified. The full contents of the three changed files were not read; only relevant ranges were inspected. The manifest lists all three as included, and no changed files were excluded.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6015983615 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/7544#pullrequestreview-6015983615). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-23T02:41:16Z. **Review:** COMMENTED --- # Reviewed — no blocking findings The changed `lgamma` logic and its tests were reviewed at head `92365e35a4cac04a651731dc1fb0cdd4fb52851b`; no concrete defect was found, but tests were not run and the complete changed files were not read. ## What I ran Read the prepared description, commits, manifest, diff, and targeted ranges from all three changed files using `repo_read.py`’s review reader. No build or tests were run. ## Results | Check | Result | Note | |---|---|---| | Changed logic review | passed | Targeted hunks and context read | | Build and tests | not run | No test execution available | | Changed file completeness | not run | Full files were not read | ## Negative control Not run; no test execution was available. ## Findings ### Blocking None found in the changed hunks reviewed. ### Non-blocking None. ## Sources Reviewed the changed hunks at `core/libs/prx/libc/src/Math.cpp:725-730`, `core/libs/tests/GuestMath.cpp:1805-1817`, and `docs/dev/debt/libc.md:117` in the prepared diff and pinned-head reader output. ## Not verified Build and test results, including the author-reported runs, were not independently verified. The full contents of the three changed files were not read; only relevant ranges were inspected. The manifest lists all three as included, and no changed files were excluded. ## To get this to a good state Nothing is required.

Pull request closed

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!7544
No description provided.