feat(libc): implement fesetenv #8937

Merged
UnhealthyKraken merged 5 commits from upstream-pr/8937 into main 2026-11-01 06:16:41 +00:00
UnhealthyKraken commented 2026-10-21 06:42:18 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by UnhealthyKraken on 2026-10-21T06:42:18Z.


What

Adds missing fesetenv (Q-bLp+b-RVY) to shared libc. It restores the saved 28-byte x87 environment and independent MXCSR from the existing 32-byte guest layout, preserving errno and leaving pending x87 exception delivery until a subsequent waiting instruction.

The signature, layout and restore sequence follow the pinned public SDK header and FreeBSD reference. The name appears in the firmware export inventory and its NID is independently corroborated by sce_symbols. Null inputs and bits unsupported by the current host's FXSAVE MXCSR mask throw before changing state; a zero reported mask uses the architectural 0xffbf fallback; console fault behavior is unverified. Intel documents these reserved MXCSR bits. Console ABI/behavior and module/library versions remain unmeasured; the separate __fe_dfl_env object remains missing, with its console initializer unknown.

Tested

Windows x86-64, MinGW GCC15.2 Release; no game run. Baseline ec7eacc62d5839aa3134e43d347485c923db07d1, candidate 6e43cea19323048ab02875e7a43fa3729a048bed.

  • Regression added before implementation: missing-export failure, both existing math suites pass.
  • Final identical binaries against preserved baseline vs candidate DLLs: baseline 7 missing-export failures/2 math passes; candidate 9/9 pass.
  • State matrix: 196,608 x87/SSE flag, rounding and precision combinations; 4,096 independent mask pairs; supported DAZ/FTZ; tags/TOP/pointers; guest fegetenv round trip; errno; two-thread isolation; read-only input ending exactly at guard page; null/host-unsupported bits preserve state.
  • Review regression: before the mask fix, an isolated modelled-host probe fails 4/15 cases; the same executable with FXSAVE report substitution passes 15/15 after the fix. It models masks 0/0xffbf/0xffff by changing only the capability report in its own process. This is not an unsupported physical CPU measurement. Native tests additionally check all bits unsupported by the actual host mask.
  • Thread-test repair after a reviewer-reported Linux flake: errno sentinel/capture now bracket only fesetenv. A deterministic fixture that changes errno after each barrier fails the old test and passes the repair; Windows main case passes 20 consecutive repetitions. The reviewer's Linux result is attributed, not an own Linux run.
  • Six subprocess tests verify restoration returns before fwait delivers a pending enabled x87 exception. Windows checks saved active cause and exception code; denormal accepts INVALID_OPERATION only with solely the saved denormal cause (matching prior native hardware checks). POSIX handler checks SIGFPE/return ordering but not saved cause; Linux/macOS were not run here.
  • Full libs and affected test targets build. Final CTest 10/10: new state test, six deferred-exception cases, guest_math, guest_math_exact, patched_libraries.357 patched libraries load,0 failures; this is loader coverage, not behavior coverage for those libraries.
  • Conventions, whitespace checks and independent code review pass. Final overlap scan has no reported same-line/export conflict;16 base-conflicted shared-file warnings were reviewed. #6044 reorganizes test directories; the new test will need the same mechanical relocation if it lands first. The initial insertion conflict with #8863 was removed; no implementation dependency on #8863 or #8903.
