startup: refuse unmapped source ranges before a probe or a copy #2838

Merged
tedin7 merged 6 commits from upstream-pr/2846 into main 2026-11-27 23:24:38 +00:00
tedin7 commented 2026-11-26 13:21:13 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T13:21:13Z.


Part of #870

Fixes #2845

What this unblocks: the startup runtime stops raising a first-chance access violation for every read of unmapped title memory, so a debugger attached to a run no longer stops on each of them.

Change

  • src/startup_stubs/local_log.h: new mapped_prefix() asks VirtualQuery first (a small per-thread cache of mapped spans) and refuses only MEM_FREE ranges. Reserved but uncommitted pages stay accessible because the lazy-commit memory relies on first-touch faults. probe_readable() touches only the mapped prefix. New guarded_memcpy() runs the pre-check, then the existing __try copy as the last guard (a fault drops the cached spans). New faults_avoided counter.
  • src/startup_stubs/linear_buffer_backing.h, src/startup_stubs/d3d12_draw.inl: guarded_copy and copy_title_bytes call guarded_memcpy.
  • src/startup_stubs/d3d12_xs_device.cpp: the render totals line gains reads refused before a fault N (inserted before the line's end, which tests/startup_compute_request_check.py pins).
  • docs/startup-runtime.md: describes the pre-check.

Tests

startup_local_log (existing C++ check) gains test_unmapped_no_faults: it releases its own address range, requires it to be MEM_FREE before and after the calls, and requires zero first-chance exceptions on the checking thread from probe_readable, readable and both copy flavours, four counted refusals per round, and a control touch of a free range that is exactly one first-chance fault. A mapped source still copies and counts nothing. A round that lost its range to another thread is dropped; ten stable rounds are required, so the check does not depend on other threads in the process.

Verification

Linux (Stage 1; the check uses MSVC __try, so it compiles on Windows only): git diff --check clean, mingw -fsyntax-only shows no errors other than the SEH keywords.

Win2025 WARP (Windows Server 2025 build 26100, MSVC 14.44), the same change applied as a patch on a build base, five runs at once, dev and release:

python3 x2w_pipe.py win2025 <PR> --host proxmox --patch <diff> --regex '^startup_local_log' --targets startup_local_log_check,startup_local_log_cache_failure_check --keep-release --force

Result: ^startup_local_log 5/5 passed in dev and 5/5 in release, in all five runs. Control: with the pre-check disabled (mapped_prefix always reports mapped) startup_local_log fails on "zero first-chance exceptions in every judged round".

Gate on this PR's own head 3b259bd78 (independent worker, head fetched from the PR, no patch): Win2025 dev 10/10 and release 10/10 for ^(startup_local_log|startup_compute_request|startup_shader_cache). Mutant (patch drops the MEM_FREE refusal): startup_local_log fails ("zero first-chance exceptions", "four refusals counted"). Receipt on this PR.

Real-hardware testing: @Makto94 - thanks for the help.

Source: Microsoft documentation, VirtualQuery and Structured Exception Handling.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:5510794230 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-26T13:21:13Z. --- Part of #870 Fixes #2845 What this unblocks: the startup runtime stops raising a first-chance access violation for every read of unmapped title memory, so a debugger attached to a run no longer stops on each of them. ## Change - `src/startup_stubs/local_log.h`: new `mapped_prefix()` asks `VirtualQuery` first (a small per-thread cache of mapped spans) and refuses only `MEM_FREE` ranges. Reserved but uncommitted pages stay accessible because the lazy-commit memory relies on first-touch faults. `probe_readable()` touches only the mapped prefix. New `guarded_memcpy()` runs the pre-check, then the existing `__try` copy as the last guard (a fault drops the cached spans). New `faults_avoided` counter. - `src/startup_stubs/linear_buffer_backing.h`, `src/startup_stubs/d3d12_draw.inl`: `guarded_copy` and `copy_title_bytes` call `guarded_memcpy`. - `src/startup_stubs/d3d12_xs_device.cpp`: the render totals line gains `reads refused before a fault N` (inserted before the line's end, which `tests/startup_compute_request_check.py` pins). - `docs/startup-runtime.md`: describes the pre-check. ## Tests `startup_local_log` (existing C++ check) gains `test_unmapped_no_faults`: it releases its own address range, requires it to be `MEM_FREE` before and after the calls, and requires zero first-chance exceptions on the checking thread from `probe_readable`, `readable` and both copy flavours, four counted refusals per round, and a control touch of a free range that is exactly one first-chance fault. A mapped source still copies and counts nothing. A round that lost its range to another thread is dropped; ten stable rounds are required, so the check does not depend on other threads in the process. ## Verification Linux (Stage 1; the check uses MSVC `__try`, so it compiles on Windows only): `git diff --check` clean, mingw `-fsyntax-only` shows no errors other than the SEH keywords. Win2025 WARP (Windows Server 2025 build 26100, MSVC 14.44), the same change applied as a patch on a build base, five runs at once, dev and release: ``` python3 x2w_pipe.py win2025 <PR> --host proxmox --patch <diff> --regex '^startup_local_log' --targets startup_local_log_check,startup_local_log_cache_failure_check --keep-release --force ``` Result: `^startup_local_log` 5/5 passed in dev and 5/5 in release, in all five runs. Control: with the pre-check disabled (`mapped_prefix` always reports mapped) `startup_local_log` fails on "zero first-chance exceptions in every judged round". Gate on this PR's own head 3b259bd78 (independent worker, head fetched from the PR, no patch): Win2025 dev 10/10 and release 10/10 for `^(startup_local_log|startup_compute_request|startup_shader_cache)`. Mutant (patch drops the MEM_FREE refusal): `startup_local_log` fails ("zero first-chance exceptions", "four refusals counted"). Receipt on this PR. Real-hardware testing: @Makto94 - thanks for the help. Source: Microsoft documentation, [VirtualQuery](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualquery) and [Structured Exception Handling](https://learn.microsoft.com/en-us/windows/win32/debug/structured-exception-handling). AI-assisted; commands listed were executed locally.
chatgpt-codex-connector[bot] commented 2026-11-26 14:20:14 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-26T14:20:14Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3b259bd786

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6075701506 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#pullrequestreview-6075701506). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/apps/chatgpt-codex-connector) on 2026-11-26T14:20:14Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `3b259bd786` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
tedin7 commented 2026-11-26 15:00:48 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T14:31:16Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6075865011 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#pullrequestreview-6075865011). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-26T14:31:16Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-26 15:00:49 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T14:31:19Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6075865718 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#pullrequestreview-6075865718). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-26T14:31:19Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-26 15:00:59 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T14:11:09Z.


Independent review of head 3b259bd786: PASS.

Verification:

  • Windows Server 2025 (D3D12 WARP), the PR head fetched as it is (no patch), ctest -R '^(startup_local_log|startup_compute_request|startup_shader_cache)': dev 10/10 and release 10/10.
  • Control: with the MEM_FREE refusal in mapped_prefix removed (patch applied on the same head), startup_local_log fails in dev with "zero first-chance exceptions in every judged round" and "the four refusals of every judged round are counted".
  • Diff read in full: copy_title_bytes still catches every exception, guarded_copy still catches only access violations and in-page errors; an overflowing range or a failed VirtualQuery falls back to the old touch/__try path; reserved pages are not refused, so lazy-commit first touch keeps working.

Not blocking: the per-thread cache holds 16 spans with round-robin replacement, so a thread that alternates over more than 16 regions pays one VirtualQuery per switch (about 1 ms on the title's multi-gigabyte regions, per the code comment). Worth watching the probe cost after the next tester run.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7194396596 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#issuecomment-7194396596). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-26T14:11:09Z. --- Independent review of head 3b259bd786f86253c761352edcec659312f9373c: PASS. Verification: - Windows Server 2025 (D3D12 WARP), the PR head fetched as it is (no patch), `ctest -R '^(startup_local_log|startup_compute_request|startup_shader_cache)'`: dev 10/10 and release 10/10. - Control: with the `MEM_FREE` refusal in `mapped_prefix` removed (patch applied on the same head), `startup_local_log` fails in dev with "zero first-chance exceptions in every judged round" and "the four refusals of every judged round are counted". - Diff read in full: `copy_title_bytes` still catches every exception, `guarded_copy` still catches only access violations and in-page errors; an overflowing range or a failed `VirtualQuery` falls back to the old touch/`__try` path; reserved pages are not refused, so lazy-commit first touch keeps working. Not blocking: the per-thread cache holds 16 spans with round-robin replacement, so a thread that alternates over more than 16 regions pays one `VirtualQuery` per switch (about 1 ms on the title's multi-gigabyte regions, per the code comment). Worth watching the probe cost after the next tester run. AI-assisted; commands listed were executed locally.
chatgpt-codex-connector[bot commented 2026-11-26 15:00:59 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-26T14:12:34Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T14:20:16.850322Z 3b259bd Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7194430196 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#issuecomment-7194430196). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-26T14:12:34Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"3b259bd786f86253c761352edcec659312f9373c","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-26T14:20:16.850322Z">2026-11-26T14:20:16.850322Z</relative-time> | `3b259bd` | Draft marked ready | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
tedin7 commented 2026-11-26 15:00:59 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T14:31:10Z.


Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit f85b47bfa92b51a566ecc3c4500a7591a5665822:

  • Debug (--preset dev):
    • Build (cmake --build --preset dev --target startup_local_log_check -- -j 2): 1.50s (configure 2.46s)
    • Test (ctest --preset dev -R '^startup_local_log' --parallel 2 --no-tests=error --output-on-failure): 5/5 passed (6.22s: startup_local_log_cache_failure_control 3.01s, startup_local_log_guard_drop_control 3.04s, startup_local_log_reopen_control 2.12s, startup_local_log_wrap_control 0.01s, startup_local_log 3.05s)
  • Release /O2 (--preset release):
    • Build (cmake --build --preset release --target startup_local_log_check -- -j 2): 6.23s (configure 2.26s)
    • Test (ctest --preset release -R '^startup_local_log' --parallel 2 --no-tests=error --output-on-failure): 5/5 passed (6.04s: startup_local_log 2.93s, startup_local_log_guard_drop_control 2.94s, startup_local_log_reopen_control 2.25s, startup_local_log_wrap_control 0.02s, startup_local_log_cache_failure_control 2.95s)
  • sccache: 9/13 hits; wall 29.4s
    tested: f85b47bf via fetch (pull/2846/head, no patch)

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7194936090 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#issuecomment-7194936090). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-26T14:31:10Z. --- Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit `f85b47bfa92b51a566ecc3c4500a7591a5665822`: - **Debug (`--preset dev`)**: - Build (`cmake --build --preset dev --target startup_local_log_check -- -j 2`): `1.50s` (configure `2.46s`) - Test (`ctest --preset dev -R '^startup_local_log' --parallel 2 --no-tests=error --output-on-failure`): **5/5 passed** (`6.22s`: `startup_local_log_cache_failure_control` `3.01s`, `startup_local_log_guard_drop_control` `3.04s`, `startup_local_log_reopen_control` `2.12s`, `startup_local_log_wrap_control` `0.01s`, `startup_local_log` `3.05s`) - **Release `/O2` (`--preset release`)**: - Build (`cmake --build --preset release --target startup_local_log_check -- -j 2`): `6.23s` (configure `2.26s`) - Test (`ctest --preset release -R '^startup_local_log' --parallel 2 --no-tests=error --output-on-failure`): **5/5 passed** (`6.04s`: `startup_local_log` `2.93s`, `startup_local_log_guard_drop_control` `2.94s`, `startup_local_log_reopen_control` `2.25s`, `startup_local_log_wrap_control` `0.02s`, `startup_local_log_cache_failure_control` `2.95s`) - `sccache`: 9/13 hits; wall `29.4s` tested: f85b47bf via fetch (pull/2846/head, no patch) AI-assisted; commands listed were executed locally.
chatgpt-codex-connector[bot commented 2026-11-26 15:01:01 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-26T14:20:14Z.

Code review location: src/startup_stubs/local_log.h; line 116

@@ -61,7 +111,11 @@ inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexc
     std::size_t done = 0;
     DWORD code = 0;
     std::uintptr_t at = start;
-    const std::uintptr_t end = start + bytes;
+    // Free address space is refused without touching it; the touch below only sees mapped pages.
+    const std::size_t mapped = mapped_prefix(start, bytes);
+    if (mapped < bytes) InterlockedIncrement(&faults_avoided);

P2 Badge Count an avoided fault only after probing the mapped prefix

When a requested range contains a PAGE_NOACCESS page before a MEM_FREE tail, mapped_prefix() returns a short prefix and this increments faults_avoided, but the subsequent touch loop still faults on the earlier page and exits before reaching the free range. The previous implementation raises the same exception in this case, so repeated reads increase the heartbeat's avoided-fault total without avoiding any exceptions. For nonzero mapped prefixes, defer the increment until the probe successfully traverses the prefix; retain the immediate count when mapped == 0.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4709644198 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#discussion_r4709644198). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-26T14:20:14Z. **Code review location:** `src/startup_stubs/local_log.h`; line 116 ~~~~diff @@ -61,7 +111,11 @@ inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexc std::size_t done = 0; DWORD code = 0; std::uintptr_t at = start; - const std::uintptr_t end = start + bytes; + // Free address space is refused without touching it; the touch below only sees mapped pages. + const std::size_t mapped = mapped_prefix(start, bytes); + if (mapped < bytes) InterlockedIncrement(&faults_avoided); ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Count an avoided fault only after probing the mapped prefix** When a requested range contains a `PAGE_NOACCESS` page before a `MEM_FREE` tail, `mapped_prefix()` returns a short prefix and this increments `faults_avoided`, but the subsequent touch loop still faults on the earlier page and exits before reaching the free range. The previous implementation raises the same exception in this case, so repeated reads increase the heartbeat's avoided-fault total without avoiding any exceptions. For nonzero mapped prefixes, defer the increment until the probe successfully traverses the prefix; retain the immediate count when `mapped == 0`. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-26 15:01:01 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-26T14:20:14Z.

Code review location: tests/startup_local_log_check.cpp; line 658

@@ -585,6 +586,106 @@ void test_probe_and_access(bool guard_drop_mutate)
     }
 }
 
+// Exceptions seen by a vectored handler, for the thread that runs the check only: a debugger stops on every
+// first-chance fault, and faults of other threads in the process do not belong to it.
+volatile LONG first_chance_faults = 0;
+volatile LONG counted_thread = 0;
+LONG CALLBACK count_first_chance(PEXCEPTION_POINTERS info)
+{
+    const DWORD code = info->ExceptionRecord->ExceptionCode;
+    if (GetCurrentThreadId() == static_cast<DWORD>(counted_thread) &&
+        (code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_IN_PAGE_ERROR || code == 0x80000001u))
+        InterlockedIncrement(&first_chance_faults);
+    return EXCEPTION_CONTINUE_SEARCH;
+}
+
+bool range_is_free(std::uintptr_t base, std::size_t bytes)
+{
+    MEMORY_BASIC_INFORMATION info{};
+    return VirtualQuery(reinterpret_cast<const void*>(base), &info, sizeof(info)) && info.State == MEM_FREE &&
+           info.RegionSize >= bytes;
+}
+
+// Free address space is refused with zero first-chance exceptions by the probe, readable() and both copy flavours,
+// each counted in faults_avoided; a mapped source still copies and counts nothing.
+//
+// The range is one this check released itself. Nothing else can be trusted to leave it free (another thread, or
+// this thread's own heap, may reuse it the moment it is released), so each round is only judged when the range is
+// verified MEM_FREE right before and right after the calls, the handler is installed beforehand and the calls
+// in between allocate nothing. A round that lost its range is dropped, not counted; the check needs enough stable
+// rounds and holds every stable one to zero faults.
+void test_unmapped_no_faults()
+{
+    constexpr std::size_t kPage = 0x1000;
+    constexpr int rounds = 40, needed = 10;
+    char copy[64] = {};
+    {
+        void* const mapped = VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
+        check(mapped != nullptr, "VirtualAlloc a page for the mapped-source check");
+        if (!mapped) return;
+        std::memset(mapped, 0x5A, kPage);
+        x2w_local::forget_mapped_spans();
+        const LONG before = x2w_local::faults_avoided;
+        const bool copied = x2w_local::guarded_memcpy(copy, mapped, sizeof(copy), false);
+        check(copied && copy[0] == 0x5A, "a mapped source is copied");
+        check(x2w_local::faults_avoided == before, "a mapped source avoids no fault");
+        VirtualFree(mapped, 0, MEM_RELEASE);
+    }
+    counted_thread = static_cast<LONG>(GetCurrentThreadId());
+    void* const handler = AddVectoredExceptionHandler(1, count_first_chance);
+    check(handler != nullptr, "vectored handler installed");
+    int stable = 0, wrong_results = 0, faulted = 0, miscounted = 0, control_faults = 0, controls = 0;
+    for (int round = 0; round < rounds && stable < needed; ++round) {
+        void* const block = VirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
+        if (!block) continue;
+        const auto base = reinterpret_cast<std::uintptr_t>(block);
+        VirtualFree(block, 0, MEM_RELEASE);
+        x2w_local::forget_mapped_spans();
+        if (!range_is_free(base, 2 * kPage)) continue;
+        InterlockedExchange(&first_chance_faults, 0);
+        const LONG before = x2w_local::faults_avoided;
+        const bool probe_zero = x2w_local::probe_readable(base, 16) == 0;
+        const bool not_readable = !x2w_local::readable(reinterpret_cast<const void*>(base), 16);
+        const bool refused_av = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), false);
+        const bool refused_any = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), true);
+        const LONG faults = first_chance_faults;
+        const LONG counted = x2w_local::faults_avoided - before;
+        if (!range_is_free(base, 2 * kPage)) continue;  // the range was taken meanwhile: this round proves nothing
+        ++stable;
+        if (!(probe_zero && not_readable && refused_av && refused_any)) ++wrong_results;
+        if (faults != 0) ++faulted;
+        if (counted != 4) ++miscounted;
+        if (stable == 1) {

P2 Badge Retry a discarded control round

If another thread reuses the control allocation and either range_is_free() check rejects it, controls remains zero, but the control is never attempted again because subsequent judged rounds increment stable beyond one. Consequently, even ten successful probe rounds end in a failed controls == 1 assertion under the address-space churn that the surrounding retry logic is intended to tolerate. Retry the control until one stable control round has been observed, rather than restricting it to the first stable probe round.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4709644204 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#discussion_r4709644204). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-26T14:20:14Z. **Code review location:** `tests/startup_local_log_check.cpp`; line 658 ~~~~diff @@ -585,6 +586,106 @@ void test_probe_and_access(bool guard_drop_mutate) } } +// Exceptions seen by a vectored handler, for the thread that runs the check only: a debugger stops on every +// first-chance fault, and faults of other threads in the process do not belong to it. +volatile LONG first_chance_faults = 0; +volatile LONG counted_thread = 0; +LONG CALLBACK count_first_chance(PEXCEPTION_POINTERS info) +{ + const DWORD code = info->ExceptionRecord->ExceptionCode; + if (GetCurrentThreadId() == static_cast<DWORD>(counted_thread) && + (code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_IN_PAGE_ERROR || code == 0x80000001u)) + InterlockedIncrement(&first_chance_faults); + return EXCEPTION_CONTINUE_SEARCH; +} + +bool range_is_free(std::uintptr_t base, std::size_t bytes) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(reinterpret_cast<const void*>(base), &info, sizeof(info)) && info.State == MEM_FREE && + info.RegionSize >= bytes; +} + +// Free address space is refused with zero first-chance exceptions by the probe, readable() and both copy flavours, +// each counted in faults_avoided; a mapped source still copies and counts nothing. +// +// The range is one this check released itself. Nothing else can be trusted to leave it free (another thread, or +// this thread's own heap, may reuse it the moment it is released), so each round is only judged when the range is +// verified MEM_FREE right before and right after the calls, the handler is installed beforehand and the calls +// in between allocate nothing. A round that lost its range is dropped, not counted; the check needs enough stable +// rounds and holds every stable one to zero faults. +void test_unmapped_no_faults() +{ + constexpr std::size_t kPage = 0x1000; + constexpr int rounds = 40, needed = 10; + char copy[64] = {}; + { + void* const mapped = VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + check(mapped != nullptr, "VirtualAlloc a page for the mapped-source check"); + if (!mapped) return; + std::memset(mapped, 0x5A, kPage); + x2w_local::forget_mapped_spans(); + const LONG before = x2w_local::faults_avoided; + const bool copied = x2w_local::guarded_memcpy(copy, mapped, sizeof(copy), false); + check(copied && copy[0] == 0x5A, "a mapped source is copied"); + check(x2w_local::faults_avoided == before, "a mapped source avoids no fault"); + VirtualFree(mapped, 0, MEM_RELEASE); + } + counted_thread = static_cast<LONG>(GetCurrentThreadId()); + void* const handler = AddVectoredExceptionHandler(1, count_first_chance); + check(handler != nullptr, "vectored handler installed"); + int stable = 0, wrong_results = 0, faulted = 0, miscounted = 0, control_faults = 0, controls = 0; + for (int round = 0; round < rounds && stable < needed; ++round) { + void* const block = VirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!block) continue; + const auto base = reinterpret_cast<std::uintptr_t>(block); + VirtualFree(block, 0, MEM_RELEASE); + x2w_local::forget_mapped_spans(); + if (!range_is_free(base, 2 * kPage)) continue; + InterlockedExchange(&first_chance_faults, 0); + const LONG before = x2w_local::faults_avoided; + const bool probe_zero = x2w_local::probe_readable(base, 16) == 0; + const bool not_readable = !x2w_local::readable(reinterpret_cast<const void*>(base), 16); + const bool refused_av = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), false); + const bool refused_any = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), true); + const LONG faults = first_chance_faults; + const LONG counted = x2w_local::faults_avoided - before; + if (!range_is_free(base, 2 * kPage)) continue; // the range was taken meanwhile: this round proves nothing + ++stable; + if (!(probe_zero && not_readable && refused_av && refused_any)) ++wrong_results; + if (faults != 0) ++faulted; + if (counted != 4) ++miscounted; + if (stable == 1) { ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Retry a discarded control round** If another thread reuses the control allocation and either `range_is_free()` check rejects it, `controls` remains zero, but the control is never attempted again because subsequent judged rounds increment `stable` beyond one. Consequently, even ten successful probe rounds end in a failed `controls == 1` assertion under the address-space churn that the surrounding retry logic is intended to tolerate. Retry the control until one stable control round has been observed, rather than restricting it to the first stable probe round. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-26 15:01:01 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T14:31:16Z.

Code review location: src/startup_stubs/local_log.h; line 116

@@ -61,7 +111,11 @@ inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexc
     std::size_t done = 0;
     DWORD code = 0;
     std::uintptr_t at = start;
-    const std::uintptr_t end = start + bytes;
+    // Free address space is refused without touching it; the touch below only sees mapped pages.
+    const std::size_t mapped = mapped_prefix(start, bytes);
+    if (mapped < bytes) InterlockedIncrement(&faults_avoided);

Fixed in f85b47bf: the avoided-fault count for a free tail is now added only after the mapped prefix was walked without a fault (immediate when the prefix is 0). New test test_protected_prefix_not_counted in startup_local_log_check covers a PAGE_NOACCESS page before a free tail. Win2025 dev+release ^startup_local_log 5/5.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4709778917 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#discussion_r4709778917). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-26T14:31:16Z. **Code review location:** `src/startup_stubs/local_log.h`; line 116 ~~~~diff @@ -61,7 +111,11 @@ inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexc std::size_t done = 0; DWORD code = 0; std::uintptr_t at = start; - const std::uintptr_t end = start + bytes; + // Free address space is refused without touching it; the touch below only sees mapped pages. + const std::size_t mapped = mapped_prefix(start, bytes); + if (mapped < bytes) InterlockedIncrement(&faults_avoided); ~~~~ --- Fixed in f85b47bf: the avoided-fault count for a free tail is now added only after the mapped prefix was walked without a fault (immediate when the prefix is 0). New test `test_protected_prefix_not_counted` in `startup_local_log_check` covers a PAGE_NOACCESS page before a free tail. Win2025 dev+release `^startup_local_log` 5/5. AI-assisted; commands listed were executed locally.
tedin7 commented 2026-11-26 15:01:01 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-26T14:31:19Z.

Code review location: tests/startup_local_log_check.cpp; line 658

@@ -585,6 +586,106 @@ void test_probe_and_access(bool guard_drop_mutate)
     }
 }
 
