Skip to content

tests: a released page is read back without racing the tests beside it - #3017

Open
fiestorra wants to merge 1 commit into
ProjectLeonida:mainfrom
fiestorra:loader-page-race
Open

fiestorra wants to merge 1 commit into
ProjectLeonida:mainfrom
fiestorra:loader-page-race

Conversation

@fiestorra

Copy link
Copy Markdown
Contributor

tests: a released page is read back without racing the tests beside it

memory_at_names_what_an_access_hit releases a four-page reservation and then reads one of
the pages back to see nothing mapped there. Another test in the same binary mapping in the
microseconds between the VirtualFree and the read takes that address, and the read says
read-write instead - which is exactly what CI did on two unrelated pull requests:

---- crash::tests::memory_at_names_what_an_access_hit
assertion `left == right` failed
  left: "read-write"
 right: "nothing mapped there"

The read is now over a fresh reservation released immediately before it, retried: the first
attempt whose address nobody took is the answer, and 64 taken in a row is a real failure
rather than a busy neighbour. Each attempt is a VirtualAlloc and a VirtualFree of 4 KiB.

Why not a lock: the window is between the release and the read, and the neighbour is any of
six files in this crate that map pages in their tests (console_insn, descriptor_sites,
game_actions, thunks, tls, write_sites), so a lock held by this module alone would not
remove it; a crate-wide one would touch all seven. The retry costs nothing and holds whatever
the neighbour does.

What I could not do: reproduce the failure on demand. cargo test -p leonida-loader --lib crash::tests passed 19/19 six times in a row here, so the negative control is the CI log
above and not a local red. With the change: 19/19 four more times, clippy 0.

Written with an AI assistant.

`memory_at_names_what_an_access_hit` releases a four-page reservation and then reads one of
the pages back to see `nothing mapped there`. Another test in the same binary mapping in the
microseconds between the `VirtualFree` and the read takes that address, and the read says
`read-write` instead - which is exactly what CI did on two unrelated pull requests:

    ---- crash::tests::memory_at_names_what_an_access_hit
    assertion `left == right` failed
      left: "read-write"
     right: "nothing mapped there"

The read is now over a fresh reservation released immediately before it, retried: the first
attempt whose address nobody took is the answer, and 64 taken in a row is a real failure
rather than a busy neighbour. Each attempt is a `VirtualAlloc` and a `VirtualFree` of 4 KiB.

Why not a lock: the window is between the release and the read, and the neighbour is any of
six files in this crate that map pages in their tests (`console_insn`, `descriptor_sites`,
`game_actions`, `thunks`, `tls`, `write_sites`), so a lock held by this module alone would not
remove it; a crate-wide one would touch all seven. The retry costs nothing and holds whatever
the neighbour does.

What I could not do: reproduce the failure on demand. `cargo test -p leonida-loader --lib
crash::tests` passed 19/19 six times in a row here, so the negative control is the CI log
above and not a local red. With the change: 19/19 four more times, clippy 0.

Written with an AI assistant.
@andrew-ai

Copy link
Copy Markdown

Ran the Windows leonida-loader library suite 25 times at parent 913b88b and 25 times at PR head a607df1. I rebuilt at each revision with cargo test --locked -p leonida-loader --lib --no-run, then launched the resulting test executable in a fresh process each time with --test-threads 16.

All 85 tests passed in each of the 50 runs (2,125 test executions per revision). I could not reproduce the original intermittent failure on this machine, so this confirms repeated parallel passes on the PR but does not establish a reduction in flake rate.

Codex-assisted.

@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-3017 — Linux, Fedora 45, Rust 1.98.1, cross-compiled for x86_64-pc-windows-gnu, Wine 11.21, no GPU device, no game files

Verdict: PASS. The old line reads an address back after handing it to the free pool, and anything else can already be in it; the pull request keeps the property the line was checking (a released page reads back free) and stops failing on a neighbour taking it. I reproduced the race it is defending against.

Head a607df12, base the current main (0ae5a266), merge base 913b88b9, 1 file, +17/−1: d3d12/crates/leonida-loader/src/crash.rs.

1. What it changes

One test, crash::tests::memory_at_names_what_an_access_hit, which reserves four pages, commits three with different protections, asks [memory_at] to name each, releases them all, and then asks what the released range is. The base asserts that directly, which is the flaky part:

unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) };
-        assert_eq!(memory_at(base + 8), "nothing mapped there");

The release hands those pages back to the process, and a test running beside this one can take them between the VirtualFree and the read. The replacement makes a fresh reservation instead and treats a taken range as "try again":