cmake --build <build> --target libs patched_libraries_tests guest_set_env_tests guest_math_tests guest_math_exact_tests -j 6
ctest --test-dir <build> -R '^(guest_set_env(_pending_[0-5])?|guest_math|guest_math_exact|patched_libraries)$' --output-on-failure --timeout 30
python tools/check_conventions.py --base origin/main
python tools/pr_overlap.py --branch feat/libc-fesetenv --repo boykopovar/AnyPS5

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
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4947513626 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8937). Originally posted by [UnhealthyKraken](https://github.com/UnhealthyKraken) on 2026-10-21T06:42:18Z. --- ### What Adds missing `fesetenv` (`Q-bLp+b-RVY`) to shared libc. It restores the saved 28-byte x87 environment and independent MXCSR from the existing 32-byte guest layout, preserving errno and leaving pending x87 exception delivery until a subsequent waiting instruction. The signature, layout and restore sequence follow the pinned [public SDK header](https://github.com/ps5-payload-dev/sdk/blob/a7685ce8e97ce1f8a4f38253a41d54241c9124f1/include/freebsd/fenv.h#L328) and [FreeBSD reference](https://github.com/freebsd/freebsd-src/blob/d106002967eff712894ab8b5337bbbff106ce5e0/lib/msun/x86/fenv.h). The name appears in the firmware export inventory and its NID is independently corroborated by `sce_symbols`. Null inputs and bits unsupported by the current host's `FXSAVE` MXCSR mask throw before changing state; a zero reported mask uses the architectural `0xffbf` fallback; console fault behavior is unverified. Intel documents these [reserved MXCSR bits](https://cdrdv2-public.intel.com/671436/253665-sdm-vol-1.pdf). Console ABI/behavior and module/library versions remain unmeasured; the separate `__fe_dfl_env` object remains missing, with its console initializer unknown. ### Tested Windows x86-64, MinGW GCC15.2 Release; no game run. Baseline `ec7eacc62d5839aa3134e43d347485c923db07d1`, candidate `6e43cea19323048ab02875e7a43fa3729a048bed`. - Regression added before implementation: missing-export failure, both existing math suites pass. - Final identical binaries against preserved baseline vs candidate DLLs: baseline 7 missing-export failures/2 math passes; candidate 9/9 pass. - State matrix: 196,608 x87/SSE flag, rounding and precision combinations; 4,096 independent mask pairs; supported DAZ/FTZ; tags/TOP/pointers; guest `fegetenv` round trip; errno; two-thread isolation; read-only input ending exactly at guard page; null/host-unsupported bits preserve state. - Review regression: before the mask fix, an isolated modelled-host probe fails 4/15 cases; the same executable with FXSAVE report substitution passes 15/15 after the fix. It models masks 0/0xffbf/0xffff by changing only the capability report in its own process. This is not an unsupported physical CPU measurement. Native tests additionally check all bits unsupported by the actual host mask. - Thread-test repair after a reviewer-reported Linux flake: errno sentinel/capture now bracket only fesetenv. A deterministic fixture that changes errno after each barrier fails the old test and passes the repair; Windows main case passes 20 consecutive repetitions. The reviewer's Linux result is attributed, not an own Linux run. - Six subprocess tests verify restoration returns before `fwait` delivers a pending enabled x87 exception. Windows checks saved active cause and exception code; denormal accepts INVALID_OPERATION only with solely the saved denormal cause (matching prior native hardware checks). POSIX handler checks SIGFPE/return ordering but not saved cause; Linux/macOS were not run here. - Full `libs` and affected test targets build. Final CTest 10/10: new state test, six deferred-exception cases, `guest_math`, `guest_math_exact`, `patched_libraries`.357 patched libraries load,0 failures; this is loader coverage, not behavior coverage for those libraries. - Conventions, whitespace checks and independent code review pass. Final overlap scan has no reported same-line/export conflict;16 base-conflicted shared-file warnings were reviewed. #6044 reorganizes test directories; the new test will need the same mechanical relocation if it lands first. The initial insertion conflict with #8863 was removed; no implementation dependency on #8863 or #8903. ```powershell cmake --build <build> --target libs patched_libraries_tests guest_set_env_tests guest_math_tests guest_math_exact_tests -j 6 ctest --test-dir <build> -R '^(guest_set_env(_pending_[0-5])?|guest_math|guest_math_exact|patched_libraries)$' --output-on-failure --timeout 30 python tools/check_conventions.py --base origin/main python tools/pr_overlap.py --branch feat/libc-fesetenv --repo boykopovar/AnyPS5 ``` <!-- 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. --> ### 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
MarcZX10 commented 2026-10-21 06:50:06 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-21T06:50:06Z.

Review: COMMENTED


One edge case to consider before merge: the guard only rejects MXCSR bits 16–31. The architectural MXCSR_MASK can also report unsupported bits within the low 16 (notably DAZ bit 6); ldmxcsr with one of those bits set raises #GP on a host that does not support it. I saw the test query the host mask before testing DAZ, but the implementation does not appear to use that mask to validate incoming environments. Does AnyPS5 require DAZ on every supported host, or should fesetenv reject an input containing host-unsupported bits before fldenv/_mm_setcsr? The console behavior for malformed environments can remain documented as unverified.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5595929226 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8937#pullrequestreview-5595929226). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-21T06:50:06Z. **Review:** COMMENTED --- One edge case to consider before merge: the guard only rejects MXCSR bits 16–31. The architectural MXCSR_MASK can also report unsupported bits within the low 16 (notably DAZ bit 6); `ldmxcsr` with one of those bits set raises #GP on a host that does not support it. I saw the test query the host mask before testing DAZ, but the implementation does not appear to use that mask to validate incoming environments. Does AnyPS5 require DAZ on every supported host, or should `fesetenv` reject an input containing host-unsupported bits before `fldenv`/`_mm_setcsr`? The console behavior for malformed environments can remain documented as unverified.
MarcZX10 commented 2026-10-21 06:52:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-21T06:52:32Z.


I verified the concern against AMD’s current architecture manual: it says DAZ support is indicated by MXCSR_MASK and recommends masking writes with the returned/default mask to avoid #GP. The project’s required AVX2 feature set does not itself check this per-register mask. Source: AMD64 Architecture Programmer’s Manual, Vol. 2.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6309970662 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8937#issuecomment-6309970662). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-21T06:52:32Z. --- I verified the concern against AMD’s current architecture manual: it says DAZ support is indicated by `MXCSR_MASK` and recommends masking writes with the returned/default mask to avoid #GP. The project’s required AVX2 feature set does not itself check this per-register mask. Source: [AMD64 Architecture Programmer’s Manual, Vol. 2](https://docs.amd.com/api/khub/documents/sD1_QL~h4Afq2_tvzxqqSQ/content).
MarcZX10 commented 2026-10-21 06:58:59 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-21T06:58:59Z.

Review: COMMENTED


Linux verification found a flaky failure in the new thread test. The build succeeds; all six guest_set_env_pending_* cases pass. guest_set_env failed at thread-local errno on the first run and again on the fourth run of ctest --repeat until-fail:20; adding a diagnostic print made it pass once. In Threads(), each worker sets errno before the first std::barrier::arrive_and_wait(), then checks it after a second barrier. Since the intended assertion is that fesetenv preserves errno, set the sentinel immediately after the first barrier and check it immediately after setEnvironment, before the second barrier. That removes unrelated synchronization calls from the errno assertion.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5596014734 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8937#pullrequestreview-5596014734). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-21T06:58:59Z. **Review:** COMMENTED --- Linux verification found a flaky failure in the new thread test. The build succeeds; all six `guest_set_env_pending_*` cases pass. `guest_set_env` failed at `thread-local errno` on the first run and again on the fourth run of `ctest --repeat until-fail:20`; adding a diagnostic print made it pass once. In `Threads()`, each worker sets errno before the first `std::barrier::arrive_and_wait()`, then checks it after a second barrier. Since the intended assertion is that `fesetenv` preserves errno, set the sentinel immediately after the first barrier and check it immediately after `setEnvironment`, before the second barrier. That removes unrelated synchronization calls from the errno assertion.
MarcZX10 commented 2026-10-21 07:04:57 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-21T07:04:57Z.


I made the errno test adjustment on my fork at codex/fix-fesetenv-errno-test. It sets the sentinel after the first barrier and snapshots errno immediately after fesetenv, before the second barrier. On Linux, the focused target builds; guest_set_env passes 20 consecutive runs, and all seven environment tests pass. git diff --check and tools/check_conventions.py --base upstream/main pass. I could not push directly to this PR head (GitHub returned 403 for the fork branch), so the commit is available to cherry-pick if useful.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6310161419 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8937#issuecomment-6310161419). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-21T07:04:57Z. --- I made the errno test adjustment on my fork at [`codex/fix-fesetenv-errno-test`](https://github.com/MarcZX10/AnyPS5/commit/0c5da2c2f8). It sets the sentinel after the first barrier and snapshots errno immediately after `fesetenv`, before the second barrier. On Linux, the focused target builds; `guest_set_env` passes 20 consecutive runs, and all seven environment tests pass. `git diff --check` and `tools/check_conventions.py --base upstream/main` pass. I could not push directly to this PR head (GitHub returned 403 for the fork branch), so the commit is available to cherry-pick if useful.
UnhealthyKraken commented 2026-10-21 07:08:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by UnhealthyKraken on 2026-10-21T07:08:24Z.


Confirmed the mask gap. I found no explicit DAZ requirement in the project's host CPU checks, so the implementation now validates against the actual FXSAVE MXCSR_MASK before changing either environment. A zero report uses the architectural 0xffbf fallback, following Intel's guidelines. Commit 40add4dc2fb77a3096d0fa080adf94c779ba8e8b.

I added the regression before changing production behavior. The existing DLL failed 4 of 15 modelled-mask cases (DAZ accepted under 0/0xffbf). The same probe executable passes 15/15 on the correction; it substitutes only the FXSAVE report in its own process. This is modelled capability coverage, not evidence from a physical CPU lacking DAZ. The actual function's rejection path and unchanged-state checks run natively.

The upstream test now tries every bit unsupported by the actual host mask. Full Windows libs build, all 10 native/loader cases, and 357 library loads pass. The final identical test binaries still give 7 missing-export failures/2 math passes against the original missing-export baseline, then 9/9 on the candidate. Independent review, conventions and whitespace checks pass; 16 base-conflicted overlap warnings were reviewed without a same-line/export conflict. Linux/macOS/console behavior remains unmeasured here. PR description and debt were updated; AI-assisted remains yes.

For reproduction, the source below takes a libc path and optionally the current function's FXSAVE instruction offset, memory displacement, instruction length and register index. Decode those from the exact candidate disassembly; for this GCC15.2 build they are 0x1b 0x30 5 4 (RSP). Without a FXSAVE site, the initial implementation runs with no substitution and fails the four expected mask cases. The fixture patches only its own mapped image and restores it; no on-disk DLL or other process is modified.

g++ -std=c++20 -O3 -DNDEBUG -fno-asynchronous-unwind-tables '-Wl,--wrap=main' fesetenv-host-mask-probe.cpp cmake/WindowsTestExit.cpp <libc-import-library> -o fesetenv-host-mask-probe.exe
objcopy --rename-section .eh_frame=.ehfram fesetenv-host-mask-probe.exe
objdump -d --disassemble=fesetenv_nid_postfix <candidate-unpatched-libc>
.\fesetenv-host-mask-probe.exe <initial-unpatched-libc>
.\fesetenv-host-mask-probe.exe <candidate-unpatched-libc> 0x1b 0x30 5 4
Modelled-host probe source
#include <windows.h>
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <xmmintrin.h>
struct Environment { std::array<std::uint32_t,7> x87; std::uint32_t mxcsr; };
using Set=int(__attribute__((sysv_abi))*)(const Environment*);
Environment readState() { Environment v; asm volatile("fnstenv %0\n\tfldenv %0":"=m"(v.x87)); v.mxcsr=_mm_getcsr(); return v; }
void writeState(const Environment& v) { asm volatile("fldenv %0"::"m"(v.x87)); _mm_setcsr(v.mxcsr); }
unsigned char* instruction=nullptr;
unsigned instructionLength=0;
long displacement=0;
unsigned registerIndex=0;
std::uint32_t reportedMask=0xffbf;
unsigned injected=0;
LONG CALLBACK substituteMask(EXCEPTION_POINTERS* p) {
    if(p->ExceptionRecord->ExceptionCode!=EXCEPTION_ILLEGAL_INSTRUCTION || p->ContextRecord->Rip!=reinterpret_cast<std::uintptr_t>(instruction)) return EXCEPTION_CONTINUE_SEARCH;
    auto& c=*p->ContextRecord;
    const std::uintptr_t registers[]{c.Rax,c.Rcx,c.Rdx,c.Rbx,c.Rsp,c.Rbp,c.Rsi,c.Rdi,c.R8,c.R9,c.R10,c.R11,c.R12,c.R13,c.R14,c.R15};
    auto* output=reinterpret_cast<unsigned char*>(registers[registerIndex]+displacement);
    std::memset(output,0,512);
    std::memcpy(output+28,&reportedMask,4);
    ++injected;
    c.Rip+=instructionLength;
    return EXCEPTION_CONTINUE_EXECUTION;
}
int main(int argc,char** argv) {
    SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
    if(argc!=2 && argc!=6) return 2;
    auto module=LoadLibraryA(argv[1]);
    if(!module) return 3;
    auto set=reinterpret_cast<Set>(GetProcAddress(module,"fesetenv_nid_postfix"));
    if(!set) return 4;
    unsigned char originalInstruction[2]{};
    DWORD originalProtection=0;
    if(argc==6) {
        instruction=reinterpret_cast<unsigned char*>(set)+std::strtoul(argv[2],nullptr,0);
        displacement=std::strtol(argv[3],nullptr,0);
        instructionLength=static_cast<unsigned>(std::strtoul(argv[4],nullptr,0));
        registerIndex=static_cast<unsigned>(std::strtoul(argv[5],nullptr,0));
        if(registerIndex>=16 || instructionLength<3 || instruction[0]!=0x0f || instruction[1]!=0xae) return 5;
        std::memcpy(originalInstruction,instruction,2);
        if(!VirtualProtect(instruction,2,PAGE_EXECUTE_READWRITE,&originalProtection)) return 6;
        instruction[0]=0x0f; instruction[1]=0x0b;
        FlushInstructionCache(GetCurrentProcess(),instruction,2);
        if(!AddVectoredExceptionHandler(1,substituteMask)) return 7;
    }
    const auto original=readState();
    unsigned cases=0,failures=0;
    for(const std::uint32_t mask:{0u,0xffbfu,0xffffu}) {
        reportedMask=mask;
        for(const std::uint32_t extra:{0u,0x40u,0x8000u,0x8040u,0x10000u}) {
            auto requested=original;
            requested.x87[0]^=0xc00;
            requested.mxcsr|=extra;
            const auto actualMask=mask ? mask : 0xffbf;
            const bool shouldReject=(requested.mxcsr&~actualMask)!=0;
            bool rejected=false;
            int result=-99;
            try { result=set(&requested); } catch(const std::invalid_argument&) { rejected=true; }
            const auto after=readState();
            writeState(original);
            const bool good=shouldReject ? rejected && after.x87==original.x87 && after.mxcsr==original.mxcsr : !rejected && result==0 && after.x87==requested.x87 && after.mxcsr==requested.mxcsr;
            if(!good) { std::printf("FAIL modelMask=%x input=%x expectedReject=%d actualReject=%d result=%d\n",mask,requested.mxcsr,shouldReject,rejected,result); ++failures; }
            ++cases;
        }
    }
    if(instruction) {
        std::memcpy(instruction,originalInstruction,2);
        FlushInstructionCache(GetCurrentProcess(),instruction,2);
        DWORD ignored;
        VirtualProtect(instruction,2,originalProtection,&ignored);
    }
    std::printf("Modelled FXSAVE masks:cases=%u failures=%u intercepted=%u; not an unsupported physical CPU measurement\n",cases,failures,injected);
    return failures ? 10 : 0;
}

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6310216408 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8937#issuecomment-6310216408). Originally posted by [UnhealthyKraken](https://github.com/UnhealthyKraken) on 2026-10-21T07:08:24Z. --- Confirmed the mask gap. I found no explicit DAZ requirement in the project's host CPU checks, so the implementation now validates against the actual `FXSAVE` MXCSR_MASK before changing either environment. A zero report uses the architectural `0xffbf` fallback, following [Intel's guidelines](https://cdrdv2-public.intel.com/819710/252046-sdm-change-document.pdf). Commit `40add4dc2fb77a3096d0fa080adf94c779ba8e8b`. I added the regression before changing production behavior. The existing DLL failed 4 of 15 modelled-mask cases (DAZ accepted under 0/0xffbf). The same probe executable passes 15/15 on the correction; it substitutes only the FXSAVE report in its own process. This is modelled capability coverage, not evidence from a physical CPU lacking DAZ. The actual function's rejection path and unchanged-state checks run natively. The upstream test now tries every bit unsupported by the actual host mask. Full Windows libs build, all 10 native/loader cases, and 357 library loads pass. The final identical test binaries still give 7 missing-export failures/2 math passes against the original missing-export baseline, then 9/9 on the candidate. Independent review, conventions and whitespace checks pass; 16 base-conflicted overlap warnings were reviewed without a same-line/export conflict. Linux/macOS/console behavior remains unmeasured here. PR description and debt were updated; AI-assisted remains yes. For reproduction, the source below takes a libc path and optionally the current function's FXSAVE instruction offset, memory displacement, instruction length and register index. Decode those from the exact candidate disassembly; for this GCC15.2 build they are `0x1b 0x30 5 4` (RSP). Without a FXSAVE site, the initial implementation runs with no substitution and fails the four expected mask cases. The fixture patches only its own mapped image and restores it; no on-disk DLL or other process is modified. ```powershell g++ -std=c++20 -O3 -DNDEBUG -fno-asynchronous-unwind-tables '-Wl,--wrap=main' fesetenv-host-mask-probe.cpp cmake/WindowsTestExit.cpp <libc-import-library> -o fesetenv-host-mask-probe.exe objcopy --rename-section .eh_frame=.ehfram fesetenv-host-mask-probe.exe objdump -d --disassemble=fesetenv_nid_postfix <candidate-unpatched-libc> .\fesetenv-host-mask-probe.exe <initial-unpatched-libc> .\fesetenv-host-mask-probe.exe <candidate-unpatched-libc> 0x1b 0x30 5 4 ``` <details><summary>Modelled-host probe source</summary> ```cpp #include <windows.h> #include <array> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <stdexcept> #include <xmmintrin.h> struct Environment { std::array<std::uint32_t,7> x87; std::uint32_t mxcsr; }; using Set=int(__attribute__((sysv_abi))*)(const Environment*); Environment readState() { Environment v; asm volatile("fnstenv %0\n\tfldenv %0":"=m"(v.x87)); v.mxcsr=_mm_getcsr(); return v; } void writeState(const Environment& v) { asm volatile("fldenv %0"::"m"(v.x87)); _mm_setcsr(v.mxcsr); } unsigned char* instruction=nullptr; unsigned instructionLength=0; long displacement=0; unsigned registerIndex=0; std::uint32_t reportedMask=0xffbf; unsigned injected=0; LONG CALLBACK substituteMask(EXCEPTION_POINTERS* p) { if(p->ExceptionRecord->ExceptionCode!=EXCEPTION_ILLEGAL_INSTRUCTION || p->ContextRecord->Rip!=reinterpret_cast<std::uintptr_t>(instruction)) return EXCEPTION_CONTINUE_SEARCH; auto& c=*p->ContextRecord; const std::uintptr_t registers[]{c.Rax,c.Rcx,c.Rdx,c.Rbx,c.Rsp,c.Rbp,c.Rsi,c.Rdi,c.R8,c.R9,c.R10,c.R11,c.R12,c.R13,c.R14,c.R15}; auto* output=reinterpret_cast<unsigned char*>(registers[registerIndex]+displacement); std::memset(output,0,512); std::memcpy(output+28,&reportedMask,4); ++injected; c.Rip+=instructionLength; return EXCEPTION_CONTINUE_EXECUTION; } int main(int argc,char** argv) { SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX); if(argc!=2 && argc!=6) return 2; auto module=LoadLibraryA(argv[1]); if(!module) return 3; auto set=reinterpret_cast<Set>(GetProcAddress(module,"fesetenv_nid_postfix")); if(!set) return 4; unsigned char originalInstruction[2]{}; DWORD originalProtection=0; if(argc==6) { instruction=reinterpret_cast<unsigned char*>(set)+std::strtoul(argv[2],nullptr,0); displacement=std::strtol(argv[3],nullptr,0); instructionLength=static_cast<unsigned>(std::strtoul(argv[4],nullptr,0)); registerIndex=static_cast<unsigned>(std::strtoul(argv[5],nullptr,0)); if(registerIndex>=16 || instructionLength<3 || instruction[0]!=0x0f || instruction[1]!=0xae) return 5; std::memcpy(originalInstruction,instruction,2); if(!VirtualProtect(instruction,2,PAGE_EXECUTE_READWRITE,&originalProtection)) return 6; instruction[0]=0x0f; instruction[1]=0x0b; FlushInstructionCache(GetCurrentProcess(),instruction,2); if(!AddVectoredExceptionHandler(1,substituteMask)) return 7; } const auto original=readState(); unsigned cases=0,failures=0; for(const std::uint32_t mask:{0u,0xffbfu,0xffffu}) { reportedMask=mask; for(const std::uint32_t extra:{0u,0x40u,0x8000u,0x8040u,0x10000u}) { auto requested=original; requested.x87[0]^=0xc00; requested.mxcsr|=extra; const auto actualMask=mask ? mask : 0xffbf; const bool shouldReject=(requested.mxcsr&~actualMask)!=0; bool rejected=false; int result=-99; try { result=set(&requested); } catch(const std::invalid_argument&) { rejected=true; } const auto after=readState(); writeState(original); const bool good=shouldReject ? rejected && after.x87==original.x87 && after.mxcsr==original.mxcsr : !rejected && result==0 && after.x87==requested.x87 && after.mxcsr==requested.mxcsr; if(!good) { std::printf("FAIL modelMask=%x input=%x expectedReject=%d actualReject=%d result=%d\n",mask,requested.mxcsr,shouldReject,rejected,result); ++failures; } ++cases; } } if(instruction) { std::memcpy(instruction,originalInstruction,2); FlushInstructionCache(GetCurrentProcess(),instruction,2); DWORD ignored; VirtualProtect(instruction,2,originalProtection,&ignored); } std::printf("Modelled FXSAVE masks:cases=%u failures=%u intercepted=%u; not an unsupported physical CPU measurement\n",cases,failures,injected); return failures ? 10 : 0; } ``` </details>
UnhealthyKraken commented 2026-10-21 07:14:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by UnhealthyKraken on 2026-10-21T07:14:42Z.


Fixed in 6e43cea19323048ab02875e7a43fa3729a048bed. The sentinel is now set after the first barrier and errno is captured immediately after fesetenv, before the second barrier. The assertion checks that captured value. No library implementation changed in this commit.

I reproduced the assertion flaw deterministically on Windows by compiling a temporary copy of the test with an errno write after each barrier. The old test fails at thread-local errno; the repaired test passes with the identical injected side effects. The normal Windows main test then passed 20 consecutive repetitions, followed by 10/10 native/loader cases and 357 libraries loaded. Final identical binaries against the original missing-export baseline still give 7 failures/2 math passes, then 9/9 on the candidate. Conventions and whitespace checks pass.

For a source-only reproducer, apply this transformation to a temporary copy of GuestSetEnv.cpp from each revision and compile it with the same includes, libc import library, Windows unwind/exit settings as the test target:

from pathlib import Path
source = Path("core/libs/tests/GuestSetEnv.cpp").read_text()
assert source.count("ready.arrive_and_wait();") == 2
source = source.replace(
    "ready.arrive_and_wait();",
    "ready.arrive_and_wait(); *__error_nid_postfix()=789;",
)
Path("temporary-GuestSetEnv.cpp").write_text(source)

Your Linux result is recorded as attributed review evidence; I have not run Linux here. A rerun on this head would verify that the reported flake is resolved on that host. The PR description now records this test correction and its validation; AI-assisted remains yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6310319374 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8937#issuecomment-6310319374). Originally posted by [UnhealthyKraken](https://github.com/UnhealthyKraken) on 2026-10-21T07:14:42Z. --- Fixed in `6e43cea19323048ab02875e7a43fa3729a048bed`. The sentinel is now set after the first barrier and errno is captured immediately after `fesetenv`, before the second barrier. The assertion checks that captured value. No library implementation changed in this commit. I reproduced the assertion flaw deterministically on Windows by compiling a temporary copy of the test with an errno write after each barrier. The old test fails at `thread-local errno`; the repaired test passes with the identical injected side effects. The normal Windows main test then passed 20 consecutive repetitions, followed by 10/10 native/loader cases and 357 libraries loaded. Final identical binaries against the original missing-export baseline still give 7 failures/2 math passes, then 9/9 on the candidate. Conventions and whitespace checks pass. For a source-only reproducer, apply this transformation to a temporary copy of `GuestSetEnv.cpp` from each revision and compile it with the same includes, libc import library, Windows unwind/exit settings as the test target: ```python from pathlib import Path source = Path("core/libs/tests/GuestSetEnv.cpp").read_text() assert source.count("ready.arrive_and_wait();") == 2 source = source.replace( "ready.arrive_and_wait();", "ready.arrive_and_wait(); *__error_nid_postfix()=789;", ) Path("temporary-GuestSetEnv.cpp").write_text(source) ``` Your Linux result is recorded as attributed review evidence; I have not run Linux here. A rerun on this head would verify that the reported flake is resolved on that host. The PR description now records this test correction and its validation; AI-assisted remains yes.
UnhealthyKraken commented 2026-10-21 07:34:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by UnhealthyKraken on 2026-10-21T07:34:32Z.


Thanks for the Linux verification and the test-fix commit. I had already applied the adjustment from your review in 6e43cea193 before seeing this fork commit; the assertion window is equivalent, with only the captured variable name differing.

I’ve recorded your 20 consecutive Linux runs and seven passing environment tests against your fork commit. Its parent is 05d3768, so that evidence covers the errno-test repair, while the later host-mask correction still has the separately documented Windows and modelled-mask validation. This preserves the source-head distinction and credits your contribution without claiming an own Linux run.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6310640402 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8937#issuecomment-6310640402). Originally posted by [UnhealthyKraken](https://github.com/UnhealthyKraken) on 2026-10-21T07:34:32Z. --- Thanks for the Linux verification and the [test-fix commit](https://github.com/MarcZX10/AnyPS5/commit/0c5da2c2f80102256c52ad0ba2d320dccd9de29e). I had already applied the adjustment from your review in `6e43cea193` before seeing this fork commit; the assertion window is equivalent, with only the captured variable name differing. I’ve recorded your 20 consecutive Linux runs and seven passing environment tests against your fork commit. Its parent is `05d3768`, so that evidence covers the errno-test repair, while the later host-mask correction still has the separately documented Windows and modelled-mask validation. This preserves the source-head distinction and credits your contribution without claiming an own Linux run.
MarcZX10 commented 2026-10-29 09:24:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T09:24:58Z.

Review: CHANGES_REQUESTED


Re-check — changes requested

The new commit test(libc): isolate fesetenv errno from synchronization appears to implement my earlier test-isolation suggestion: the errno sentinel is set after the first barrier and checked immediately after fesetenv, before the next barrier. The intervening synchronization no longer contaminates that assertion.

I checked the exact PR head d2386a7a78fca58ae72f0e2d4a1a8373c9e19750 and hosted status. Windows and the register-context jobs pass, but the Linux product-test job is skipped. The earlier Linux run failed guest_set_env twice in 20 repetitions, so the fix still needs an exact-head Linux run of guest_set_env repeated enough to show the race is gone. Please also refresh onto current main aaccd0ba39b7; this branch's target base is 10bec5c322eb.

I did not run the C++ test locally. I am not approving the previously flaky test until the focused Linux result is reported.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5695444201 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8937#pullrequestreview-5695444201). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-29T09:24:58Z. **Review:** CHANGES_REQUESTED --- # Re-check — changes requested The new commit `test(libc): isolate fesetenv errno from synchronization` appears to implement my earlier test-isolation suggestion: the errno sentinel is set after the first barrier and checked immediately after `fesetenv`, before the next barrier. The intervening synchronization no longer contaminates that assertion. I checked the exact PR head `d2386a7a78fca58ae72f0e2d4a1a8373c9e19750` and hosted status. Windows and the register-context jobs pass, but the Linux product-test job is skipped. The earlier Linux run failed `guest_set_env` twice in 20 repetitions, so the fix still needs an exact-head Linux run of `guest_set_env` repeated enough to show the race is gone. Please also refresh onto current main `aaccd0ba39b7`; this branch's target base is `10bec5c322eb`. I did not run the C++ test locally. I am not approving the previously flaky test until the focused Linux result is reported.
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!8937
No description provided.