+// Exceptions seen by a vectored handler, for the thread that runs the check only: a debugger stops on every
+// first-chance fault, and faults of other threads in the process do not belong to it.
+volatile LONG first_chance_faults = 0;
+volatile LONG counted_thread = 0;
+LONG CALLBACK count_first_chance(PEXCEPTION_POINTERS info)
+{
+    const DWORD code = info->ExceptionRecord->ExceptionCode;
+    if (GetCurrentThreadId() == static_cast<DWORD>(counted_thread) &&
+        (code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_IN_PAGE_ERROR || code == 0x80000001u))
+        InterlockedIncrement(&first_chance_faults);
+    return EXCEPTION_CONTINUE_SEARCH;
+}
+
+bool range_is_free(std::uintptr_t base, std::size_t bytes)
+{
+    MEMORY_BASIC_INFORMATION info{};
+    return VirtualQuery(reinterpret_cast<const void*>(base), &info, sizeof(info)) && info.State == MEM_FREE &&
+           info.RegionSize >= bytes;
+}
+
+// Free address space is refused with zero first-chance exceptions by the probe, readable() and both copy flavours,
+// each counted in faults_avoided; a mapped source still copies and counts nothing.
+//
+// The range is one this check released itself. Nothing else can be trusted to leave it free (another thread, or
+// this thread's own heap, may reuse it the moment it is released), so each round is only judged when the range is
+// verified MEM_FREE right before and right after the calls, the handler is installed beforehand and the calls
+// in between allocate nothing. A round that lost its range is dropped, not counted; the check needs enough stable
+// rounds and holds every stable one to zero faults.
+void test_unmapped_no_faults()
+{
+    constexpr std::size_t kPage = 0x1000;
+    constexpr int rounds = 40, needed = 10;
+    char copy[64] = {};
+    {
+        void* const mapped = VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
+        check(mapped != nullptr, "VirtualAlloc a page for the mapped-source check");
+        if (!mapped) return;
+        std::memset(mapped, 0x5A, kPage);
+        x2w_local::forget_mapped_spans();
+        const LONG before = x2w_local::faults_avoided;
+        const bool copied = x2w_local::guarded_memcpy(copy, mapped, sizeof(copy), false);
+        check(copied && copy[0] == 0x5A, "a mapped source is copied");
+        check(x2w_local::faults_avoided == before, "a mapped source avoids no fault");
+        VirtualFree(mapped, 0, MEM_RELEASE);
+    }
+    counted_thread = static_cast<LONG>(GetCurrentThreadId());
+    void* const handler = AddVectoredExceptionHandler(1, count_first_chance);
+    check(handler != nullptr, "vectored handler installed");
+    int stable = 0, wrong_results = 0, faulted = 0, miscounted = 0, control_faults = 0, controls = 0;
+    for (int round = 0; round < rounds && stable < needed; ++round) {
+        void* const block = VirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
+        if (!block) continue;
+        const auto base = reinterpret_cast<std::uintptr_t>(block);
+        VirtualFree(block, 0, MEM_RELEASE);
+        x2w_local::forget_mapped_spans();
+        if (!range_is_free(base, 2 * kPage)) continue;
+        InterlockedExchange(&first_chance_faults, 0);
+        const LONG before = x2w_local::faults_avoided;
+        const bool probe_zero = x2w_local::probe_readable(base, 16) == 0;
+        const bool not_readable = !x2w_local::readable(reinterpret_cast<const void*>(base), 16);
+        const bool refused_av = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), false);
+        const bool refused_any = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), true);
+        const LONG faults = first_chance_faults;
+        const LONG counted = x2w_local::faults_avoided - before;
+        if (!range_is_free(base, 2 * kPage)) continue;  // the range was taken meanwhile: this round proves nothing
+        ++stable;
+        if (!(probe_zero && not_readable && refused_av && refused_any)) ++wrong_results;
+        if (faults != 0) ++faulted;
+        if (counted != 4) ++miscounted;
+        if (stable == 1) {

Fixed in f85b47bf: the control now retries until one control round survives (controls == 0 instead of stable == 1). Win2025 dev+release ^startup_local_log 5/5.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4709779467 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#discussion_r4709779467). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-26T14:31:19Z. **Code review location:** `tests/startup_local_log_check.cpp`; line 658 ~~~~diff @@ -585,6 +586,106 @@ void test_probe_and_access(bool guard_drop_mutate) } } +// Exceptions seen by a vectored handler, for the thread that runs the check only: a debugger stops on every +// first-chance fault, and faults of other threads in the process do not belong to it. +volatile LONG first_chance_faults = 0; +volatile LONG counted_thread = 0; +LONG CALLBACK count_first_chance(PEXCEPTION_POINTERS info) +{ + const DWORD code = info->ExceptionRecord->ExceptionCode; + if (GetCurrentThreadId() == static_cast<DWORD>(counted_thread) && + (code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_IN_PAGE_ERROR || code == 0x80000001u)) + InterlockedIncrement(&first_chance_faults); + return EXCEPTION_CONTINUE_SEARCH; +} + +bool range_is_free(std::uintptr_t base, std::size_t bytes) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(reinterpret_cast<const void*>(base), &info, sizeof(info)) && info.State == MEM_FREE && + info.RegionSize >= bytes; +} + +// Free address space is refused with zero first-chance exceptions by the probe, readable() and both copy flavours, +// each counted in faults_avoided; a mapped source still copies and counts nothing. +// +// The range is one this check released itself. Nothing else can be trusted to leave it free (another thread, or +// this thread's own heap, may reuse it the moment it is released), so each round is only judged when the range is +// verified MEM_FREE right before and right after the calls, the handler is installed beforehand and the calls +// in between allocate nothing. A round that lost its range is dropped, not counted; the check needs enough stable +// rounds and holds every stable one to zero faults. +void test_unmapped_no_faults() +{ + constexpr std::size_t kPage = 0x1000; + constexpr int rounds = 40, needed = 10; + char copy[64] = {}; + { + void* const mapped = VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + check(mapped != nullptr, "VirtualAlloc a page for the mapped-source check"); + if (!mapped) return; + std::memset(mapped, 0x5A, kPage); + x2w_local::forget_mapped_spans(); + const LONG before = x2w_local::faults_avoided; + const bool copied = x2w_local::guarded_memcpy(copy, mapped, sizeof(copy), false); + check(copied && copy[0] == 0x5A, "a mapped source is copied"); + check(x2w_local::faults_avoided == before, "a mapped source avoids no fault"); + VirtualFree(mapped, 0, MEM_RELEASE); + } + counted_thread = static_cast<LONG>(GetCurrentThreadId()); + void* const handler = AddVectoredExceptionHandler(1, count_first_chance); + check(handler != nullptr, "vectored handler installed"); + int stable = 0, wrong_results = 0, faulted = 0, miscounted = 0, control_faults = 0, controls = 0; + for (int round = 0; round < rounds && stable < needed; ++round) { + void* const block = VirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!block) continue; + const auto base = reinterpret_cast<std::uintptr_t>(block); + VirtualFree(block, 0, MEM_RELEASE); + x2w_local::forget_mapped_spans(); + if (!range_is_free(base, 2 * kPage)) continue; + InterlockedExchange(&first_chance_faults, 0); + const LONG before = x2w_local::faults_avoided; + const bool probe_zero = x2w_local::probe_readable(base, 16) == 0; + const bool not_readable = !x2w_local::readable(reinterpret_cast<const void*>(base), 16); + const bool refused_av = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), false); + const bool refused_any = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), true); + const LONG faults = first_chance_faults; + const LONG counted = x2w_local::faults_avoided - before; + if (!range_is_free(base, 2 * kPage)) continue; // the range was taken meanwhile: this round proves nothing + ++stable; + if (!(probe_zero && not_readable && refused_av && refused_any)) ++wrong_results; + if (faults != 0) ++faulted; + if (counted != 4) ++miscounted; + if (stable == 1) { ~~~~ --- Fixed in f85b47bf: the control now retries until one control round survives (`controls == 0` instead of `stable == 1`). Win2025 dev+release `^startup_local_log` 5/5. AI-assisted; commands listed were executed locally.
pigalot commented 2026-11-27 19:44:33 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by pigalot on 2026-11-27T19:44:33Z.

Review: COMMENTED


Independently reviewed f85b47bf integrated over main 0f3e8248 (tree b139609a, clean merge).

What I traced. mapped_prefix refuses only MEM_FREE, and only from a fresh VirtualQuery. The per-thread cache holds only regions that are not free. So a stale entry can only send a range back to the old touch / __try path; it can never refuse a mapped range. copy_title_bytes keeps its catch-all filter (any_exception true), and guarded_copy keeps its AV / in-page filter. Both Codex threads are resolved, and the changes in f85b47bf do what the replies say.

What I ran. I built startup_local_log_check, startup_local_log_cache_failure_check and d3d12_xs_shim in dev and release, then ran:
ctest --test-dir out/build/<preset> --no-tests=error -j 1 -R '^startup_local_log.*$'
5/5 passed in Debug and Release /O2, including the four controls.

Mutant. Dropping the up-front refusal in guarded_memcpy (if (false)) fails startup_local_log with two checks:

  • FAIL free address space: zero first-chance exceptions in every judged round
  • FAIL free address space: the four refusals of every judged round are counted

Restored, it passes. git diff --check is clean.

Cost measurement. This puts a VirtualQuery in front of every probe and guarded copy, with no debugger attached as well. The file's own comment above probe_readable says the probe avoided VirtualQuery for cost. So I timed probe_readable with main's local_log.h against this PR's, in a small standalone program on synthetic memory only (cl /O2, two runs each, consistent):

case main PR
4 MiB probe across 64 regions of alternating protection 7.8–8.1 µs 32.0 µs
4 KiB probe, round-robin over 32 separate 1 MiB allocations (more than the 16-entry cache) 2 ns 1.27 µs
64 KiB probe inside one 2 GiB committed region 11.6 µs 11.6 µs
repeated 4 KiB probe of one region 1 ns 3 ns

So:

  • a range made of many regions costs about 4× as much;
  • callers that cycle over more than 16 regions per thread pay one query per probe;
  • single-region and cached cases stay cheap.

I couldn't measure how often the runtime hits the first two patterns. Mapped-page runs and texture uploads are the likely candidates, but that is a hypothesis.

Benchmark source and commands

main header: git show origin/main:src/startup_stubs/local_log.h > main/startup_stubs/local_log.h, then
cl /nologo /std:c++20 /O2 /EHsc /I main /I src bench.cpp /Fe:bench_main.exe and the same without /I main for the PR.

// #2846 micro-benchmark: probe_readable cost, main header vs PR header (synthetic memory only).
#include <windows.h>
#include "startup_stubs/local_log.h"
#include <chrono>
#include <cstdio>
#include <cstdint>

static double per_call_ns(int iters, auto&& fn)
{
    const auto t0 = std::chrono::steady_clock::now();
    std::size_t sink = 0;
    for (int i = 0; i < iters; ++i) sink += fn(i);
    const auto t1 = std::chrono::steady_clock::now();
    if (sink == 1) std::printf(" ");
    return std::chrono::duration<double, std::nano>(t1 - t0).count() / iters;
}

int main()
{
    constexpr std::size_t block = 64 << 10;
    // A: 1024 regions of 64 KiB with alternating protection (all readable), probed in 4 MiB windows.
    auto* a = static_cast<unsigned char*>(VirtualAlloc(nullptr, 1024 * block, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
    for (std::size_t i = 0; i < 1024; ++i) { a[i * block] = 1; DWORD old; if (i & 1) VirtualProtect(a + i * block, block, PAGE_READONLY, &old); }
    const double na = per_call_ns(2000, [&](int i) { return x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(a + (i % 960) * block), 64 * block); });
    // B: one 2 GiB committed private region (untouched except probed pages), 64 KiB probes at spread offsets.
    const std::size_t big = std::size_t{2} << 30;
    auto* b = static_cast<unsigned char*>(VirtualAlloc(nullptr, big, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
    const double nb = per_call_ns(2000, [&](int i) { return x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(b + (std::size_t(i) * 7919 % 32768) * block), block); });
    // C: 32 separate 1 MiB allocations probed round-robin (more regions than the 16-entry cache).
    unsigned char* c[32];
    for (auto& p : c) { p = static_cast<unsigned char*>(VirtualAlloc(nullptr, 1 << 20, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); p[0] = 1; }
    const double nc = per_call_ns(20000, [&](int i) { return x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(c[i % 32]), 4096); });
    // D: the same 4 KiB probe of one region, repeated (cache hit on the PR side).
    static unsigned char dst[4096];
    const double nd = per_call_ns(20000, [&](int i) { return x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(c[0]), 4096) + dst[0]; });
    std::printf("A 1024-region 4MiB probe: %.0f ns\nB 2GiB-region 64KiB probe: %.0f ns\nC 32 allocs round-robin 4KiB probe: %.0f ns\nD same 4KiB probe: %.0f ns\n", na, nb, nc, nd);
    return 0;
}

Suggested direction (untested): gate the up-front query on IsDebuggerPresent(), the case the PR is for. Without a debugger, a first-chance exception doesn't stop the process, and __try already handles it at the old cost. faults_avoided would then count only debugger runs, which the docs line could say.

Verdict: comment on f85b47bf. The behaviour is correct and tested. I'm not approving until the author decides whether the always-on query cost is acceptable or should be gated.

Environment: Windows 11 25H2 build 26200.9974; MSVC 19.52.37029; no debugger attached.
CI: Build and test on Windows passes on f85b47bf. Both review threads are resolved.

This reply was AI-assisted.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6092744569 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#pullrequestreview-6092744569). Originally posted by [pigalot](https://github.com/pigalot) on 2026-11-27T19:44:33Z. **Review:** COMMENTED --- Independently reviewed `f85b47bf` integrated over `main` `0f3e8248` (tree `b139609a`, clean merge). **What I traced.** `mapped_prefix` refuses only `MEM_FREE`, and only from a fresh `VirtualQuery`. The per-thread cache holds only regions that are not free. So a stale entry can only send a range back to the old touch / `__try` path; it can never refuse a mapped range. `copy_title_bytes` keeps its catch-all filter (`any_exception` true), and `guarded_copy` keeps its AV / in-page filter. Both Codex threads are resolved, and the changes in `f85b47bf` do what the replies say. **What I ran.** I built `startup_local_log_check`, `startup_local_log_cache_failure_check` and `d3d12_xs_shim` in `dev` and `release`, then ran: `ctest --test-dir out/build/<preset> --no-tests=error -j 1 -R '^startup_local_log.*$'` 5/5 passed in Debug and Release `/O2`, including the four controls. **Mutant.** Dropping the up-front refusal in `guarded_memcpy` (`if (false)`) fails `startup_local_log` with two checks: - `FAIL free address space: zero first-chance exceptions in every judged round` - `FAIL free address space: the four refusals of every judged round are counted` Restored, it passes. `git diff --check` is clean. **Cost measurement.** This puts a `VirtualQuery` in front of every probe and guarded copy, with no debugger attached as well. The file's own comment above `probe_readable` says the probe avoided `VirtualQuery` for cost. So I timed `probe_readable` with `main`'s `local_log.h` against this PR's, in a small standalone program on synthetic memory only (`cl /O2`, two runs each, consistent): | case | `main` | PR | |---|---|---| | 4 MiB probe across 64 regions of alternating protection | 7.8–8.1 µs | 32.0 µs | | 4 KiB probe, round-robin over 32 separate 1 MiB allocations (more than the 16-entry cache) | 2 ns | 1.27 µs | | 64 KiB probe inside one 2 GiB committed region | 11.6 µs | 11.6 µs | | repeated 4 KiB probe of one region | 1 ns | 3 ns | So: - a range made of many regions costs about 4× as much; - callers that cycle over more than 16 regions per thread pay one query per probe; - single-region and cached cases stay cheap. I couldn't measure how often the runtime hits the first two patterns. Mapped-page runs and texture uploads are the likely candidates, but that is a hypothesis. <details><summary>Benchmark source and commands</summary> `main` header: `git show origin/main:src/startup_stubs/local_log.h > main/startup_stubs/local_log.h`, then `cl /nologo /std:c++20 /O2 /EHsc /I main /I src bench.cpp /Fe:bench_main.exe` and the same without `/I main` for the PR. ```cpp // #2846 micro-benchmark: probe_readable cost, main header vs PR header (synthetic memory only). #include <windows.h> #include "startup_stubs/local_log.h" #include <chrono> #include <cstdio> #include <cstdint> static double per_call_ns(int iters, auto&& fn) { const auto t0 = std::chrono::steady_clock::now(); std::size_t sink = 0; for (int i = 0; i < iters; ++i) sink += fn(i); const auto t1 = std::chrono::steady_clock::now(); if (sink == 1) std::printf(" "); return std::chrono::duration<double, std::nano>(t1 - t0).count() / iters; } int main() { constexpr std::size_t block = 64 << 10; // A: 1024 regions of 64 KiB with alternating protection (all readable), probed in 4 MiB windows. auto* a = static_cast<unsigned char*>(VirtualAlloc(nullptr, 1024 * block, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); for (std::size_t i = 0; i < 1024; ++i) { a[i * block] = 1; DWORD old; if (i & 1) VirtualProtect(a + i * block, block, PAGE_READONLY, &old); } const double na = per_call_ns(2000, [&](int i) { return x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(a + (i % 960) * block), 64 * block); }); // B: one 2 GiB committed private region (untouched except probed pages), 64 KiB probes at spread offsets. const std::size_t big = std::size_t{2} << 30; auto* b = static_cast<unsigned char*>(VirtualAlloc(nullptr, big, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); const double nb = per_call_ns(2000, [&](int i) { return x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(b + (std::size_t(i) * 7919 % 32768) * block), block); }); // C: 32 separate 1 MiB allocations probed round-robin (more regions than the 16-entry cache). unsigned char* c[32]; for (auto& p : c) { p = static_cast<unsigned char*>(VirtualAlloc(nullptr, 1 << 20, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); p[0] = 1; } const double nc = per_call_ns(20000, [&](int i) { return x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(c[i % 32]), 4096); }); // D: the same 4 KiB probe of one region, repeated (cache hit on the PR side). static unsigned char dst[4096]; const double nd = per_call_ns(20000, [&](int i) { return x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(c[0]), 4096) + dst[0]; }); std::printf("A 1024-region 4MiB probe: %.0f ns\nB 2GiB-region 64KiB probe: %.0f ns\nC 32 allocs round-robin 4KiB probe: %.0f ns\nD same 4KiB probe: %.0f ns\n", na, nb, nc, nd); return 0; } ``` </details> **Suggested direction (untested):** gate the up-front query on `IsDebuggerPresent()`, the case the PR is for. Without a debugger, a first-chance exception doesn't stop the process, and `__try` already handles it at the old cost. `faults_avoided` would then count only debugger runs, which the docs line could say. **Verdict:** comment on `f85b47bf`. The behaviour is correct and tested. I'm not approving until the author decides whether the always-on query cost is acceptable or should be gated. Environment: Windows 11 25H2 build 26200.9974; MSVC 19.52.37029; no debugger attached. CI: `Build and test on Windows` passes on `f85b47bf`. Both review threads are resolved. This reply was AI-assisted.
tedin7 commented 2026-11-27 22:08:15 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-27T22:08:15Z.


Thanks for the cost measurement. The VirtualQuery pre-check is now debug-only: it runs only when a debugger is attached or X2W_PROBE_PRECHECK is set (anything but 0), read once and cached. Normal runs keep the old probe / __try path at the old cost. Pushed a870370723565aad456a060f20aad3b3965a34cf (includes a merge of current main).

Verification:

  • Win2025 (Build 26100, MSVC 14.44.35207), exact head a8703707: x2w_pipe.py win2025 2846 --targets startup_local_log_check,startup_local_log_cache_failure_check,d3d12_xs_shim --regex '^startup_local_log' --force
  • Debug: ctest --preset dev -R '^startup_local_log' 6/6 passed. Release /O2: 6/6 passed.
  • New startup_local_log_precheck_off (env off): a free range is still refused, nothing is counted as an avoided fault, and the touch takes the real first-chance fault. The existing cases run with the env var on.
  • Linux: python3 tests/docs_links_check.py, cmake -S . -B <tmp> -DDXC_EXECUTABLE=/bin/true, public_guard.py.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7229059581 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#issuecomment-7229059581). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-27T22:08:15Z. --- Thanks for the cost measurement. The VirtualQuery pre-check is now debug-only: it runs only when a debugger is attached or `X2W_PROBE_PRECHECK` is set (anything but `0`), read once and cached. Normal runs keep the old probe / `__try` path at the old cost. Pushed `a870370723565aad456a060f20aad3b3965a34cf` (includes a merge of current `main`). Verification: - Win2025 (Build 26100, MSVC 14.44.35207), exact head a8703707: `x2w_pipe.py win2025 2846 --targets startup_local_log_check,startup_local_log_cache_failure_check,d3d12_xs_shim --regex '^startup_local_log' --force` - Debug: `ctest --preset dev -R '^startup_local_log'` 6/6 passed. Release /O2: 6/6 passed. - New `startup_local_log_precheck_off` (env off): a free range is still refused, nothing is counted as an avoided fault, and the touch takes the real first-chance fault. The existing cases run with the env var on. - Linux: `python3 tests/docs_links_check.py`, `cmake -S . -B <tmp> -DDXC_EXECUTABLE=/bin/true`, `public_guard.py`. AI-assisted; commands listed were executed locally.
pigalot commented 2026-11-27 23:24:24 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by pigalot on 2026-11-27T23:24:24Z.

Review: APPROVED


Re-reviewed 88b915db merged over current main 9345c21f. The merge is clean and git diff --cached --check is clean.

The cost question from my comment on f85b47bf is resolved.

  • The gate: 03c2ee01 gates mapped_prefix on precheck_enabled(). The pre-check runs only when a debugger is attached at the first call or X2W_PROBE_PRECHECK is set to anything but 0, and the result is read once into a function-local static.
  • Default runs: with neither, mapped_prefix returns bytes before any VirtualQuery. So probes and guarded copies take main's touch / __try path at main's cost, the case my benchmark measured.
  • The tests: startup_local_log now sets the variable itself before its first case. The new startup_local_log_precheck_off runs the same free-range probe with X2W_PROBE_PRECHECK=0. It requires that the range is still refused, that nothing is counted in faults_avoided, and exactly one first-chance fault per round.
  • The docs line says the same.

What I ran. I did a full build in dev and release, then ran

ctest --test-dir out/build/<preset> --no-tests=error -j 4 -R '^(startup_local_log.*|startup_compute_request.*|startup_shader_cache.*)$' -E '(_hardware$|startup_audio_)'

12/12 pass in both presets, with no skips. That includes startup_local_log_precheck_off and the controls.

Mutants. For each, I rebuilt startup_local_log_check and startup_local_log_cache_failure_check in dev and ran ^startup_local_log.*$:

Mutant Result
mapped_prefix ignores the gate (always pre-checks) killed (startup_local_log_precheck_off)
precheck_enabled() always false killed (startup_local_log, startup_local_log_cache_failure_control)
an unset X2W_PROBE_PRECHECK counts as on (n == 0 || value[0] != '0') survives
IsDebuggerPresent() dropped from the gate survives (no debugger in CTest, as expected)

Restored and rebuilt afterwards; git diff --quiet is clean.

Non-blocking.

  • The default case is unpinned. startup_local_log_precheck_off sets X2W_PROBE_PRECHECK=0, but no test leaves the variable unset, and unset is how every normal run starts. A gate that treats "not set" as on would bring back the always-on cost and still pass. A second phase that calls SetEnvironmentVariableA("X2W_PROBE_PRECHECK", nullptr) before its first probe and then runs the same checks would pin it. (ENVIRONMENT_MODIFICATION ... unset: would need CMake 3.22, above the project's 3.21 minimum.)

Verdict: approve on 88b915db.

Environment: Windows 11 25H2 build 26200.9974; MSVC 19.52.37029; Python 3.12.10; no debugger attached (no GPU tests in this set).
CI: Build and test on Windows, Assemble and translate gfx1013 fixtures and Run platform-independent Python checks on Linux pass on 88b915db.

This reply was AI-assisted.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6094239547 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2846#pullrequestreview-6094239547). Originally posted by [pigalot](https://github.com/pigalot) on 2026-11-27T23:24:24Z. **Review:** APPROVED --- Re-reviewed `88b915db` merged over current `main` `9345c21f`. The merge is clean and `git diff --cached --check` is clean. **The cost question from my comment on `f85b47bf` is resolved.** - **The gate:** `03c2ee01` gates `mapped_prefix` on `precheck_enabled()`. The pre-check runs only when a debugger is attached at the first call or `X2W_PROBE_PRECHECK` is set to anything but `0`, and the result is read once into a function-local static. - **Default runs:** with neither, `mapped_prefix` returns `bytes` before any `VirtualQuery`. So probes and guarded copies take `main`'s touch / `__try` path at `main`'s cost, the case my benchmark measured. - **The tests:** `startup_local_log` now sets the variable itself before its first case. The new `startup_local_log_precheck_off` runs the same free-range probe with `X2W_PROBE_PRECHECK=0`. It requires that the range is still refused, that nothing is counted in `faults_avoided`, and exactly one first-chance fault per round. - **The docs line** says the same. **What I ran.** I did a full build in `dev` and `release`, then ran ```powershell ctest --test-dir out/build/<preset> --no-tests=error -j 4 -R '^(startup_local_log.*|startup_compute_request.*|startup_shader_cache.*)$' -E '(_hardware$|startup_audio_)' ``` 12/12 pass in both presets, with no skips. That includes `startup_local_log_precheck_off` and the controls. **Mutants.** For each, I rebuilt `startup_local_log_check` and `startup_local_log_cache_failure_check` in `dev` and ran `^startup_local_log.*$`: | Mutant | Result | |---|---| | `mapped_prefix` ignores the gate (always pre-checks) | killed (`startup_local_log_precheck_off`) | | `precheck_enabled()` always false | killed (`startup_local_log`, `startup_local_log_cache_failure_control`) | | an unset `X2W_PROBE_PRECHECK` counts as on (`n == 0 \|\| value[0] != '0'`) | **survives** | | `IsDebuggerPresent()` dropped from the gate | survives (no debugger in CTest, as expected) | Restored and rebuilt afterwards; `git diff --quiet` is clean. **Non-blocking.** - **The default case is unpinned.** `startup_local_log_precheck_off` sets `X2W_PROBE_PRECHECK=0`, but no test leaves the variable unset, and unset is how every normal run starts. A gate that treats "not set" as on would bring back the always-on cost and still pass. A second phase that calls `SetEnvironmentVariableA("X2W_PROBE_PRECHECK", nullptr)` before its first probe and then runs the same checks would pin it. (`ENVIRONMENT_MODIFICATION ... unset:` would need CMake 3.22, above the project's 3.21 minimum.) **Verdict:** approve on `88b915db`. Environment: Windows 11 25H2 build 26200.9974; MSVC 19.52.37029; Python 3.12.10; no debugger attached (no GPU tests in this set). CI: `Build and test on Windows`, `Assemble and translate gfx1013 fixtures` and `Run platform-independent Python checks on Linux` pass on `88b915db`. This reply was AI-assisted.
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
R0Y00/Xbox2Windows!2838
No description provided.