+        let gone = (0..64).any(|_| {
+            // SAFETY: reserves, commits and releases four pages of ours; nothing reads them.
+            let fresh = unsafe {
+                let fresh = VirtualAlloc(std::ptr::null(), 0x4000, MEM_RESERVE, PAGE_NOACCESS);
+                assert!(!fresh.is_null());
+                assert!(!VirtualAlloc(fresh, 0x1000, MEM_COMMIT, PAGE_READWRITE).is_null());
+                VirtualFree(fresh, 0, MEM_RELEASE);
+                fresh as usize
+            };
+            memory_at(fresh + 8) == "nothing mapped there"
+        });
+        assert!(gone, "a released page was still read back as mapped 64 times in a row");

and it keeps the base's remaining lines, memory_at(0), memory_at(usize::MAX) and the check that the test's own code is a read-execute image page named by its module. Everything is inside mod tests, so no production code moves.

2. The new test checks the property that matters

This is test-only, so the red side (merge base plus the test hunks) compiles and passes the same way the green side does, and the harness cannot show red-then-green. Two things were worth checking instead.

First, that the race is real. I wrote a small standalone program (cross-compiled with the same toolchain and run under Wine) where one thread reserves the same range as PAGE_READWRITE, commits it, spins, and releases it, while the main thread reserves, commits, MEM_RELEASEs and reads the range back 200 000 times:

rounds released range read back as what memory_at would say
200 000 MEM_FREE nothing mapped there — 52 156, 54 991, 58 621 over three runs
200 000 mapped in the meantime MEM_COMMIT/PAGE_READWRITE — 6 399, 5 882, 6 590
200 000 taken outright (my own VirtualAlloc failed) 141 445, 139 127, 134 789

So the base line is not deterministic: in about one round out of thirty the range already holds somebody else's PAGE_READWRITE, and the assertion fails for a reason nothing to do with the code. That is the bug, and it explains a read-write from CI.

Second, that the replacement is not vacuous. I mutated the loop body so no attempt can ever match (memory_at(fresh + 8) == "a string that is never returned"), rebuilt, and the test failed with the new message:

panicked at crates/leonida-loader/src/crash.rs:931:9:
a released page was still read back as mapped 64 times in a row

Restoring the line, it passes again. So the assertion still has teeth, and it still says something the base said — a released page really does read back free — rather than giving that up.

Compared with the sibling pull request #2939, which fixes the same test by querying addresses Windows never maps, this one is the more conservative fix: it retains the property under test. The cost is the any over 64 attempts, and the assert!(!fresh.is_null()) inside it, which would panic rather than retry if a neighbour held the address space in that round. Sixty-four 16 KiB allocations is nothing to exhaust, and the retry loop was intended to absorb exactly that, but it is a panic path rather than a skipped one.

3. What the tests do here

count
red side (merge base + this pull request's test hunks) 88
green side (the pull request's head) 88
pass on both 87
red → green 0 (expected: the change touches no production code)
regressions (pass on red, fail on green) 0
fail on both 1 — loads_binds_and_calls_probe
ignored 0
only on red / only on green 0 / 0

Run by hand on the head, the crate's unit suite is 84 passed / 0 failed three times in a row, and memory_at_names_what_an_access_hit on its own is 30/30. The red side has one test fewer than the green side because the merge base here is newer than the one #2939 branched from, not because this pull request removed anything.

4. Any failure I saw, and why it is not this pull request

loads_binds_and_calls_probe fails on the red side and on the green side alike, so it is not caused here. It is an integration test (d3d12/crates/leonida-loader/tests/load_probe.rs) and it dies building its own fixture:

panicked at crates/leonida-loader/tests/load_probe.rs:35:10: running cargo: Os { code: 6, kind: Uncategorized, ... }
error: manifest path `/home/shangli/.../d3d12/tests/fixtures/hle-probe/Cargo.toml` does not exist

The test shells out to cargo to compile a probe, and there is no cargo on the Wine side of this machine, and the manifest path is written with backslashes that only Windows accepts. It needs a native Windows box. Nothing else failed on either side.

5. What I did not check

  • A GPU, a D3D12 adapter, or the running title. Everything is unit tests under Wine. The crash module needs no device, which is why these pass here at all.
  • Real Windows, not Wine 11.21. The CI failure the comment refers to happened on a different machine, and I have not reproduced it there, nor can I see their log. I reproduced the race on this one.
  • The real contention rate. My racer polls one address as hard as it can, which overstates it: the actual neighbour is whatever test calls VirtualAlloc next, so ~3 % is a ceiling and not a measurement. I did not measure how often the 64 attempts would all be beaten, and the panic path on a null VirtualAlloc was exercised by reasoning only, not by forcing an exhaustion.
  • The PAGE_NOACCESS reservation versus the base's mixed protections. The fresh block reserves four pages as PAGE_NOACCESS and commits one as PAGE_READWRITE; the base committed read-only, guard and no-access pages. Both end MEM_FREE after the release, and that is the point, but the fresh loop does not re-exercise the three protections — the lines above it do, so nothing is lost.

The program was scratch work under /tmp/opencode, cross-compiled with the same toolchain, and is not part of this pull request: nothing was committed and nothing was pushed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants