WIP: fix(host): the stack walks run clang's AVX return suffix themselves and every step under a fault guard #1951

Draft
siantm wants to merge 10 commits from siantm/Longshot:fix/sampler-epilogue-unwind into main
Contributor

Summary

Fixes #1584. The all-thread sampler (HOS_SAMPLE_ALL, which HOS_PROFILE=1 starts), the one-thread sampler
(HOS_SAMPLE), the slow-frame recorder, the crash report and the crash record walk host stacks one frame at a time.
Since #1343 the walk checks the stack pointer and the frame register before it calls RtlVirtualUnwind, and the game
could still close with 0xc0000005 inside RtlVirtualUnwind, in the sampler's thread.

The cause: clang's AVX code (the lifted game, the host and the renderer at -march=native) ends a function with its
pops, then a vzeroupper, then the ret. Windows' unwinder knows an epilogue only as an add/lea to rsp, pops and
a ret or jump, so a thread stopped on those pops or on the vzeroupper is unwound as if it were in the function's
body: the whole prologue is undone again on a stack pointer the pops have already moved, and the unwinder reads up to
the frame's size too high. Inside the stack that gives the sample wrong callers; when the frame is larger than what the
thread's stack has above it, the read leaves the stack and faults.

This PR (host/mkw_glue.c, host/hos_crash_record.c):

  • unwind_avx_return: the walk runs that one suffix itself, as the processor will: pop r64 (0 to 16, never rsp),
    vzeroupper (c5 f8 77), a plain ret (c3), every byte inside the function's own RUNTIME_FUNCTION range, the
    registers written through CONTEXT's named members, the pops and the return address checked against the walked
    thread's stack first. Everything else (the add/lea before the pops, where the body's unwind is still right; ret imm16; jumps; an epilogue without the vzeroupper, which Windows recognises itself) goes to RtlVirtualUnwind. A
    record that is not version 1 or 2 ends the walk; the frame register's frame must be on the stack, as before.
  • walk_guarded/walk_fault: every step runs under a vectored handler registered first at startup; a fault while a
    step runs (a no-access page inside the stack's range, unwind data that cannot be read) puts the thread back where the
    step began and the walk ends there, the sample cut short.
  • sample_stack (both samplers): the sampled thread is suspended only to take its context, its stack's limits and a
    copy of its stack from the stack pointer up (128 KB at most, through ReadProcessMemory, which reports an unreadable
    page as a short copy); it is resumed before anything that can fault or take a lock (the unwind-table lookup,
    RtlVirtualUnwind, the guard, the module lookups), and the walk runs in the copy (copy_step). Each sampler's copy
    is a reservation of its own (stack_copy_open): 128 KB read-write right under 64 MB reserved without access, the
    copy placed at the end of the read-write part, so a step that would read past the bytes taken for this sample faults
    in the guard and the walk ends at that frame; below the copy the buffer is kept zero.
  • At the pops and the ret of an ordinary frame-pointer epilogue (lea rsp, [r12 + disp]; pop r12; ret) the frame
    register lies below the stack pointer: in a function with a version 1 record the step now checks only the pops'
    slots and the return address (on the stack or in the copy) and leaves the frame register alone; a stop on that
    lea itself is run by the walk (unwind_r12_lea), since RtlVirtualUnwind decodes it without its SIB byte.
  • walk_init: NtQueryInformationThread and the handler are set up on the main thread in hos_commit_init, and again
    before the samplers' threads start in hos_prof_start, so no sampler resolves anything on first use.
  • The crash record's backtrace (host_stack in host/hos_crash_record.c) steps through the same guarded unwind_step
    (hos_crash_record_unwinder) instead of calling RtlVirtualUnwind itself.

To see the bugs without the game: python -I -B tests/test_sampler_stack_walk.py on Windows at 1b0c78fe (the sampler
walking a suspended thread hangs), at 99cc86f3 (the new cases on this PR's first fix) or at this branch's first commit
e339fad8 (the earlier test alone on main).

Read first: sample_stack, copy_step, unwind_avx_return, step_frame, walk_guarded and unwind_step in
host/mkw_glue.c;
tests/test_sampler_stack_walk.py.

Testing

Tested: Windows 11, i7-9700, RTX 4060 (NVIDIA 610.88), llvm-mingw clang 23.1.5; game-free checks only. This change
has not run in the game on this PC yet (Still to test). Each check ran in a hidden console of its own, through the PC's
job queue. Round 4 (futondestroyer's third review), on main @ 9dd41326, head ea04ea95, now rebased onto main @
f8c130b1 as f6d9c754 (git range-diff: every commit "="; main's new commits touch none of this PR's files, so the
checks were not run again):

  • tests/test_sampler_stack_walk.py at the epilogue test commit 69bd2665: fails (the lea, the pops and the ret of
    an ordinary frame-pointer epilogue do not unwind, on the stack and in the samplers' copy); at the cut-off test commit
    c0d66d2d: fails (cut_save walks on to the caller with a save read past the copy); at the head ea04ea95: passes,
    every case, with --cc and with the default compiler, incl. fp_epilogue, cut_save, cut_return, the 53-step
    AVX frame and the 400-sample lock case; its control (the walk with the thread suspended) hung after 0 of 400.
  • host/mkw_glue.c and host/hos_crash_record.c compiled -fsyntax-only at ea04ea95: no error.
  • run_all --changed was not run again this round.

Round 3, on this branch rebased onto main @ 9dd41326, head 2ee9b8f9:

  • python -I -B tests/test_sampler_stack_walk.py --cc <llvm-mingw clang> at 1b0c78fe (the lock test on this PR's
    previous fix): fails: sampler_lock "the sampler hung after 0 of 400 samples, the thread left suspended" (the
    samplers walked the thread while it was suspended), and the source checks find no sample_stack. At the head
    (2ee9b8f9): passes, all 13 cases, "PASS (runtime: every case ran)": the 10 authored cases, the stepped AVX frame "53
    steps of avx_frame unwound to its caller (7 of them pops, 1 the vzeroupper)", and "400 samples of a thread adding and
    removing vectored handlers, each walk through unreadable unwind data". The same at the head without --cc (the
    default compiler, LONGSHOT_MINGW's clang). The control case (the walk made with the thread suspended, as before)
    hung in each of the four runs where it ran (two at 1b0c78fe, two at the head), after 0, 3, 43 and 0 of 400 samples.
  • The earlier round (on main @ f1f2dc5b): with the authored cases on this PR's first fix (f3ed9d4b, now 99cc86f3)
    8 of 11 cases failed; at 186660c6 all 11 passed. They are unchanged since and pass at the head (above).
  • host/mkw_glue.c and host/hos_crash_record.c compiled -fsyntax-only with the host build's flags (llvm-mingw,
    -fms-extensions, -march=native) at the fix: no error.
  • python -I -B tests/run_all.py --strict --changed origin/main at the fix (2ddabf67, before the test's syntax-only
    compile got -Wno-unused-function; the host files are the head's): 5 passed, 7 failed, 0 skipped. Six of the 7
    (test_crash_record.py, test_crash_dialog.py, test_input_background.py, test_profiling_mode.py,
    test_renderer_new_handler.py, test_slow_frames.py) fail on main @ 9dd41326 too, run by name in the same
    queue job; the seventh, test_sampler_stack_walk.py, stopped at that unused-function error and passes at the head
    (above). test_crash_record.py stops at a renderer source check before it builds the record, so the record's
    step is covered only by the syntax check and the walk test's source check.

Still to test:

  • Windows 11, this PC (i7-9700, RTX 4060 (NVIDIA 610.88)): HOS_PROFILE=1 in Castle Town's market, 120 s standing and
    turning, this PR and main alternated (A B B A A B), expecting no CRASH: line from the walk, a readable profile
    (python -I scripts/perf.py report on the run's profile folder), the time each sampled thread stays suspended, the
    sweeps a second and the stack depths on both sides (the game-free fixture in Measurements shows this PR slower than
    main there), and the frame-time tails about as on main, with HOS_PROFILE=1 and with the slow-frame recorder (by hand,
    queued)
  • Linux: python3 -I -B tests/test_sampler_stack_walk.py, expecting the source checks to pass and "source only" (the
    walk is Windows' only); the host build (by hand)
  • Windows, other CPUs and GPUs (an AMD CPU; AMD and Intel GPUs): Castle Town's market for two minutes with
    HOS_PROFILE=1, this PR against main, expecting no crash on this PR's side (@Beanstalk play Castle Town's market
    for two minutes with HOS_PROFILE=1 on Windows PCs, this PR against main, and report any crash)

Measurements

Verdict: in the authored fixture the walk unwinds every stop of clang's AVX return suffix, and the stops this PR's
first fix misread or faulted on (ret 16, lea through r12, jmp r11, no-access pages, a bad chain, a version 3 record) now
unwind right or end the walk, and a sampled thread that holds the vectored-handler lock is resumed (400 of 400 samples)
where walking it while suspended hung. (The earlier fixture's 8 wrong steps of 53 on main @ fc4a6769 stay at 0 of 53.)
The cost, game-free: a sample is slower on this PR than on main, 13.30 against 9.00 us with 12 frames x 256 B and
26.60 against 10.50 us with 48 frames x 2048 B (4.30 and 16.10 us more), so the sweep rate falls from 111111 to 75188
and from 95238 to 37594 samples a second (32 % and 61 % fewer); the sampled thread is held suspended 7.90 against 6.80 us
and 14.60 against 8.50 us. Only runs with the diagnostic sampling switches pay it (below). Not measured in play yet
(Still to test).

Setup: Windows 11, i7-9700, llvm-mingw clang 23.1.5; python -I -B tests/test_sampler_stack_walk.py, once a side
through the PC's job queue.

Baseline: this PR's earlier fixes with the tests that catch what they missed (the authored cases on the first fix,
99cc86f3, on main @ f1f2dc5b; the lock case on the second fix, 1b0c78fe, on main @ 9dd41326), as the bugs fixed
here are in this PR's own earlier code.

Before: this PR @ 99cc86f3 (row 1) and @ 1b0c78fe (row 2), with the new tests After: this PR @ 2ee9b8f9
tests/test_sampler_stack_walk.py: authored cases and the stepped AVX frame (99cc86f3) 8 of 11 cases fail (3 of them exit 0xc0000005) 11 of 11 pass; 53 of 53 stepped AVX stops unwound to the caller
tests/test_sampler_stack_walk.py sampler_lock: samples of a thread adding and removing vectored handlers (1b0c78fe) hung after 0 of 400 400 of 400, the thread running after
FAIL: a jmp r11 in the body (no epilogue): step 1, rip 0, ...
FAIL: ret 16: step 1, rsp ...fe8, want the walk ended or rsp ...ff8
sampler stack walk: 8 of 11 cases failed: avx_native (exit 0x1), ret_imm16 (exit 0x1), lea_sib (exit 0x1), version3 (exit 0x1), bad_chain (exit 0xc0000005), no_access_suffix (exit 0xc0000005), no_access_body (exit 0xc0000005), wrap (exit 0x1)
FAIL: the sampler hung after 0 of 400 samples, the thread left suspended

ok avx_suffix ... ok wrap (10 authored cases)
400 samples of a thread adding and removing vectored handlers, each walk through unreadable unwind data
53 steps of avx_frame unwound to its caller (7 of them pops, 1 the vzeroupper)
PASS (runtime: every case ran): the stack walks step through unwind_step, under its fault guard, on the walked thread's stack

The cost of a sample (futondestroyer's 65450 and 67046: suspension time, sweep rate, stack depth). Setup: Windows
11, i7-9700, llvm-mingw clang 23.1.5 -std=gnu11 -O2; run alone on this PC on 2026-11-22 (02:13 UTC). Each checkout's
walk helpers from host/mkw_glue.c, cut as tests/test_sampler_stack_walk.py cuts them, sample a thread of the
harness's own: a chain of frames, each with its own unwind data, and a busy loop at the bottom. Two shapes: 12 frames x
256 B (about 4 KiB of stack) and 48 frames x 2048 B (about 100 KiB, near the copy's 128 KiB). 11 rounds of 300 samples
per arm and shape, the arms interleaved and their order reversed every other round. "Suspended" is the time from
SuspendThread's return to the ResumeThread call (how long the sampler holds the thread); "sample" is the whole call.
Each is the median of the rounds' medians, with the range of the round medians and the median of the rounds' p99s.
"Frames" is the depth the walk reports; "sweep" is 1e6 / the sample median, samples a second for one thread and one
sampler. The harness walks up to 128 frames; in the game the samplers stop at 16 (HOS_SAMPLE_ALL, the slow-frame
recorder) or 48 (HOS_SAMPLE).

The arms:

  • main @ f8c130b1 (this PR's merge base): suspend, take the context, walk the live stack frame by frame with main's
    unwind_step, resume. This is how the samplers sample on main.
  • this PR @ f6d9c754: sample_stack. It suspends the thread, takes the context, the stack's limits and a copy of the
    stack (at most 128 KiB) and resumes it; then it walks the copy.
  • head-susp: f6d9c754's unwinder walked while the thread is suspended, as on main (the test's walk_suspended).
    It has the same unwinder as this PR and no copy, so it splits the cost: this PR against head-susp is the copy's
    share, head-susp against main the unwinder's.
main @ f8c130b1 this PR @ f6d9c754 head-susp (f6d9c754, walked while suspended)
12 x 256 B: suspended, us (median, rounds, p99) 6.80 (4.80 to 8.10), p99 52.30 7.90 (7.00 to 10.00), p99 45.90 7.40 (4.90 to 9.90), p99 48.90
12 x 256 B: sample, us (median, rounds, p99) 9.00 (6.30 to 12.00), p99 56.40 13.30 (11.30 to 25.50), p99 59.70 9.50 (6.20 to 16.10), p99 55.10
12 x 256 B: frames; sweep, samples/s 15; 111111 15; 75188 15; 105263
48 x 2048 B: suspended, us (median, rounds, p99) 8.50 (7.50 to 13.60), p99 52.10 14.60 (13.60 to 18.50), p99 57.90 11.00 (9.30 to 16.30), p99 50.70
48 x 2048 B: sample, us (median, rounds, p99) 10.50 (8.90 to 18.40), p99 58.30 26.60 (24.20 to 41.00), p99 88.40 13.00 (10.80 to 27.40), p99 52.50
48 x 2048 B: frames; sweep, samples/s 51; 95238 51; 37594 51; 76923
bench_sample_suspend: E:\LongshotTools\LongshotBuilder\tools\llvm-mingw\bin\clang.exe -std=gnu11 -O2; main E:/longshot-x86asm/pr-work/tmp/measure/f8c130b1, head E:/longshot-x86asm/pr-work/tmp/measure/f6d9c754; 11 rounds of 300 samples
12 frames x  256 B  main      suspended median     6.80 us (rounds 4.80 to 8.10), p99    52.30 | sample median     9.00 us (rounds 6.30 to 12.00), p99    56.40 | frames  15 | sweep  111111 samples/s
12 frames x  256 B  head      suspended median     7.90 us (rounds 7.00 to 10.00), p99    45.90 | sample median    13.30 us (rounds 11.30 to 25.50), p99    59.70 | frames  15 | sweep   75188 samples/s
12 frames x  256 B  head-susp suspended median     7.40 us (rounds 4.90 to 9.90), p99    48.90 | sample median     9.50 us (rounds 6.20 to 16.10), p99    55.10 | frames  15 | sweep  105263 samples/s
48 frames x 2048 B  main      suspended median     8.50 us (rounds 7.50 to 13.60), p99    52.10 | sample median    10.50 us (rounds 8.90 to 18.40), p99    58.30 | frames  51 | sweep   95238 samples/s
48 frames x 2048 B  head      suspended median    14.60 us (rounds 13.60 to 18.50), p99    57.90 | sample median    26.60 us (rounds 24.20 to 41.00), p99    88.40 | frames  51 | sweep   37594 samples/s
48 frames x 2048 B  head-susp suspended median    11.00 us (rounds 9.30 to 16.30), p99    50.70 | sample median    13.00 us (rounds 10.80 to 27.40), p99    52.50 | frames  51 | sweep   76923 samples/s

Where the cost comes from (12 x 256 B / 48 x 2048 B):

  • The copy (this PR against head-susp, same unwinder): +0.50 / +3.60 us suspended and +3.80 / +13.60 us a sample.
    sample_stack copies the whole stack from the stack pointer up, at most 128 KiB, while the thread is suspended,
    however few frames its caller walks (host/mkw_glue.c:523-528). Most of this share falls after the resume, in the
    walk in the copy. Reading the code does not explain that part: copy_step's register remap (:477-489) is a few
    compares a step, and it was not measured apart.
  • The unwinder (head-susp against main, both walking while suspended): +0.50 / +2.50 us a sample. This covers the
    fault guard, set up for every step where once per walk would do (unwind_step calls walk_guarded, an
    RtlCaptureContext each step: :467-473, :453-464), and the AVX-suffix and lea decoders (:395-450). They
    were measured together, not apart.

What that buys: the samplers no longer walk a thread while it is suspended. A fault in a step (a no-access page,
unreadable unwind data) or a lock the walk takes can no longer wait on the suspended thread and hang both
(sample_stack, :508-545; the sampler_lock case above). Every read the walk makes is bounded by the copy and its
no-access guard (:490-507). The AVX return suffix and lea rsp, [r12 + disp] stops unwind right (:395-418).

Who pays: only runs with the diagnostic sampling switches. These are HOS_PROFILE=1 (which sets HOS_SAMPLE_ALL),
HOS_SAMPLE_ALL, HOS_SAMPLE with HOS_PROFILE_EVERY, and HOS_SLOW_FRAMES, all off by default
(gpu/vk/switches.def:158, :172, :173, :186). The samplers' threads start only in hos_prof_start (host/mkw_glue.c:1112-1123).
The crash report and the crash record walk only after a crash, on the failing thread's own stack, with no copy (:577,
:674). The renderer's hang dump (RX_VK_HANG_DUMP, off by default) has its own unwinder in
gpu/vk/vk_hangdump.cpp, which this PR does not touch. Every run, profiled or not, pays one thing, not measured: walk_fault is first in the
process's vectored-handler chain (hos_commit_init → walk_init, :682, :330). Each exception, a commit-on-touch
fault included, first takes one thread-local read there (:318-320).

Risks

The change is in the stack walks only: the crash report's backtrace and the crash record's, HOS_SAMPLE,
HOS_SAMPLE_ALL (HOS_PROFILE) and the slow-frame recorder. A walk that a check or the guard ends early gives a shorter
backtrace or sample, as a refused step did before; a mistake in unwind_avx_return would show as wrong callers in a
profile or a crash report, never in play without those switches (a crash walks only after the crash). The guard's
handler is first in the process's vectored chain, in every run; on any exception it reads one thread-local and passes the
exception on unless a step is running on that thread (not measured). The samplers no longer walk a suspended thread: while it is suspended, sample_stack makes only system calls
(GetThreadContext, NtQueryInformationThread, ReadProcessMemory) and reads the thread's TEB, so a fault in a walk
is dispatched with no thread suspended (before, one could wait for a lock the suspended thread held and hang both:
the test's sampler_lock case hangs at 1b0c78fe). A suspension now costs the copy of the stack the thread uses, up to
128 KB: in the game-free fixture a sample takes 4.30 to 16.10 us more than on main and holds the thread 1.10 to 6.10 us
longer (Measurements), with the diagnostic sampling switches only; not measured in play yet (Still to test). A stack deeper than the copy ends the sample there. The crash
report and the crash record walk the failing thread's own stack, with no other thread suspended. The crash record without hos_crash_record_unwinder set
(its test fixture) walks frame pointers. A revert is enough; players notice nothing.

Checklist

Ready for review

  • One topic, on current main; the title is a Conventional Commit.
  • Tested on my own PC, in the game for a change the game runs, as Testing says.
  • mise run test passes (any failure that also fails on main is named).
  • Measured against main, or Measurements says why there is nothing to measure.
  • No game files, build output or hand-edited generated files; third_party/ untouched; nothing GPL-incompatible.

When it applies

  • A fix: a game-free test that fails on main and passes here.
  • A check under tests/ that reads changed source is updated, not weakened.
  • Host code builds on Windows (llvm-mingw) and Linux, with UTF-8 paths.
  • AI assistance recorded with Assisted-by: / Co-Authored-By: trailers.
## Summary Fixes #1584. The all-thread sampler (`HOS_SAMPLE_ALL`, which `HOS_PROFILE=1` starts), the one-thread sampler (`HOS_SAMPLE`), the slow-frame recorder, the crash report and the crash record walk host stacks one frame at a time. Since #1343 the walk checks the stack pointer and the frame register before it calls `RtlVirtualUnwind`, and the game could still close with `0xc0000005` inside `RtlVirtualUnwind`, in the sampler's thread. The cause: clang's AVX code (the lifted game, the host and the renderer at `-march=native`) ends a function with its pops, then a `vzeroupper`, then the `ret`. Windows' unwinder knows an epilogue only as an `add`/`lea` to `rsp`, pops and a `ret` or jump, so a thread stopped on those pops or on the `vzeroupper` is unwound as if it were in the function's body: the whole prologue is undone again on a stack pointer the pops have already moved, and the unwinder reads up to the frame's size too high. Inside the stack that gives the sample wrong callers; when the frame is larger than what the thread's stack has above it, the read leaves the stack and faults. This PR (`host/mkw_glue.c`, `host/hos_crash_record.c`): - `unwind_avx_return`: the walk runs that one suffix itself, as the processor will: `pop r64` (0 to 16, never `rsp`), `vzeroupper` (`c5 f8 77`), a plain `ret` (`c3`), every byte inside the function's own `RUNTIME_FUNCTION` range, the registers written through `CONTEXT`'s named members, the pops and the return address checked against the walked thread's stack first. Everything else (the `add`/`lea` before the pops, where the body's unwind is still right; `ret imm16`; jumps; an epilogue without the `vzeroupper`, which Windows recognises itself) goes to `RtlVirtualUnwind`. A record that is not version 1 or 2 ends the walk; the frame register's frame must be on the stack, as before. - `walk_guarded`/`walk_fault`: every step runs under a vectored handler registered first at startup; a fault while a step runs (a no-access page inside the stack's range, unwind data that cannot be read) puts the thread back where the step began and the walk ends there, the sample cut short. - `sample_stack` (both samplers): the sampled thread is suspended only to take its context, its stack's limits and a copy of its stack from the stack pointer up (128 KB at most, through `ReadProcessMemory`, which reports an unreadable page as a short copy); it is resumed before anything that can fault or take a lock (the unwind-table lookup, `RtlVirtualUnwind`, the guard, the module lookups), and the walk runs in the copy (`copy_step`). Each sampler's copy is a reservation of its own (`stack_copy_open`): 128 KB read-write right under 64 MB reserved without access, the copy placed at the end of the read-write part, so a step that would read past the bytes taken for this sample faults in the guard and the walk ends at that frame; below the copy the buffer is kept zero. - At the pops and the `ret` of an ordinary frame-pointer epilogue (`lea rsp, [r12 + disp]; pop r12; ret`) the frame register lies below the stack pointer: in a function with a version 1 record the step now checks only the pops' slots and the return address (on the stack or in the copy) and leaves the frame register alone; a stop on that `lea` itself is run by the walk (`unwind_r12_lea`), since `RtlVirtualUnwind` decodes it without its SIB byte. - `walk_init`: `NtQueryInformationThread` and the handler are set up on the main thread in `hos_commit_init`, and again before the samplers' threads start in `hos_prof_start`, so no sampler resolves anything on first use. - The crash record's backtrace (`host_stack` in `host/hos_crash_record.c`) steps through the same guarded `unwind_step` (`hos_crash_record_unwinder`) instead of calling `RtlVirtualUnwind` itself. To see the bugs without the game: `python -I -B tests/test_sampler_stack_walk.py` on Windows at 1b0c78fe (the sampler walking a suspended thread hangs), at 99cc86f3 (the new cases on this PR's first fix) or at this branch's first commit e339fad8 (the earlier test alone on `main`). Read first: `sample_stack`, `copy_step`, `unwind_avx_return`, `step_frame`, `walk_guarded` and `unwind_step` in `host/mkw_glue.c`; `tests/test_sampler_stack_walk.py`. ## Testing **Tested:** Windows 11, i7-9700, RTX 4060 (NVIDIA 610.88), llvm-mingw clang 23.1.5; game-free checks only. This change has not run in the game on this PC yet (Still to test). Each check ran in a hidden console of its own, through the PC's job queue. Round 4 (futondestroyer's third review), on `main` @ 9dd41326, head ea04ea95, now rebased onto `main` @ f8c130b1 as f6d9c754 (`git range-diff`: every commit "="; main's new commits touch none of this PR's files, so the checks were not run again): - `tests/test_sampler_stack_walk.py` at the epilogue test commit 69bd2665: fails (the `lea`, the pops and the `ret` of an ordinary frame-pointer epilogue do not unwind, on the stack and in the samplers' copy); at the cut-off test commit c0d66d2d: fails (`cut_save` walks on to the caller with a save read past the copy); at the head ea04ea95: passes, every case, with `--cc` and with the default compiler, incl. `fp_epilogue`, `cut_save`, `cut_return`, the 53-step AVX frame and the 400-sample lock case; its control (the walk with the thread suspended) hung after 0 of 400. - `host/mkw_glue.c` and `host/hos_crash_record.c` compiled `-fsyntax-only` at ea04ea95: no error. - `run_all --changed` was not run again this round. Round 3, on this branch rebased onto `main` @ 9dd41326, head 2ee9b8f9: - `python -I -B tests/test_sampler_stack_walk.py --cc <llvm-mingw clang>` at 1b0c78fe (the lock test on this PR's previous fix): fails: `sampler_lock` "the sampler hung after 0 of 400 samples, the thread left suspended" (the samplers walked the thread while it was suspended), and the source checks find no `sample_stack`. At the head (2ee9b8f9): passes, all 13 cases, "PASS (runtime: every case ran)": the 10 authored cases, the stepped AVX frame "53 steps of avx_frame unwound to its caller (7 of them pops, 1 the vzeroupper)", and "400 samples of a thread adding and removing vectored handlers, each walk through unreadable unwind data". The same at the head without `--cc` (the default compiler, `LONGSHOT_MINGW`'s clang). The control case (the walk made with the thread suspended, as before) hung in each of the four runs where it ran (two at 1b0c78fe, two at the head), after 0, 3, 43 and 0 of 400 samples. - The earlier round (on `main` @ f1f2dc5b): with the authored cases on this PR's first fix (f3ed9d4b, now 99cc86f3) 8 of 11 cases failed; at 186660c6 all 11 passed. They are unchanged since and pass at the head (above). - `host/mkw_glue.c` and `host/hos_crash_record.c` compiled `-fsyntax-only` with the host build's flags (llvm-mingw, `-fms-extensions`, `-march=native`) at the fix: no error. - `python -I -B tests/run_all.py --strict --changed origin/main` at the fix (2ddabf67, before the test's syntax-only compile got `-Wno-unused-function`; the host files are the head's): 5 passed, 7 failed, 0 skipped. Six of the 7 (`test_crash_record.py`, `test_crash_dialog.py`, `test_input_background.py`, `test_profiling_mode.py`, `test_renderer_new_handler.py`, `test_slow_frames.py`) fail on `main` @ 9dd41326 too, run by name in the same queue job; the seventh, `test_sampler_stack_walk.py`, stopped at that unused-function error and passes at the head (above). `test_crash_record.py` stops at a renderer source check before it builds the record, so the record's step is covered only by the syntax check and the walk test's source check. **Still to test:** - Windows 11, this PC (i7-9700, RTX 4060 (NVIDIA 610.88)): `HOS_PROFILE=1` in Castle Town's market, 120 s standing and turning, this PR and `main` alternated (A B B A A B), expecting no `CRASH:` line from the walk, a readable profile (`python -I scripts/perf.py report` on the run's profile folder), the time each sampled thread stays suspended, the sweeps a second and the stack depths on both sides (the game-free fixture in Measurements shows this PR slower than `main` there), and the frame-time tails about as on `main`, with `HOS_PROFILE=1` and with the slow-frame recorder (by hand, queued) - Linux: `python3 -I -B tests/test_sampler_stack_walk.py`, expecting the source checks to pass and "source only" (the walk is Windows' only); the host build (by hand) - Windows, other CPUs and GPUs (an AMD CPU; AMD and Intel GPUs): Castle Town's market for two minutes with `HOS_PROFILE=1`, this PR against `main`, expecting no crash on this PR's side (@Beanstalk play Castle Town's market for two minutes with HOS_PROFILE=1 on Windows PCs, this PR against main, and report any crash) ## Measurements **Verdict:** in the authored fixture the walk unwinds every stop of clang's AVX return suffix, and the stops this PR's first fix misread or faulted on (ret 16, lea through r12, jmp r11, no-access pages, a bad chain, a version 3 record) now unwind right or end the walk, and a sampled thread that holds the vectored-handler lock is resumed (400 of 400 samples) where walking it while suspended hung. (The earlier fixture's 8 wrong steps of 53 on `main` @ fc4a6769 stay at 0 of 53.) The cost, game-free: a sample is slower on this PR than on `main`, 13.30 against 9.00 us with 12 frames x 256 B and 26.60 against 10.50 us with 48 frames x 2048 B (4.30 and 16.10 us more), so the sweep rate falls from 111111 to 75188 and from 95238 to 37594 samples a second (32 % and 61 % fewer); the sampled thread is held suspended 7.90 against 6.80 us and 14.60 against 8.50 us. Only runs with the diagnostic sampling switches pay it (below). Not measured in play yet (Still to test). Setup: Windows 11, i7-9700, llvm-mingw clang 23.1.5; `python -I -B tests/test_sampler_stack_walk.py`, once a side through the PC's job queue. Baseline: this PR's earlier fixes with the tests that catch what they missed (the authored cases on the first fix, 99cc86f3, on `main` @ f1f2dc5b; the lock case on the second fix, 1b0c78fe, on `main` @ 9dd41326), as the bugs fixed here are in this PR's own earlier code. | | Before: this PR @ 99cc86f3 (row 1) and @ 1b0c78fe (row 2), with the new tests | After: this PR @ 2ee9b8f9 | |---|---|---| | `tests/test_sampler_stack_walk.py`: authored cases and the stepped AVX frame (99cc86f3) | 8 of 11 cases fail (3 of them exit 0xc0000005) | 11 of 11 pass; 53 of 53 stepped AVX stops unwound to the caller | | `tests/test_sampler_stack_walk.py` `sampler_lock`: samples of a thread adding and removing vectored handlers (1b0c78fe) | hung after 0 of 400 | 400 of 400, the thread running after | ``` FAIL: a jmp r11 in the body (no epilogue): step 1, rip 0, ... FAIL: ret 16: step 1, rsp ...fe8, want the walk ended or rsp ...ff8 sampler stack walk: 8 of 11 cases failed: avx_native (exit 0x1), ret_imm16 (exit 0x1), lea_sib (exit 0x1), version3 (exit 0x1), bad_chain (exit 0xc0000005), no_access_suffix (exit 0xc0000005), no_access_body (exit 0xc0000005), wrap (exit 0x1) FAIL: the sampler hung after 0 of 400 samples, the thread left suspended ok avx_suffix ... ok wrap (10 authored cases) 400 samples of a thread adding and removing vectored handlers, each walk through unreadable unwind data 53 steps of avx_frame unwound to its caller (7 of them pops, 1 the vzeroupper) PASS (runtime: every case ran): the stack walks step through unwind_step, under its fault guard, on the walked thread's stack ``` **The cost of a sample** (futondestroyer's 65450 and 67046: suspension time, sweep rate, stack depth). Setup: Windows 11, i7-9700, llvm-mingw clang 23.1.5 `-std=gnu11 -O2`; run alone on this PC on 2026-11-22 (02:13 UTC). Each checkout's walk helpers from `host/mkw_glue.c`, cut as `tests/test_sampler_stack_walk.py` cuts them, sample a thread of the harness's own: a chain of frames, each with its own unwind data, and a busy loop at the bottom. Two shapes: 12 frames x 256 B (about 4 KiB of stack) and 48 frames x 2048 B (about 100 KiB, near the copy's 128 KiB). 11 rounds of 300 samples per arm and shape, the arms interleaved and their order reversed every other round. "Suspended" is the time from `SuspendThread`'s return to the `ResumeThread` call (how long the sampler holds the thread); "sample" is the whole call. Each is the median of the rounds' medians, with the range of the round medians and the median of the rounds' p99s. "Frames" is the depth the walk reports; "sweep" is 1e6 / the sample median, samples a second for one thread and one sampler. The harness walks up to 128 frames; in the game the samplers stop at 16 (`HOS_SAMPLE_ALL`, the slow-frame recorder) or 48 (`HOS_SAMPLE`). The arms: - `main` @ f8c130b1 (this PR's merge base): suspend, take the context, walk the live stack frame by frame with main's `unwind_step`, resume. This is how the samplers sample on `main`. - this PR @ f6d9c754: `sample_stack`. It suspends the thread, takes the context, the stack's limits and a copy of the stack (at most 128 KiB) and resumes it; then it walks the copy. - head-susp: f6d9c754's unwinder walked while the thread is suspended, as on `main` (the test's `walk_suspended`). It has the same unwinder as this PR and no copy, so it splits the cost: this PR against head-susp is the copy's share, head-susp against `main` the unwinder's. | | `main` @ f8c130b1 | this PR @ f6d9c754 | head-susp (f6d9c754, walked while suspended) | |---|---|---|---| | 12 x 256 B: suspended, us (median, rounds, p99) | 6.80 (4.80 to 8.10), p99 52.30 | 7.90 (7.00 to 10.00), p99 45.90 | 7.40 (4.90 to 9.90), p99 48.90 | | 12 x 256 B: sample, us (median, rounds, p99) | 9.00 (6.30 to 12.00), p99 56.40 | 13.30 (11.30 to 25.50), p99 59.70 | 9.50 (6.20 to 16.10), p99 55.10 | | 12 x 256 B: frames; sweep, samples/s | 15; 111111 | 15; 75188 | 15; 105263 | | 48 x 2048 B: suspended, us (median, rounds, p99) | 8.50 (7.50 to 13.60), p99 52.10 | 14.60 (13.60 to 18.50), p99 57.90 | 11.00 (9.30 to 16.30), p99 50.70 | | 48 x 2048 B: sample, us (median, rounds, p99) | 10.50 (8.90 to 18.40), p99 58.30 | 26.60 (24.20 to 41.00), p99 88.40 | 13.00 (10.80 to 27.40), p99 52.50 | | 48 x 2048 B: frames; sweep, samples/s | 51; 95238 | 51; 37594 | 51; 76923 | ``` bench_sample_suspend: E:\LongshotTools\LongshotBuilder\tools\llvm-mingw\bin\clang.exe -std=gnu11 -O2; main E:/longshot-x86asm/pr-work/tmp/measure/f8c130b1, head E:/longshot-x86asm/pr-work/tmp/measure/f6d9c754; 11 rounds of 300 samples 12 frames x 256 B main suspended median 6.80 us (rounds 4.80 to 8.10), p99 52.30 | sample median 9.00 us (rounds 6.30 to 12.00), p99 56.40 | frames 15 | sweep 111111 samples/s 12 frames x 256 B head suspended median 7.90 us (rounds 7.00 to 10.00), p99 45.90 | sample median 13.30 us (rounds 11.30 to 25.50), p99 59.70 | frames 15 | sweep 75188 samples/s 12 frames x 256 B head-susp suspended median 7.40 us (rounds 4.90 to 9.90), p99 48.90 | sample median 9.50 us (rounds 6.20 to 16.10), p99 55.10 | frames 15 | sweep 105263 samples/s 48 frames x 2048 B main suspended median 8.50 us (rounds 7.50 to 13.60), p99 52.10 | sample median 10.50 us (rounds 8.90 to 18.40), p99 58.30 | frames 51 | sweep 95238 samples/s 48 frames x 2048 B head suspended median 14.60 us (rounds 13.60 to 18.50), p99 57.90 | sample median 26.60 us (rounds 24.20 to 41.00), p99 88.40 | frames 51 | sweep 37594 samples/s 48 frames x 2048 B head-susp suspended median 11.00 us (rounds 9.30 to 16.30), p99 50.70 | sample median 13.00 us (rounds 10.80 to 27.40), p99 52.50 | frames 51 | sweep 76923 samples/s ``` Where the cost comes from (12 x 256 B / 48 x 2048 B): - The copy (this PR against head-susp, same unwinder): +0.50 / +3.60 us suspended and +3.80 / +13.60 us a sample. `sample_stack` copies the whole stack from the stack pointer up, at most 128 KiB, while the thread is suspended, however few frames its caller walks (`host/mkw_glue.c:523-528`). Most of this share falls after the resume, in the walk in the copy. Reading the code does not explain that part: `copy_step`'s register remap (`:477-489`) is a few compares a step, and it was not measured apart. - The unwinder (head-susp against `main`, both walking while suspended): +0.50 / +2.50 us a sample. This covers the fault guard, set up for every step where once per walk would do (`unwind_step` calls `walk_guarded`, an `RtlCaptureContext` each step: `:467-473`, `:453-464`), and the AVX-suffix and `lea` decoders (`:395-450`). They were measured together, not apart. What that buys: the samplers no longer walk a thread while it is suspended. A fault in a step (a no-access page, unreadable unwind data) or a lock the walk takes can no longer wait on the suspended thread and hang both (`sample_stack`, `:508-545`; the `sampler_lock` case above). Every read the walk makes is bounded by the copy and its no-access guard (`:490-507`). The AVX return suffix and `lea rsp, [r12 + disp]` stops unwind right (`:395-418`). Who pays: only runs with the diagnostic sampling switches. These are `HOS_PROFILE=1` (which sets `HOS_SAMPLE_ALL`), `HOS_SAMPLE_ALL`, `HOS_SAMPLE` with `HOS_PROFILE_EVERY`, and `HOS_SLOW_FRAMES`, all off by default (`gpu/vk/switches.def:158`, `:172`, `:173`, `:186`). The samplers' threads start only in `hos_prof_start` (`host/mkw_glue.c:1112-1123`). The crash report and the crash record walk only after a crash, on the failing thread's own stack, with no copy (`:577`, `:674`). The renderer's hang dump (`RX_VK_HANG_DUMP`, off by default) has its own unwinder in `gpu/vk/vk_hangdump.cpp`, which this PR does not touch. Every run, profiled or not, pays one thing, not measured: `walk_fault` is first in the process's vectored-handler chain (`hos_commit_init` → `walk_init`, `:682`, `:330`). Each exception, a commit-on-touch fault included, first takes one thread-local read there (`:318-320`). ## Risks The change is in the stack walks only: the crash report's backtrace and the crash record's, `HOS_SAMPLE`, `HOS_SAMPLE_ALL` (`HOS_PROFILE`) and the slow-frame recorder. A walk that a check or the guard ends early gives a shorter backtrace or sample, as a refused step did before; a mistake in `unwind_avx_return` would show as wrong callers in a profile or a crash report, never in play without those switches (a crash walks only after the crash). The guard's handler is first in the process's vectored chain, in every run; on any exception it reads one thread-local and passes the exception on unless a step is running on that thread (not measured). The samplers no longer walk a suspended thread: while it is suspended, `sample_stack` makes only system calls (`GetThreadContext`, `NtQueryInformationThread`, `ReadProcessMemory`) and reads the thread's TEB, so a fault in a walk is dispatched with no thread suspended (before, one could wait for a lock the suspended thread held and hang both: the test's `sampler_lock` case hangs at 1b0c78fe). A suspension now costs the copy of the stack the thread uses, up to 128 KB: in the game-free fixture a sample takes 4.30 to 16.10 us more than on `main` and holds the thread 1.10 to 6.10 us longer (Measurements), with the diagnostic sampling switches only; not measured in play yet (Still to test). A stack deeper than the copy ends the sample there. The crash report and the crash record walk the failing thread's own stack, with no other thread suspended. The crash record without `hos_crash_record_unwinder` set (its test fixture) walks frame pointers. A revert is enough; players notice nothing. ## Checklist ### Ready for review - [x] One topic, on current `main`; the title is a Conventional Commit. - [ ] Tested on my own PC, in the game for a change the game runs, as Testing says. - [ ] `mise run test` passes (any failure that also fails on `main` is named). - [ ] Measured against `main`, or Measurements says why there is nothing to measure. - [x] No game files, build output or hand-edited generated files; `third_party/` untouched; nothing GPL-incompatible. ### When it applies - [x] A fix: a game-free test that fails on `main` and passes here. - [x] A check under `tests/` that reads changed source is updated, not weakened. - [ ] Host code builds on Windows (llvm-mingw) and Linux, with UTF-8 paths. - [x] AI assistance recorded with `Assisted-by:` / `Co-Authored-By:` trailers.
tests/test_sampler_stack_walk.py now also runs the walk, on Windows: a clang -mavx function with a large frame, on a
fresh thread's stack, is stepped one instruction at a time (the trap flag), and every step's context is unwound by
unwind_step, which must give the caller's frame with the callee-saved registers as they were; then a body step and an
epilogue step with their stack pointer moved near the stack's top must end the walk instead of faulting.

It fails at this commit, for issue 1584's reason: clang puts a vzeroupper between the epilogue's last pop and its
ret, Windows' unwinder does not take that for an epilogue, and a thread stopped among the pops is unwound as if in
the body: the prologue is undone again on a stack pointer the pops already moved, up to the frame's size too high.

Assisted-by: Claude Code
fix(host): the samplers' stack walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame
Some checks failed
PR description / Description follows the template (pull_request_target) Successful in 12s
Website / Website on Cloudflare (pull_request_target) Has been skipped
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
Guide screenshots / Guide images and local UI source review (pull_request) Has been cancelled
Third-party parts / As their notes say (pull_request) Has been cancelled
Third-party parts / The same as upstream (pull_request) Has been cancelled
7231d69ef1
Windows' unwinder knows an epilogue only as an add or lea to rsp, pops and a ret or jump; clang's AVX code has a
vzeroupper between the last pop and the ret, so a thread stopped among the pops was unwound as if in the body and the
prologue undone again on a stack pointer the pops had moved: it read up to the frame's size too high. Inside the stack
that gave the sample wrong callers; past its top it faulted in ntdll, in the sampler's thread, and took the game down
(issue 1584: HOS_PROFILE=1 and HOS_SAMPLE_ALL).

- unwind_epilogue: a frame stopped in its epilogue is unwound in the walk itself, Windows' rules plus the vzeroupper,
  with every pop and the return address checked on the walked thread's stack first.
- frame_on_stack: for every other frame, the reads RtlVirtualUnwind will make are worked out from the frame's unwind
  codes (the pushes, the saves at offsets, a chained entry's parents', the return address after a large allocation)
  and checked before the call, in place of the frame register's check alone.

tests/test_sampler_stack_walk.py passes: every step of the AVX frame unwinds to its caller.

Assisted-by: Claude Code
BeanBot left a comment

Recommendation: Request changes. The Windows fixture shows that the patch fixes the reported AVX unwind error. The new decoder can still fault while reading instructions or metadata, and it can mistake an in-function jump for a return and corrupt the backtrace.

Windows profiles and the legacy crash log can recover callers that were lost when Clang inserted vzeroupper before a return. The patch also adds a second interpretation of Windows unwind rules on every stack step, while the persisted crash record still uses its own unchecked walk.

Does it help: Yes for the reported fixture. On one Windows 11 i7-9700 run per side with llvm-mingw Clang 23.1.5, the test-only baseline at ed7462ec unwound 8 of 53 instruction stops incorrectly and the patch at 6a84dcc4 unwound all 53 correctly. The tested commits precede this rebase. The game fix and the cost of walking stacks while threads are suspended remain unproven in play.
Other systems: The Windows single-thread sampler, all-thread sampler, slow-frame recorder and legacy crash log share this helper. Shorter or wrong stacks also change the output of profile readers that consume those samples. Suspended game and renderer threads can see extra latency on any Windows GPU driver. The persisted crash record and renderer hang dump have separate Windows unwinders. Linux and Steam Deck use separate paths. The diff touches neither gameplay data, saves, audio, input, renderer APIs nor sample formats.
Switches: No game switches added, changed or removed. The existing profiling and slow-frame defaults stay off. The Windows test adds -mavx unconditionally for its runtime fixture, which needs a runtime feature check or a baseline-safe fixture.

Reviewed: 7231d69ef1 against 2e1f6c32d3: Read host/mkw_glue.c and tests/test_sampler_stack_walk.py in full, both commits and their diff, AGENTS.md, CONTRIBUTING.md, the Forgejo template and docs/dev/standards.md. No repository review checklist was present. Traced the sampler startup and callers, slow-frame consumer, fiber switch, separate crash writer and test runner in the relevant sections. Skimmed CI and related test contracts. Read the reported runs and the supplied comments and reviews, which were empty. The two historical run commits were unavailable locally. No recorded run artifacts, translations or generated files were changed.; nothing run (a code review).
Checked and fine:

  • Both commits have Assisted-by: trailers. The patch has one topic and changes no game-derived files, generated files, vendor code, shaders or renderer API definitions.
  • The measured test-only commit keeps the baseline source assertions, so the reported baseline failure reached the behavioral test. The regression fixture checks caller PC, SP and restored nonvolatile integer registers.
  • The new production code is guarded by _WIN32 and introduces no production path handling, allocations, shared caches or per-thread allocations. The test uses a temporary directory and adds no downloads or writes to the checkout.
  • The base update from fc4a6769 to 2e1f6c32 does not touch either changed file. git diff --check was clean.

Blocking (to change before merge)

  1. host/mkw_glue.c:355: The decoder fetches instruction bytes without checking the function end or whether the bytes are readable. A corrupted saved RIP can land on a byte that looks like an instruction prefix at the end of a mapped code page, and the decoder then reads into the next page. The pop scan has no end bound either. Bound every fetch by the runtime function and use fault-safe reads or a guarded unwind so an unreadable instruction ends the walk.
  2. host/mkw_glue.c:384: Jumping outside one runtime-function entry does not establish a tail call. A branch from a hot range into a chained cold range of the same function can leave its frame allocated. This decoder would then read a local stack slot as the return address. The indirect-jump check also accepts any REX prefix and any addressing mode, including a register-indirect jump-table dispatch through r11. Restrict the custom path to the affected AVX return sequence and leave ordinary branches to a guarded native unwinder.
  3. host/mkw_glue.c:363: The lea decoder treats the ModRM r/m field as the entire memory operand. With r12 as the frame register, lea rsp,[r12+0x58] has a SIB byte before the displacement. The code takes the SIB as the displacement and reads 0x58 as a pop rax, so a valid-looking suffix restores registers and RIP from the wrong addresses. Decode the complete operand or decline this form and use a guarded fallback.
  4. host/mkw_glue.c:390: The decoder indexes and writes separate CONTEXT members through &ctx->Rax as though the members were elements of a C array. A pop r15 writes through a pointer past the Rax object, which is undefined even with the expected Windows layout. Use named members or an explicit register-to-member mapping for this write and the frame-register reads.
  5. host/mkw_glue.c:463: The preflight checks one interpretation of the unwind codes and then lets Windows choose a potentially different unwind path. For example, a version-2 record can describe an epilogue through UWOP_EPILOG, which this code discards while it validates body reads. It also accepts unknown ops and dereferences chained metadata before verifying that the record is readable. An invalid chain can fault in the preflight itself. Use a fault-contained Windows step outside the narrow AVX case, or stop on records the preflight cannot validate and handle exactly. A guarded native step would also avoid interpreting each ordinary frame twice.
  6. host/mkw_glue.c:340: The old on_stack check still accepts an RSP of UINT64_MAX - 7 because p + 8 wraps. The new range check also establishes only numeric containment. A save slot in a no-access page inside the recorded stack interval passes it and is then dereferenced. Use the subtraction-based check for the first and final RSP too, and contain faults from actual stack reads.
  7. host/mkw_glue.c:313: The stack-range lookup this safety check relies on has an existing first-use race. Both samplers can run when HOS_SAMPLE and HOS_PROFILE are enabled. They can enter thread_stack together and race on the plain looked and query globals. Resolve the function before starting the sampler threads and publish it with thread creation, so neither sampler needs to initialize it with another thread suspended.
  8. host/mkw_glue.c:309: The persisted crash record still unwinds before the changed legacy log path. record_exception calls hos_crash_record_write, whose host_stack in host/hos_crash_record.c directly calls RtlVirtualUnwind. A crash with the same bad saved frame can fault there before the new checks run. Route the persisted record through a fault-contained step as well, or give it a safe partial backtrace when the frame cannot be read.
  9. tests/test_sampler_stack_walk.py:164: A compiler that puts vzeroupper before the pops can pass without testing the bug. The shape check prints a note and still reports success, so reverting the AVX-specific logic can go unnoticed on that compiler. Use an authored Windows fixture with the exact epilogue and assert that the walk reaches it. Keep the compiler-generated frame as additional coverage if useful.
  10. tests/test_sampler_stack_walk.py:144: The out-of-range cases cover the large allocation, pushes, return address and empty range. They cannot catch a broken offset-save check or a skipped parent in a chain. Add independent runtime cases with known saved integer and XMM values, frame-register setup and chained records. Put the individual read under test across an inaccessible boundary so removing its check fails the test.
  11. tests/test_sampler_stack_walk.py:206: The test executes an entire binary built with -mavx after checking only the compiler target. A Windows x64 PC or VM with AVX masked out can fail with an illegal instruction, even though Longshot supports lower CPU targets. Probe CPU and OS support in baseline code before launching an AVX executable, or exercise the decoder on an authored instruction sequence without executing AVX.
  12. tests/test_sampler_stack_walk.py:205: The newly compiled runtime case inherits a compiler selection that defaults to literal clang, and RUN_ALL_ARGS also supplies --cc clang. On Windows with CC pointing to llvm-mingw and another Clang first on PATH, the documented command and the suite can use the wrong target and silently skip the runtime case. Honor CC when --cc is absent and report source-only and runtime passes separately.

Waiting on the author (a run, a measurement or a decision; no edit does it)

  • The required own-PC in-game test was missing when the PR opened. Run the fixed head against the merge base in the reported Windows profiling scenario, verify the captures can be read, and record the affected Tier 1 results. Record the Linux source check and host build, and provide the head lint, full test and CI results with any remaining baseline failures identified.
  • Extra unwind work happens while each Windows target thread is suspended. A deeper renderer or game stack can stretch suspension time and worsen frame pacing even if sweep frequency looks unchanged. After reducing the duplicate work, report interleaved base/head runs with suspension time, sweeps per second, stack-depth distribution and frame-time tails for profiling and slow-frame capture.

Testing: Read-only review. No builds, tests or project scripts were run. The prior Windows changed-check run reports 6 passes and 4 failures also seen on the older baseline. No in-game run, current-head result or Linux run was supplied.
Overlaps and merge order: None found in the supplied review history or local checkout. #1343 is the merged predecessor.


Automated code review by BeanBot (gpt-6.2-sol), on the pull request's opening. Nothing was run; a maintainer decides.

**Recommendation: Request changes.** The Windows fixture shows that the patch fixes the reported AVX unwind error. The new decoder can still fault while reading instructions or metadata, and it can mistake an in-function jump for a return and corrupt the backtrace. Windows profiles and the legacy crash log can recover callers that were lost when Clang inserted `vzeroupper` before a return. The patch also adds a second interpretation of Windows unwind rules on every stack step, while the persisted crash record still uses its own unchecked walk. **Does it help:** Yes for the reported fixture. On one Windows 11 i7-9700 run per side with llvm-mingw Clang 23.1.5, the test-only baseline at ed7462ec unwound 8 of 53 instruction stops incorrectly and the patch at 6a84dcc4 unwound all 53 correctly. The tested commits precede this rebase. The game fix and the cost of walking stacks while threads are suspended remain unproven in play. **Other systems:** The Windows single-thread sampler, all-thread sampler, slow-frame recorder and legacy crash log share this helper. Shorter or wrong stacks also change the output of profile readers that consume those samples. Suspended game and renderer threads can see extra latency on any Windows GPU driver. The persisted crash record and renderer hang dump have separate Windows unwinders. Linux and Steam Deck use separate paths. The diff touches neither gameplay data, saves, audio, input, renderer APIs nor sample formats. **Switches:** No game switches added, changed or removed. The existing profiling and slow-frame defaults stay off. The Windows test adds `-mavx` unconditionally for its runtime fixture, which needs a runtime feature check or a baseline-safe fixture. **Reviewed:** 7231d69ef136 against 2e1f6c32d30e: Read host/mkw_glue.c and tests/test_sampler_stack_walk.py in full, both commits and their diff, AGENTS.md, CONTRIBUTING.md, the Forgejo template and docs/dev/standards.md. No repository review checklist was present. Traced the sampler startup and callers, slow-frame consumer, fiber switch, separate crash writer and test runner in the relevant sections. Skimmed CI and related test contracts. Read the reported runs and the supplied comments and reviews, which were empty. The two historical run commits were unavailable locally. No recorded run artifacts, translations or generated files were changed.; nothing run (a code review). **Checked and fine:** - Both commits have `Assisted-by:` trailers. The patch has one topic and changes no game-derived files, generated files, vendor code, shaders or renderer API definitions. - The measured test-only commit keeps the baseline source assertions, so the reported baseline failure reached the behavioral test. The regression fixture checks caller PC, SP and restored nonvolatile integer registers. - The new production code is guarded by `_WIN32` and introduces no production path handling, allocations, shared caches or per-thread allocations. The test uses a temporary directory and adds no downloads or writes to the checkout. - The base update from fc4a6769 to 2e1f6c32 does not touch either changed file. `git diff --check` was clean. **Blocking** (to change before merge) 1. host/mkw_glue.c:355: The decoder fetches instruction bytes without checking the function end or whether the bytes are readable. A corrupted saved RIP can land on a byte that looks like an instruction prefix at the end of a mapped code page, and the decoder then reads into the next page. The pop scan has no end bound either. Bound every fetch by the runtime function and use fault-safe reads or a guarded unwind so an unreadable instruction ends the walk. 2. host/mkw_glue.c:384: Jumping outside one runtime-function entry does not establish a tail call. A branch from a hot range into a chained cold range of the same function can leave its frame allocated. This decoder would then read a local stack slot as the return address. The indirect-jump check also accepts any REX prefix and any addressing mode, including a register-indirect jump-table dispatch through r11. Restrict the custom path to the affected AVX return sequence and leave ordinary branches to a guarded native unwinder. 3. host/mkw_glue.c:363: The `lea` decoder treats the ModRM r/m field as the entire memory operand. With r12 as the frame register, `lea rsp,[r12+0x58]` has a SIB byte before the displacement. The code takes the SIB as the displacement and reads `0x58` as a `pop rax`, so a valid-looking suffix restores registers and RIP from the wrong addresses. Decode the complete operand or decline this form and use a guarded fallback. 4. host/mkw_glue.c:390: The decoder indexes and writes separate `CONTEXT` members through `&ctx->Rax` as though the members were elements of a C array. A `pop r15` writes through a pointer past the Rax object, which is undefined even with the expected Windows layout. Use named members or an explicit register-to-member mapping for this write and the frame-register reads. 5. host/mkw_glue.c:463: The preflight checks one interpretation of the unwind codes and then lets Windows choose a potentially different unwind path. For example, a version-2 record can describe an epilogue through `UWOP_EPILOG`, which this code discards while it validates body reads. It also accepts unknown ops and dereferences chained metadata before verifying that the record is readable. An invalid chain can fault in the preflight itself. Use a fault-contained Windows step outside the narrow AVX case, or stop on records the preflight cannot validate and handle exactly. A guarded native step would also avoid interpreting each ordinary frame twice. 6. host/mkw_glue.c:340: The old `on_stack` check still accepts an RSP of `UINT64_MAX - 7` because `p + 8` wraps. The new range check also establishes only numeric containment. A save slot in a no-access page inside the recorded stack interval passes it and is then dereferenced. Use the subtraction-based check for the first and final RSP too, and contain faults from actual stack reads. 7. host/mkw_glue.c:313: The stack-range lookup this safety check relies on has an existing first-use race. Both samplers can run when `HOS_SAMPLE` and `HOS_PROFILE` are enabled. They can enter `thread_stack` together and race on the plain `looked` and `query` globals. Resolve the function before starting the sampler threads and publish it with thread creation, so neither sampler needs to initialize it with another thread suspended. 8. host/mkw_glue.c:309: The persisted crash record still unwinds before the changed legacy log path. `record_exception` calls `hos_crash_record_write`, whose `host_stack` in host/hos_crash_record.c directly calls `RtlVirtualUnwind`. A crash with the same bad saved frame can fault there before the new checks run. Route the persisted record through a fault-contained step as well, or give it a safe partial backtrace when the frame cannot be read. 9. tests/test_sampler_stack_walk.py:164: A compiler that puts `vzeroupper` before the pops can pass without testing the bug. The shape check prints a note and still reports success, so reverting the AVX-specific logic can go unnoticed on that compiler. Use an authored Windows fixture with the exact epilogue and assert that the walk reaches it. Keep the compiler-generated frame as additional coverage if useful. 10. tests/test_sampler_stack_walk.py:144: The out-of-range cases cover the large allocation, pushes, return address and empty range. They cannot catch a broken offset-save check or a skipped parent in a chain. Add independent runtime cases with known saved integer and XMM values, frame-register setup and chained records. Put the individual read under test across an inaccessible boundary so removing its check fails the test. 11. tests/test_sampler_stack_walk.py:206: The test executes an entire binary built with `-mavx` after checking only the compiler target. A Windows x64 PC or VM with AVX masked out can fail with an illegal instruction, even though Longshot supports lower CPU targets. Probe CPU and OS support in baseline code before launching an AVX executable, or exercise the decoder on an authored instruction sequence without executing AVX. 12. tests/test_sampler_stack_walk.py:205: The newly compiled runtime case inherits a compiler selection that defaults to literal `clang`, and `RUN_ALL_ARGS` also supplies `--cc clang`. On Windows with `CC` pointing to llvm-mingw and another Clang first on PATH, the documented command and the suite can use the wrong target and silently skip the runtime case. Honor `CC` when `--cc` is absent and report source-only and runtime passes separately. **Waiting on the author** (a run, a measurement or a decision; no edit does it) - The required own-PC in-game test was missing when the PR opened. Run the fixed head against the merge base in the reported Windows profiling scenario, verify the captures can be read, and record the affected Tier 1 results. Record the Linux source check and host build, and provide the head lint, full test and CI results with any remaining baseline failures identified. - Extra unwind work happens while each Windows target thread is suspended. A deeper renderer or game stack can stretch suspension time and worsen frame pacing even if sweep frequency looks unchanged. After reducing the duplicate work, report interleaved base/head runs with suspension time, sweeps per second, stack-depth distribution and frame-time tails for profiling and slow-frame capture. **Testing:** Read-only review. No builds, tests or project scripts were run. The prior Windows changed-check run reports 6 passes and 4 failures also seen on the older baseline. No in-game run, current-head result or Linux run was supplied. **Overlaps and merge order:** None found in the supplied review history or local checkout. #1343 is the merged predecessor. --- <sub>Automated code review by BeanBot (gpt-6.2-sol), on the pull request's opening. Nothing was run; a maintainer decides.</sub>
host/mkw_glue.c Outdated
@ -308,2 +308,2 @@
unable to fault rather than guarded: a step whose stack pointer, or frame register, is outside [lo, hi), the thread's
committed stack, ends the walk there, and the sample is only cut short */
unable to fault rather than guarded: a step that would read outside [lo, hi), the thread's committed stack, ends the walk
there, and the sample is only cut short. What RtlVirtualUnwind will read is worked out from the frame's unwind codes
Member

The persisted crash writer runs first and has its own unchecked RtlVirtualUnwind in host/hos_crash_record.c. Give that path a safe step or a safe partial trace too.

The persisted crash writer runs first and has its own unchecked `RtlVirtualUnwind` in `host/hos_crash_record.c`. Give that path a safe step or a safe partial trace too.
@ -310,3 +310,4 @@
first (frame_on_stack), and an epilogue is unwound here instead (unwind_epilogue) */
typedef struct { uint64_t lo, hi; } StackRange;
/* a thread's committed stack (its TEB's StackLimit to StackBase), read while it is suspended; {0, 0} when it can't be */
static StackRange thread_stack(HANDLE th) {
Member

Both samplers can enter this existing lazy lookup at once. Resolve and publish query before starting the sampler threads.

Both samplers can enter this existing lazy lookup at once. Resolve and publish `query` before starting the sampler threads.
host/mkw_glue.c Outdated
@ -337,6 +338,111 @@ static StackRange own_stack(void) {
return r;
}
static int on_stack(StackRange s, uint64_t p) { return p >= s.lo && p + 8 <= s.hi; }
Member

p + 8 can wrap and accept a corrupt RSP. Reuse span_on here and make actual stack reads fail cleanly on inaccessible pages inside the interval.

`p + 8` can wrap and accept a corrupt RSP. Reuse `span_on` here and make actual stack reads fail cleanly on inaccessible pages inside the interval.
host/mkw_glue.c Outdated
@ -340,0 +352,4 @@
const BYTE *b = (const BYTE *)ctx->Rip;
uint64_t rsp = ctx->Rsp;
int32_t d;
if (b[0] == 0x48 && (b[1] == 0x83 || b[1] == 0x81) && b[2] == 0xc4) { /* add rsp, imm8 / imm32 */
Member

Bound every instruction fetch by the function end and handle unreadable pages. A saved RIP near a page boundary can make this lookahead or the unbounded pop scan fault.

Bound every instruction fetch by the function end and handle unreadable pages. A saved RIP near a page boundary can make this lookahead or the unbounded pop scan fault.
host/mkw_glue.c Outdated
@ -340,0 +360,4 @@
b += len;
} else if ((b[0] & 0xfe) == 0x48 && b[1] == 0x8d && frame_reg && ((b[0] & 1u) << 3 | (b[2] & 7u)) == frame_reg &&
((b[2] & 0xf8) == 0x60 || (b[2] & 0xf8) == 0xa0)) { /* lea rsp, [frame register + disp8 / disp32] */
const int len = (b[2] & 0xf8) == 0x60 ? 4 : 7;
Member

An r12-based LEA has a SIB byte before its displacement. With a displacement of 0x58 this consumes the SIB as the offset and the displacement as an extra pop.

An r12-based LEA has a SIB byte before its displacement. With a displacement of 0x58 this consumes the SIB as the offset and the displacement as an extra pop.
host/mkw_glue.c Outdated
@ -340,0 +381,4 @@
int64_t to = (int64_t)((uint64_t)b - image) + (b[0] == 0xeb ? 2 : 5);
if (b[0] == 0xeb) to += (int8_t)b[1];
else memcpy(&d, b + 1, 4), to += d;
out = to <= (int64_t)f->BeginAddress || to >= (int64_t)f->EndAddress;
Member

A jump outside this RUNTIME_FUNCTION can enter a chained range of the same function with the frame still allocated. The indirect mask also accepts register dispatch. Keep custom emulation to the AVX return suffix.

A jump outside this RUNTIME_FUNCTION can enter a chained range of the same function with the frame still allocated. The indirect mask also accepts register dispatch. Keep custom emulation to the AVX return suffix.
host/mkw_glue.c Outdated
@ -340,0 +387,4 @@
if (!span_on(s, rsp, 8 * (n + 1))) return -1;
for (b = pops; b < popped; rsp += 8) {
const int rex = (b[0] & 0xf0) == 0x40;
reg[rex ? (b[0] & 1u) << 3 | (b[1] & 7u) : b[0] & 7u] = *(const uint64_t *)rsp;
Member

Indexing from &ctx->Rax crosses distinct C struct members. Use named members or a register-to-member mapping for the restores and frame-register reads.

Indexing from `&ctx->Rax` crosses distinct C struct members. Use named members or a register-to-member mapping for the restores and frame-register reads.
host/mkw_glue.c Outdated
@ -354,0 +460,4 @@
const int epilogue = unwind_epilogue(ctx, s, image, f, info[3] & 15);
if (epilogue) return epilogue > 0 && (on_stack(s, ctx->Rsp) || !ctx->Rip);
}
if (!frame_on_stack(ctx, s, image, rf)) return 0;
Member

A body preflight does not cover native epilogue handling driven by version-2 metadata. The chain reads themselves can fault too. Contain the native unwind or fail closed on records this code cannot validate exactly.

A body preflight does not cover native epilogue handling driven by version-2 metadata. The chain reads themselves can fault too. Contain the native unwind or fail closed on records this code cannot validate exactly.
@ -53,0 +141,4 @@
const StackRange s = own_stack();
CONTEXT b = body_ctx;
b.Rsp = s.hi - 0x100;
if (unwind_step(&b, s)) return 14;
Member

These bounds cases leave offset saves, XMM reads, frame-register setup and chained entries untested. Exercise each with a known context and a protected boundary.

These bounds cases leave offset saves, XMM reads, frame-register setup and chained entries untested. Exercise each with a known context and a protected boundary.
@ -53,0 +161,4 @@
int vzero = 0; /* (the shape this is about: pops, vzeroupper, ret) */
for (const BYTE *b = (const BYTE *)begin; b + 5 <= (const BYTE *)end; b++)
vzero |= (b[0] & 0xf8) == 0x58 && b[1] == 0xc5 && b[2] == 0xf8 && b[3] == 0x77 && b[4] == 0xc3;
if (!vzero) printf("note: this compiler's avx_frame has no vzeroupper between its pops and its ret\n");
Member

This can pass on a compiler that never emits the affected epilogue. Use a fixture with a guaranteed pop, vzeroupper and return sequence.

This can pass on a compiler that never emits the affected epilogue. Use a fixture with a guaranteed pop, vzeroupper and return sequence.
@ -53,0 +162,4 @@
for (const BYTE *b = (const BYTE *)begin; b + 5 <= (const BYTE *)end; b++)
vzero |= (b[0] & 0xf8) == 0x58 && b[1] == 0xc5 && b[2] == 0xf8 && b[3] == 0x77 && b[4] == 0xc3;
if (!vzero) printf("note: this compiler's avx_frame has no vzeroupper between its pops and its ret\n");
AddVectoredExceptionHandler(1, on_step);
Member

Check handler registration and the thread wait and exit-code calls. Remove the handler and close the handle on completion so setup failures produce a clear test error.

Check handler registration and the thread wait and exit-code calls. Remove the handler and close the handle on completion so setup failures produce a clear test error.
@ -72,0 +202,4 @@
return
exe = Path(tmp) / "walk_steps.exe"
run = Path(tmp) / "walk_steps.c"
run.write_text(helpers(src) + "static uint64_t prologue_size;\n" + DRIVER, encoding="utf-8")
Member

Honor CC unless --cc is explicit. With a different Clang on PATH, the Windows runtime check can otherwise be skipped and still print PASS.

Honor `CC` unless `--cc` is explicit. With a different Clang on PATH, the Windows runtime check can otherwise be skipped and still print PASS.
@ -72,0 +203,4 @@
exe = Path(tmp) / "walk_steps.exe"
run = Path(tmp) / "walk_steps.c"
run.write_text(helpers(src) + "static uint64_t prologue_size;\n" + DRIVER, encoding="utf-8")
r = subprocess.run([cc, "-std=gnu11", "-O2", "-mavx", "-Wall", "-Werror", "-Wno-unused-function", str(run), "-o",
Member

Check AVX availability before executing an AVX binary, or use a baseline-safe fixture that decodes the instruction bytes without executing them.

Check AVX availability before executing an AVX binary, or use a baseline-safe fixture that decodes the instruction bytes without executing them.
futondestroyer left a comment

Recommendation: Request changes. The Windows fixture supports fixing the AVX epilogue case. The new code also takes over ordinary epilogues and interprets unwind records it does not understand, so the walk can still produce wrong caller frames.

Does it help: Yes in the author's earlier Windows fixture. The baseline recorded 8 wrong steps out of 53, and the patch recorded 0 out of 53. The author reports that the rebase preserved the diff. Exact-head gameplay and time spent with each sampled thread suspended are still unmeasured.

Reviewed: 7231d69ef136e2696108dc53de3067479847c54d against merge base 2e1f6c32d30ec3582093743a968c8447bb435962. Queried verified revision-matched Graphify maps for unwind_step and checked its callers in source. Read both changed files' diffs and the test and CI evidence. This was a source review.

Checked and fine: The test checks the caller PC, SP and nonvolatile integer registers across instruction stops. Both commits have assistance trailers. No new switches or public formats. Linux uses a separate unwind path. On Windows the single-thread sampler, the all-thread sampler, slow-frame capture, and the legacy crash log all use this helper, including when their walks enter Windows or driver modules.

Blocking

  1. host/mkw_glue.c:378 recognizes opcode 0xc2 (ret imm16), but the success path at line 394 advances RSP by eight bytes only. If the stop is on a ret 16, the next step receives an RSP 16 bytes below the caller's actual stack pointer and may publish a wrong frame. Limit the custom handler to the reported vzeroupper followed by plain ret and keep other cases on a fault-contained native path, or correctly decode and validate the full adjustment.
  2. host/mkw_glue.c:459 enters the custom decoder without checking the unwind-record version. The helper treats the fourth byte as a frame-register/offset field and the preflight treats the payload as two-byte unwind slots. In valid V3 records those fields carry operation/epilogue counts and a different payload layout. The sampler walks into loaded modules, whose unwind format can differ from the game's toolchain. Gate the custom decoder on the supported record format before interpreting these fields, including chained records. Use a fault-contained native step or stop the walk for an unsupported format. Microsoft x64 unwind information V3

These are additional cases for the narrower handler already suggested in the existing exact-head review.

Testing: The earlier authored changed-check run had six passes and four shared baseline failures. The exact-head Forgejo description check passed, with source and workflow checks pending in the review snapshot. After the source changes, verify the exact-head AVX fixture, include negative cases for ordinary returns and unsupported unwind records, and measure stack-walk suspension cost in the reported Windows gameplay scenario. The existing Windows Market request can check profiling behavior on another CPU/GPU after that; it cannot establish unwind semantics by itself.

Overlaps and merge order: #1343 is the merged predecessor. #1947 makes handwritten Windows unwind records relevant to future coverage. This PR does not require the assembly kit.

**Recommendation: Request changes.** The Windows fixture supports fixing the AVX epilogue case. The new code also takes over ordinary epilogues and interprets unwind records it does not understand, so the walk can still produce wrong caller frames. **Does it help:** Yes in the author's earlier Windows fixture. The baseline recorded 8 wrong steps out of 53, and the patch recorded 0 out of 53. The author reports that the rebase preserved the diff. Exact-head gameplay and time spent with each sampled thread suspended are still unmeasured. **Reviewed:** `7231d69ef136e2696108dc53de3067479847c54d` against merge base `2e1f6c32d30ec3582093743a968c8447bb435962`. Queried verified revision-matched Graphify maps for `unwind_step` and checked its callers in source. Read both changed files' diffs and the test and CI evidence. This was a source review. **Checked and fine:** The test checks the caller PC, SP and nonvolatile integer registers across instruction stops. Both commits have assistance trailers. No new switches or public formats. Linux uses a separate unwind path. On Windows the single-thread sampler, the all-thread sampler, slow-frame capture, and the legacy crash log all use this helper, including when their walks enter Windows or driver modules. **Blocking** 1. `host/mkw_glue.c:378` recognizes opcode `0xc2` (`ret imm16`), but the success path at line 394 advances RSP by eight bytes only. If the stop is on a `ret 16`, the next step receives an RSP 16 bytes below the caller's actual stack pointer and may publish a wrong frame. Limit the custom handler to the reported `vzeroupper` followed by plain `ret` and keep other cases on a fault-contained native path, or correctly decode and validate the full adjustment. 2. `host/mkw_glue.c:459` enters the custom decoder without checking the unwind-record version. The helper treats the fourth byte as a frame-register/offset field and the preflight treats the payload as two-byte unwind slots. In valid V3 records those fields carry operation/epilogue counts and a different payload layout. The sampler walks into loaded modules, whose unwind format can differ from the game's toolchain. Gate the custom decoder on the supported record format before interpreting these fields, including chained records. Use a fault-contained native step or stop the walk for an unsupported format. [Microsoft x64 unwind information V3](https://learn.microsoft.com/en-us/cpp/build/x64-unwind-information-v3) These are additional cases for the narrower handler already suggested in the [existing exact-head review](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61976). **Testing:** The earlier authored changed-check run had six passes and four shared baseline failures. The exact-head Forgejo description check passed, with source and workflow checks pending in the review snapshot. After the source changes, verify the exact-head AVX fixture, include negative cases for ordinary returns and unsupported unwind records, and measure stack-walk suspension cost in the reported Windows gameplay scenario. The existing Windows Market request can check profiling behavior on another CPU/GPU after that; it cannot establish unwind semantics by itself. **Overlaps and merge order:** [#1343](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1343) is the merged predecessor. [#1947](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1947) makes handwritten Windows unwind records relevant to future coverage. This PR does not require the assembly kit.
host/mkw_glue.c Outdated
@ -340,0 +375,4 @@
}
const BYTE *popped = b;
if (b[0] == 0xc5 && b[1] == 0xf8 && b[2] == 0x77) b += 3; /* vzeroupper (clang's, before the ret) */
int out = b[0] == 0xc3 || b[0] == 0xc2 || (b[0] == 0xf3 && b[1] == 0xc3) || /* ret, ret imm16, rep ret */
Member

This accepts RET imm16, but the success path restores RSP as return slot + 8. The next unwind step will use the wrong RSP for a nonzero immediate. Restrict the custom case to the affected vzeroupper + plain RET sequence, or decode and validate the full adjustment.

This accepts RET imm16, but the success path restores RSP as return slot + 8. The next unwind step will use the wrong RSP for a nonzero immediate. Restrict the custom case to the affected vzeroupper + plain RET sequence, or decode and validate the full adjustment.
host/mkw_glue.c Outdated
@ -351,3 +458,2 @@
const BYTE *info = (const BYTE *)(image + rf->UnwindData);
const unsigned frame_reg = info[3] & 15;
if (frame_reg && !on_stack(s, (&ctx->Rax)[frame_reg])) return 0;
if (ctx->Rip - image - rf->BeginAddress >= info[1]) { /* (past the prologue: an epilogue is run here) */
Member

Check the unwind-record version before using these byte positions. In version 3, info[3] holds op/epilogue counts and the payload has a different layout. An ordinary sampler step into a loaded module can therefore interpret counts as register numbers. Keep unsupported versions, including chained records, on a fault-contained native path or stop at that frame.

Check the unwind-record version before using these byte positions. In version 3, info[3] holds op/epilogue counts and the payload has a different layout. An ordinary sampler step into a loaded module can therefore interpret counts as register numbers. Keep unsupported versions, including chained records, on a fault-contained native path or stop at that frame.
siantm force-pushed fix/sampler-epilogue-unwind from 7231d69ef1
Some checks failed
PR description / Description follows the template (pull_request_target) Successful in 12s
Website / Website on Cloudflare (pull_request_target) Has been skipped
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
Guide screenshots / Guide images and local UI source review (pull_request) Has been cancelled
Third-party parts / As their notes say (pull_request) Has been cancelled
Third-party parts / The same as upstream (pull_request) Has been cancelled
to 186660c677
Some checks failed
Website / Website on Cloudflare (pull_request_target) Has been skipped
beanstalk/approval waiting for a BigBean's 👍 on the request
PR description / Description follows the template (pull_request_target) Successful in 5s
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
Guide screenshots / Guide images and local UI source review (pull_request) Has been cancelled
Third-party parts / As their notes say (pull_request) Has been cancelled
Third-party parts / The same as upstream (pull_request) Has been cancelled
Website / Website on Cloudflare (pull_request) Has been cancelled
2026-11-21 04:30:34 +00:00
Compare
siantm changed title from WIP: fix(host): the samplers' stack walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame to WIP: fix(host): the stack walks run clang's AVX return suffix themselves and every step under a fault guard 2026-11-21 04:31:20 +00:00
Author
Contributor

Thanks for the review (61976). The branch is rebased onto main @ f1f2dc5b (the two earlier commits unchanged, git range-diff), with the checks in f3ed9d4b and the fix in 186660c6; head 186660c6. Where futondestroyer's review asked for the same thing (a narrower handler), I followed it.

  1. 61963 bounded, fault-safe fetch: fixed in 186660c6. Every byte the decoder reads is inside the RUNTIME_FUNCTION's range (the pop scan stops at 16 pops or the range's end), and the whole step, decoder included, runs under a vectored fault guard that ends the walk on a fault.
  2. 61964 jumps: fixed in 186660c6. The custom path is only pops, vzeroupper, plain ret; no jump of any kind is taken there. The avx_native case stops on a jmp r11 in a body with its frame allocated: wrong at f3ed9d4b, the caller at this head.
  3. 61965 LEA with SIB: fixed in 186660c6 by not decoding lea any more (at the lea the body's unwind is still right, and Windows does it). The lea_sib case (lea rsp, [r12 + 0x58]) was unwound wrong at f3ed9d4b and gives the caller at this head, at the lea and at the pop after it.
  4. 61966 &ctx->Rax indexing: fixed in 186660c6: gpr() maps register numbers to CONTEXT's named members, for the pops and the frame register.
  5. 61967 preflight vs native: fixed in 186660c6: frame_on_stack is gone; ordinary frames take one guarded RtlVirtualUnwind, a record that is not version 1 or 2 ends the walk. The bad_chain case (a chain into unmapped unwind data) crashed at f3ed9d4b in the preflight and ends the walk at this head; version3 ends it too.
  6. 61968 wrap and no-access pages: fixed in 186660c6: on_stack is span_on (subtraction), and reads of a no-access page inside the range are contained by the guard. The wrap, no_access_suffix and no_access_body cases failed at f3ed9d4b (on_stack took UINT64_MAX - 7; the two no-access cases exited 0xc0000005) and pass at this head.
  7. 61969 lazy lookup race: fixed in 186660c6: walk_init resolves NtQueryInformationThread (and registers the guard) on the main thread in hos_commit_init and again before the samplers' CreateThreads in hos_prof_start; thread_stack only reads it. Checked by the test's source checks (no state in thread_stack, walk_init before the first CreateThread).
  8. 61970 the crash record's walk: fixed in 186660c6: host_stack steps through the same guarded unwind_step (set by hos_crash_record_unwinder at startup) and no longer calls RtlVirtualUnwind; without it (the record's own fixture) it walks frame pointers. Checked by a source check and tests/test_crash_record.py (which stops at a renderer source check before it builds the record, on main @ f1f2dc5b too, so here only a -fsyntax-only compile with the host flags covers the file); no runtime case puts a bad frame under the record.
  9. 61971 authored fixture: fixed in f3ed9d4b: epi_avx is assembled with the exact suffix and its own unwind data, and avx_suffix unwinds every stop on its pops and its vzeroupper (the compiler-made frame stays as extra coverage, and now fails if it has no vzeroupper stop).
  10. 61972 offset saves / XMM / frame register / chains: the checks these would cover (frame_on_stack) are removed in 186660c6, and the reads go to RtlVirtualUnwind under the guard. Covered instead: a frame-register frame (lea_sib), saves inside a protected page within the stack's range (no_access_body, which faults without the guard), and chained data (bad_chain). No case with XMM saves or a valid chain was added.
  11. 61973 AVX probe: fixed in f3ed9d4b: the authored cases are never executed; the compiler-made frame is target("avx") in a baseline build and runs only when CPUID and XGETBV report AVX (else "skip avx_steps").
  12. 61974 honour CC: fixed in f3ed9d4b: --cc, then CC, then LONGSHOT_MINGW's clang, then clang/gcc on PATH, as tests/test_fastfp_regions.py; RUN_ALL_ARGS dropped; the last line says "runtime" or "source only".
  • 61975 handler/wait/exit code: fixed in f3ed9d4b: the registration, the wait (120 s) and GetExitCodeThread are checked, the handler removed and the handle closed.

Checks (Windows 11, i7-9700, llvm-mingw clang 23.1.5, each through the PC's job queue): tests/test_sampler_stack_walk.py at f3ed9d4b fails 8 of 11 cases (avx_native, ret_imm16, lea_sib, version3, wrap; bad_chain, no_access_suffix, no_access_body exit 0xc0000005); at 186660c6 all 11 pass, "PASS (runtime: every case ran)", and the stepped AVX frame gives "53 steps of avx_frame unwound to its caller (7 of them pops, 1 the vzeroupper)", with --cc and with the default compiler. run_all.py --strict --changed origin/main at the head: 7 passed, 5 failed, the 5 (test_crash_record, test_crash_dialog, test_profiling_mode, test_renderer_new_handler, test_slow_frames) failing on main @ f1f2dc5b too. host/mkw_glue.c and host/hos_crash_record.c pass a -fsyntax-only compile with the host build's flags. Not run: the game.

Waiting on me: the gameplay A/B in Castle Town's market with the time each sampled thread stays suspended, sweeps a second, stack depths and frame-time tails (Still to test); the Linux check and host build; CI on this head.

Thanks for the review ([61976](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61976)). The branch is rebased onto `main` @ f1f2dc5b (the two earlier commits unchanged, `git range-diff`), with the checks in f3ed9d4b and the fix in 186660c6; head 186660c6. Where futondestroyer's review asked for the same thing (a narrower handler), I followed it. 1. [61963](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61963) bounded, fault-safe fetch: fixed in 186660c6. Every byte the decoder reads is inside the `RUNTIME_FUNCTION`'s range (the pop scan stops at 16 pops or the range's end), and the whole step, decoder included, runs under a vectored fault guard that ends the walk on a fault. 2. [61964](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61964) jumps: fixed in 186660c6. The custom path is only pops, `vzeroupper`, plain `ret`; no jump of any kind is taken there. The `avx_native` case stops on a `jmp r11` in a body with its frame allocated: wrong at f3ed9d4b, the caller at this head. 3. [61965](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61965) LEA with SIB: fixed in 186660c6 by not decoding `lea` any more (at the `lea` the body's unwind is still right, and Windows does it). The `lea_sib` case (`lea rsp, [r12 + 0x58]`) was unwound wrong at f3ed9d4b and gives the caller at this head, at the `lea` and at the pop after it. 4. [61966](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61966) `&ctx->Rax` indexing: fixed in 186660c6: `gpr()` maps register numbers to `CONTEXT`'s named members, for the pops and the frame register. 5. [61967](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61967) preflight vs native: fixed in 186660c6: `frame_on_stack` is gone; ordinary frames take one guarded `RtlVirtualUnwind`, a record that is not version 1 or 2 ends the walk. The `bad_chain` case (a chain into unmapped unwind data) crashed at f3ed9d4b in the preflight and ends the walk at this head; `version3` ends it too. 6. [61968](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61968) wrap and no-access pages: fixed in 186660c6: `on_stack` is `span_on` (subtraction), and reads of a no-access page inside the range are contained by the guard. The `wrap`, `no_access_suffix` and `no_access_body` cases failed at f3ed9d4b (`on_stack` took UINT64_MAX - 7; the two no-access cases exited 0xc0000005) and pass at this head. 7. [61969](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61969) lazy lookup race: fixed in 186660c6: `walk_init` resolves `NtQueryInformationThread` (and registers the guard) on the main thread in `hos_commit_init` and again before the samplers' `CreateThread`s in `hos_prof_start`; `thread_stack` only reads it. Checked by the test's source checks (no state in `thread_stack`, `walk_init` before the first `CreateThread`). 8. [61970](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61970) the crash record's walk: fixed in 186660c6: `host_stack` steps through the same guarded `unwind_step` (set by `hos_crash_record_unwinder` at startup) and no longer calls `RtlVirtualUnwind`; without it (the record's own fixture) it walks frame pointers. Checked by a source check and `tests/test_crash_record.py` (which stops at a renderer source check before it builds the record, on `main` @ f1f2dc5b too, so here only a `-fsyntax-only` compile with the host flags covers the file); no runtime case puts a bad frame under the record. 9. [61971](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61971) authored fixture: fixed in f3ed9d4b: `epi_avx` is assembled with the exact suffix and its own unwind data, and `avx_suffix` unwinds every stop on its pops and its `vzeroupper` (the compiler-made frame stays as extra coverage, and now fails if it has no `vzeroupper` stop). 10. [61972](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61972) offset saves / XMM / frame register / chains: the checks these would cover (`frame_on_stack`) are removed in 186660c6, and the reads go to `RtlVirtualUnwind` under the guard. Covered instead: a frame-register frame (`lea_sib`), saves inside a protected page within the stack's range (`no_access_body`, which faults without the guard), and chained data (`bad_chain`). No case with XMM saves or a valid chain was added. 11. [61973](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61973) AVX probe: fixed in f3ed9d4b: the authored cases are never executed; the compiler-made frame is `target("avx")` in a baseline build and runs only when CPUID and XGETBV report AVX (else "skip avx_steps"). 12. [61974](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61974) honour `CC`: fixed in f3ed9d4b: `--cc`, then `CC`, then `LONGSHOT_MINGW`'s clang, then clang/gcc on PATH, as `tests/test_fastfp_regions.py`; `RUN_ALL_ARGS` dropped; the last line says "runtime" or "source only". - [61975](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-61975) handler/wait/exit code: fixed in f3ed9d4b: the registration, the wait (120 s) and `GetExitCodeThread` are checked, the handler removed and the handle closed. Checks (Windows 11, i7-9700, llvm-mingw clang 23.1.5, each through the PC's job queue): `tests/test_sampler_stack_walk.py` at f3ed9d4b fails 8 of 11 cases (`avx_native`, `ret_imm16`, `lea_sib`, `version3`, `wrap`; `bad_chain`, `no_access_suffix`, `no_access_body` exit 0xc0000005); at 186660c6 all 11 pass, "PASS (runtime: every case ran)", and the stepped AVX frame gives "53 steps of avx_frame unwound to its caller (7 of them pops, 1 the vzeroupper)", with `--cc` and with the default compiler. `run_all.py --strict --changed origin/main` at the head: 7 passed, 5 failed, the 5 (`test_crash_record`, `test_crash_dialog`, `test_profiling_mode`, `test_renderer_new_handler`, `test_slow_frames`) failing on `main` @ f1f2dc5b too. `host/mkw_glue.c` and `host/hos_crash_record.c` pass a `-fsyntax-only` compile with the host build's flags. Not run: the game. Waiting on me: the gameplay A/B in Castle Town's market with the time each sampled thread stays suspended, sweeps a second, stack depths and frame-time tails (Still to test); the Linux check and host build; CI on this head.
Author
Contributor

@futondestroyer thanks for the review (62708). Fixed in 186660c6 (checks in f3ed9d4b), rebased onto main @ f1f2dc5b, head 186660c6:

  • 62706 (ret imm16): the walk now runs only the reported suffix itself: pops, vzeroupper (c5 f8 77), then a plain ret (c3), every byte inside the function's own range. ret imm16, jumps, the add/lea before the pops and epilogues without the vzeroupper go to RtlVirtualUnwind, which now runs under a fault guard (a vectored handler; a fault ends the walk). The test's ret_imm16 case (pop rbx, vzeroupper, ret 16) failed at f3ed9d4b (the old decoder gave an RSP 16 bytes low) and passes at this head; plain_return checks an ordinary pop/ret epilogue and its ret, left to Windows.
  • 62707 (record version): the custom path no longer reads the unwind record at all (only the RUNTIME_FUNCTION's range), and the preflight that interpreted the codes is gone. Before the native step, a record that is not version 1 or 2 ends the walk; chained parents are read by RtlVirtualUnwind under the guard. The test's version3 case (a hand-made version 3 record) and bad_chain case (a chain into unmapped unwind data) end the walk without a fault; at f3ed9d4b bad_chain crashed (exit 0xc0000005) in the old preflight and version3 returned a frame.

Checks (Windows 11, i7-9700, llvm-mingw clang 23.1.5, each through the PC's job queue): tests/test_sampler_stack_walk.py at f3ed9d4b fails 8 of 11 cases (avx_native, ret_imm16, lea_sib, version3, wrap; bad_chain, no_access_suffix, no_access_body exit 0xc0000005); at 186660c6 all 11 pass, "PASS (runtime: every case ran)", and the stepped AVX frame gives "53 steps of avx_frame unwound to its caller (7 of them pops, 1 the vzeroupper)", with --cc and with the default compiler. run_all.py --strict --changed origin/main at the head: 7 passed, 5 failed, the 5 (test_crash_record, test_crash_dialog, test_profiling_mode, test_renderer_new_handler, test_slow_frames) failing on main @ f1f2dc5b too. host/mkw_glue.c and host/hos_crash_record.c pass a -fsyntax-only compile with the host build's flags. Not run: the game.

Not done yet: the gameplay run with the time each sampled thread stays suspended (Still to test), the Linux check, Tier 1 and CI on this head.

@futondestroyer thanks for the review ([62708](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-62708)). Fixed in 186660c6 (checks in f3ed9d4b), rebased onto `main` @ f1f2dc5b, head 186660c6: - [62706](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-62706) (`ret imm16`): the walk now runs only the reported suffix itself: pops, `vzeroupper` (`c5 f8 77`), then a plain `ret` (`c3`), every byte inside the function's own range. `ret imm16`, jumps, the `add`/`lea` before the pops and epilogues without the `vzeroupper` go to `RtlVirtualUnwind`, which now runs under a fault guard (a vectored handler; a fault ends the walk). The test's `ret_imm16` case (pop rbx, vzeroupper, `ret 16`) failed at f3ed9d4b (the old decoder gave an RSP 16 bytes low) and passes at this head; `plain_return` checks an ordinary pop/ret epilogue and its `ret`, left to Windows. - [62707](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-62707) (record version): the custom path no longer reads the unwind record at all (only the `RUNTIME_FUNCTION`'s range), and the preflight that interpreted the codes is gone. Before the native step, a record that is not version 1 or 2 ends the walk; chained parents are read by `RtlVirtualUnwind` under the guard. The test's `version3` case (a hand-made version 3 record) and `bad_chain` case (a chain into unmapped unwind data) end the walk without a fault; at f3ed9d4b `bad_chain` crashed (exit 0xc0000005) in the old preflight and `version3` returned a frame. Checks (Windows 11, i7-9700, llvm-mingw clang 23.1.5, each through the PC's job queue): `tests/test_sampler_stack_walk.py` at f3ed9d4b fails 8 of 11 cases (`avx_native`, `ret_imm16`, `lea_sib`, `version3`, `wrap`; `bad_chain`, `no_access_suffix`, `no_access_body` exit 0xc0000005); at 186660c6 all 11 pass, "PASS (runtime: every case ran)", and the stepped AVX frame gives "53 steps of avx_frame unwound to its caller (7 of them pops, 1 the vzeroupper)", with `--cc` and with the default compiler. `run_all.py --strict --changed origin/main` at the head: 7 passed, 5 failed, the 5 (`test_crash_record`, `test_crash_dialog`, `test_profiling_mode`, `test_renderer_new_handler`, `test_slow_frames`) failing on `main` @ f1f2dc5b too. `host/mkw_glue.c` and `host/hos_crash_record.c` pass a `-fsyntax-only` compile with the host build's flags. Not run: the game. Not done yet: the gameplay run with the time each sampled thread stays suspended (Still to test), the Linux check, Tier 1 and CI on this head.
Author
Contributor

@Beanstalk This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. It has not run in the game on these PCs yet. Please play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides, the PR against main on the same PC, on Windows PCs with an AMD processor, with an AMD GPU, with an Intel GPU and with an NVIDIA GPU. The PR side must not crash (main may: that is the bug) and must write a readable profile (some stacks may be shorter); frame time p99 within main's run-to-run spread.

@Beanstalk This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. It has not run in the game on these PCs yet. Please play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides, the PR against main on the same PC, on Windows PCs with an AMD processor, with an AMD GPU, with an Intel GPU and with an NVIDIA GPU. The PR side must not crash (main may: that is the bug) and must write a readable profile (some stacks may be shorter); frame time p99 within main's run-to-run spread.
Member

@siantm only members of BigBeans can start the farm.

One of them can approve this request by reacting 👍 to it or to this comment. This request was for 186660c, and the PR has changed since (2ee9b8f), so a 👍 no longer approves it. Comment @Beanstalk again to ask for the new commit.

@siantm only members of `BigBeans` can start the farm. ~~One of them can approve this request by reacting 👍 to it or to this comment.~~ This request was for `186660c`, and the PR has changed since (`2ee9b8f`), so a 👍 no longer approves it. Comment `@Beanstalk` again to ask for the new commit.
Author
Contributor

Description: Risks now states the fault guard's worst case exactly. A fault inside a sampler's step is dispatched while the sampled thread is suspended. If that thread was holding the lock on the vectored-handler list, both threads hang; it is not only a delay. Risks also says what bounds it in this tree: handlers are added at start-up and later only by debugging switches, and none is removed. No code change; head stays 186660c6.

Description: Risks now states the fault guard's worst case exactly. A fault inside a sampler's step is dispatched while the sampled thread is suspended. If that thread was holding the lock on the vectored-handler list, both threads hang; it is not only a delay. Risks also says what bounds it in this tree: handlers are added at start-up and later only by debugging switches, and none is removed. No code change; head stays 186660c6.
futondestroyer left a comment

Recommendation — Request changes. The narrower AVX decoder and the new fixture address the prior return and unwind-record findings. A fault in a suspended-thread walk can still hang the game before the recovery handler runs.

Blocking

  1. host/mkw_glue.c:418 runs the potentially faulting step before either sampler reaches ResumeThread (lines 710 and 991). If the target was suspended while holding Windows' vectored-handler-list lock, dispatch of a fault such as the fixture's unreadable save slot waits for that target before invoking walk_fault. The sampler then never reaches the resume. Later handler registrations can still run on a sampled thread. For example, a guest thread can register the texture-upload watch handler on its first matching upload (host/nvn_native.c:930 and :984). A driver or overlay can also register handlers. The Risks update recognizes this deadlock. Keep the suspended interval free of fault dispatch and lock-taking unwind work. For example, capture a bounded stack snapshot using reads that report failure, resume the target, then walk the captured frames. Include unwind-table lookup in that boundary (unwind_step calls RtlLookupFunctionEntry before walk_guarded today). Add a timed regression that checks that a failed frame read still resumes a sampled thread when a lock needed by the walker is held. Windows guidance on SuspendThread · Author's risk update

Does it help? The author reports 11/11 Windows fixture cases passing at 186660c6 versus 3/11 at the previous implementation with the new test, and 53/53 correct stops in the compiled AVX frame. The custom path now accepts only pops followed by vzeroupper and plain ret, and the native path stops on unsupported unwind-record versions. No switches changed.

Testing The exact-head changed checks had seven passes and five failures also seen on the base. The crash record runtime check stopped before exercising the new callback. The branch remains WIP pending the Windows gameplay run, Linux source checks and host build, and the remaining test suite. For Windows, report the Market A/B with suspension time, sweep rate, stack depth and frame-time tails, plus the slow-frame path. Hold the existing Windows Test Farm request pending the source fix. Current CI is pending and the description check passed.

Reviewed Head 186660c677296995bb238f709523c4688f9313a5 against merge base f1f2dc5bd2821cef061798ba40a043d281ac1707, including the interdiff from 7231d69e. Queried revision-matched Graphify maps for the unwind on both sides, then checked the callers and indirect crash-record callback in source. Read all four changed files' diffs and the author evidence. No PR code was run. Prior review

**Recommendation — Request changes.** The narrower AVX decoder and the new fixture address the prior return and unwind-record findings. A fault in a suspended-thread walk can still hang the game before the recovery handler runs. **Blocking** 1. `host/mkw_glue.c:418` runs the potentially faulting step before either sampler reaches `ResumeThread` (lines 710 and 991). If the target was suspended while holding Windows' vectored-handler-list lock, dispatch of a fault such as the fixture's unreadable save slot waits for that target before invoking `walk_fault`. The sampler then never reaches the resume. Later handler registrations can still run on a sampled thread. For example, a guest thread can register the texture-upload watch handler on its first matching upload (host/nvn_native.c:930 and :984). A driver or overlay can also register handlers. The Risks update recognizes this deadlock. Keep the suspended interval free of fault dispatch and lock-taking unwind work. For example, capture a bounded stack snapshot using reads that report failure, resume the target, then walk the captured frames. Include unwind-table lookup in that boundary (`unwind_step` calls `RtlLookupFunctionEntry` before `walk_guarded` today). Add a timed regression that checks that a failed frame read still resumes a sampled thread when a lock needed by the walker is held. [Windows guidance on SuspendThread](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-suspendthread) · [Author's risk update](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-63502) **Does it help?** The author reports 11/11 Windows fixture cases passing at `186660c6` versus 3/11 at the previous implementation with the new test, and 53/53 correct stops in the compiled AVX frame. The custom path now accepts only pops followed by `vzeroupper` and plain `ret`, and the native path stops on unsupported unwind-record versions. No switches changed. **Testing** The exact-head changed checks had seven passes and five failures also seen on the base. The crash record runtime check stopped before exercising the new callback. The branch remains WIP pending the Windows gameplay run, Linux source checks and host build, and the remaining test suite. For Windows, report the Market A/B with suspension time, sweep rate, stack depth and frame-time tails, plus the slow-frame path. Hold the [existing Windows Test Farm request](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-63490) pending the source fix. Current CI is pending and the description check passed. **Reviewed** Head `186660c677296995bb238f709523c4688f9313a5` against merge base `f1f2dc5bd2821cef061798ba40a043d281ac1707`, including the interdiff from `7231d69e`. Queried revision-matched Graphify maps for the unwind on both sides, then checked the callers and indirect crash-record callback in source. Read all four changed files' diffs and the author evidence. No PR code was run. [Prior review](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-62708)
host/mkw_glue.c Outdated
@ -359,0 +415,4 @@
if (passes++) return 0; /* (back from walk_fault) */
walk_resume = &resume;
__atomic_signal_fence(__ATOMIC_SEQ_CST); /* (no read of the step's moved above this, nor below the end) */
const int stepped = step_frame(ctx, s, image, f);
Member

A step fault can block before walk_fault runs if the suspended target holds Windows' vectored-handler-list lock. Both callers reach ResumeThread only after this returns. Keep faulting reads and lock-taking unwind work outside that suspension window.

A step fault can block before walk_fault runs if the suspended target holds Windows' vectored-handler-list lock. Both callers reach ResumeThread only after this returns. Keep faulting reads and lock-taking unwind work outside that suspension window.
siantm force-pushed fix/sampler-epilogue-unwind from 186660c677
Some checks failed
Website / Website on Cloudflare (pull_request_target) Has been skipped
beanstalk/approval waiting for a BigBean's 👍 on the request
PR description / Description follows the template (pull_request_target) Successful in 5s
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
Guide screenshots / Guide images and local UI source review (pull_request) Has been cancelled
Third-party parts / As their notes say (pull_request) Has been cancelled
Third-party parts / The same as upstream (pull_request) Has been cancelled
Website / Website on Cloudflare (pull_request) Has been cancelled
to 2ee9b8f9ec
Some checks failed
PR description / Description follows the template (pull_request_target) Successful in 4s
beanstalk/approval waiting for a BigBean's 👍 on the request
Website / Website on Cloudflare (pull_request_target) Has been skipped
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
Guide screenshots / Guide images and local UI source review (pull_request) Has been cancelled
Third-party parts / As their notes say (pull_request) Has been cancelled
Third-party parts / The same as upstream (pull_request) Has been cancelled
Website / Website on Cloudflare (pull_request) Has been cancelled
2026-11-21 10:43:33 +00:00
Compare
Author
Contributor

@futondestroyer thanks for the second look (65451, 65450). Fixed in 2ee9b8f9 (test in 1b0c78fe), rebased onto main @ 9dd41326. The earlier commits are unchanged per git range-diff.

  • The samplers no longer walk a suspended thread. Both now call sample_stack. While the thread is suspended it takes only the context, the stack's limits (NtQueryInformationThread and the TEB) and a copy of the stack from the stack pointer up: at most 128 KB, through ReadProcessMemory, which returns a short copy at an unreadable page instead of faulting. Then it resumes the thread. The walk runs after that, in the copy: RtlLookupFunctionEntry, RtlVirtualUnwind, the fault guard, and the module lookups (GetModuleHandleExA), which also ran while the thread was suspended before. Each sampler thread has its own copy buffer.
  • Timed regression (sampler_lock in tests/test_sampler_stack_walk.py): a thread adds and removes a vectored handler in a loop. Its outer frame is a function whose unwind data chains into unmapped memory, so every walk through it faults. 400 samples must finish within 60 s, and the thread must still be running afterwards. At 1b0c78fe the samplers still walk while the thread is suspended, and the case hung after 0 of 400 samples (2 of 400 in an earlier run of the same test). At 2ee9b8f9 all 400 samples finish and the thread is still running; all 13 cases pass. A control case walks the same thread while it is suspended, as the samplers did before, and only reports what happened. It hung in all four runs, after 0, 3, 43 and 0 samples, so on this Windows 11 PC the hang you describe does happen.

Checks (Windows 11, i7-9700, llvm-mingw clang 23.1.5, through the PC's job queue): tests/test_sampler_stack_walk.py passes at 2ee9b8f9 ("PASS (runtime: every case ran)"), with --cc and with the default compiler. host/mkw_glue.c and host/hos_crash_record.c compile -fsyntax-only with the host build's flags. run_all.py --strict --changed origin/main at the fix: 5 passed and 7 failed. Six of the 7 also fail on main @ 9dd41326: test_crash_record, test_crash_dialog, test_input_background, test_profiling_mode, test_renderer_new_handler, test_slow_frames. The seventh was this test, which stopped at an unused-function warning in its compile-only step; that is fixed in 1b0c78fe, and the test passes at the head as above. Not run: the game.

Still not done, as you list: the Market A/B on Windows with suspension time, sweep rate, stack depth and frame-time tails, plus the slow-frame path; the Linux checks and host build; the rest of the suite. The Test Farm request stays on hold until then.

@futondestroyer thanks for the second look ([65451](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-65451), [65450](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-65450)). Fixed in 2ee9b8f9 (test in 1b0c78fe), rebased onto `main` @ 9dd41326. The earlier commits are unchanged per `git range-diff`. - The samplers no longer walk a suspended thread. Both now call `sample_stack`. While the thread is suspended it takes only the context, the stack's limits (`NtQueryInformationThread` and the TEB) and a copy of the stack from the stack pointer up: at most 128 KB, through `ReadProcessMemory`, which returns a short copy at an unreadable page instead of faulting. Then it resumes the thread. The walk runs after that, in the copy: `RtlLookupFunctionEntry`, `RtlVirtualUnwind`, the fault guard, and the module lookups (`GetModuleHandleExA`), which also ran while the thread was suspended before. Each sampler thread has its own copy buffer. - Timed regression (`sampler_lock` in `tests/test_sampler_stack_walk.py`): a thread adds and removes a vectored handler in a loop. Its outer frame is a function whose unwind data chains into unmapped memory, so every walk through it faults. 400 samples must finish within 60 s, and the thread must still be running afterwards. At 1b0c78fe the samplers still walk while the thread is suspended, and the case hung after 0 of 400 samples (2 of 400 in an earlier run of the same test). At 2ee9b8f9 all 400 samples finish and the thread is still running; all 13 cases pass. A control case walks the same thread while it is suspended, as the samplers did before, and only reports what happened. It hung in all four runs, after 0, 3, 43 and 0 samples, so on this Windows 11 PC the hang you describe does happen. Checks (Windows 11, i7-9700, llvm-mingw clang 23.1.5, through the PC's job queue): `tests/test_sampler_stack_walk.py` passes at 2ee9b8f9 ("PASS (runtime: every case ran)"), with `--cc` and with the default compiler. `host/mkw_glue.c` and `host/hos_crash_record.c` compile `-fsyntax-only` with the host build's flags. `run_all.py --strict --changed origin/main` at the fix: 5 passed and 7 failed. Six of the 7 also fail on `main` @ 9dd41326: `test_crash_record`, `test_crash_dialog`, `test_input_background`, `test_profiling_mode`, `test_renderer_new_handler`, `test_slow_frames`. The seventh was this test, which stopped at an unused-function warning in its compile-only step; that is fixed in 1b0c78fe, and the test passes at the head as above. Not run: the game. Still not done, as you list: the Market A/B on Windows with suspension time, sweep rate, stack depth and frame-time tails, plus the slow-frame path; the Linux checks and host build; the rest of the suite. The Test Farm request stays on hold until then.
Author
Contributor

@Beanstalk This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. It has not run in the game on these PCs yet. This head is on main 9dd41326: please compare with main at that merge base. Please start from the market-entrance save and play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides, the PR against main on the same PC, on Windows PCs with an AMD processor, with an AMD GPU, with an Intel GPU and with an NVIDIA GPU. The PR side must not crash (main may: that is the bug) and must write a readable profile (some stacks may be shorter); frame time p99 within main's run-to-run spread.

@Beanstalk This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. It has not run in the game on these PCs yet. This head is on main 9dd41326: please compare with main at that merge base. Please start from the market-entrance save and play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides, the PR against main on the same PC, on Windows PCs with an AMD processor, with an AMD GPU, with an Intel GPU and with an NVIDIA GPU. The PR side must not crash (main may: that is the bug) and must write a readable profile (some stacks may be shorter); frame time p99 within main's run-to-run spread.
Member

@siantm only members of BigBeans can start the farm.

One of them can approve this request by reacting 👍 to it or to this comment. This request was for 2ee9b8f, and the PR has changed since (ba88b68), so a 👍 no longer approves it. Comment @Beanstalk again to ask for the new commit.

@siantm only members of `BigBeans` can start the farm. ~~One of them can approve this request by reacting 👍 to it or to this comment.~~ This request was for `2ee9b8f`, and the PR has changed since (`ba88b68`), so a 👍 no longer approves it. Comment `@Beanstalk` again to ask for the new commit.
siantm force-pushed fix/sampler-epilogue-unwind from 2ee9b8f9ec
Some checks failed
PR description / Description follows the template (pull_request_target) Successful in 4s
beanstalk/approval waiting for a BigBean's 👍 on the request
Website / Website on Cloudflare (pull_request_target) Has been skipped
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
Guide screenshots / Guide images and local UI source review (pull_request) Has been cancelled
Third-party parts / As their notes say (pull_request) Has been cancelled
Third-party parts / The same as upstream (pull_request) Has been cancelled
Website / Website on Cloudflare (pull_request) Has been cancelled
to ba88b68d28
Some checks failed
PR description / Description follows the template (pull_request_target) Successful in 4s
beanstalk/approval waiting for a BigBean's 👍 on the request
Website / Website on Cloudflare (pull_request_target) Has been skipped
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
Guide screenshots / Guide images and local UI source review (pull_request) Has been cancelled
Third-party parts / As their notes say (pull_request) Has been cancelled
Third-party parts / The same as upstream (pull_request) Has been cancelled
2026-11-21 13:42:15 +00:00
Compare
Author
Contributor

The branch's history was rebuilt (new head ba88b68d) to remove a figure taken over the game's compiled code from a comment in an earlier commit; the tree is identical to 2ee9b8f9's, so the checks run at 2ee9b8f9 stand, and the earlier heads stay reachable until an admin removes them.

The branch's history was rebuilt (new head ba88b68d) to remove a figure taken over the game's compiled code from a comment in an earlier commit; the tree is identical to 2ee9b8f9's, so the checks run at 2ee9b8f9 stand, and the earlier heads stay reachable until an admin removes them.
Author
Contributor

@Beanstalk This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. It has not run in the game on these PCs yet. Please start from the market-entrance save and play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides, the PR against main on the same PC, on Windows PCs with an AMD processor, with an AMD GPU, with an Intel GPU and with an NVIDIA GPU. The PR side must not crash (main may: that is the bug) and must write a readable profile (some stacks may be shorter); frame time p99 within main's run-to-run spread.

@Beanstalk This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. It has not run in the game on these PCs yet. Please start from the market-entrance save and play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides, the PR against main on the same PC, on Windows PCs with an AMD processor, with an AMD GPU, with an Intel GPU and with an NVIDIA GPU. The PR side must not crash (main may: that is the bug) and must write a readable profile (some stacks may be shorter); frame time p99 within main's run-to-run spread.
Member

@siantm only members of BigBeans can start the farm.

One of them can approve this request by reacting 👍 to it or to this comment. This request was for ba88b68, and the PR has changed since (f6d9c75), so a 👍 no longer approves it. Comment @Beanstalk again to ask for the new commit.

@siantm only members of `BigBeans` can start the farm. ~~One of them can approve this request by reacting 👍 to it or to this comment.~~ This request was for `ba88b68`, and the PR has changed since (`f6d9c75`), so a 👍 no longer approves it. Comment `@Beanstalk` again to ask for the new commit.
futondestroyer left a comment

Recommendation — Request changes. Resuming the sampled thread before unwinding addresses the previous deadlock. The new copy path can cut off valid frames and can make native unwind read beyond the captured bytes.

Blocking

  1. host/mkw_glue.c:439 only rebases registers at or above the sampled RSP. Take a normal frame-pointer epilogue lea rsp,[r12+0x58]; pop r12; ret, stopped at the pop. Its frame base is below the sampled RSP, but Windows only needs the pop and return slots, which the copy includes. The rebasing leaves R12 in the original address space and the frame-base precheck at line 403 rejects it before Windows can unwind it. Preserve native unwinding when all remaining reads are in the copy. Add a snapshot-path fixture for this ordinary epilogue. The existing frame-pointer fixture uses vzeroupper and takes the custom path at the pop. Microsoft's x64 epilogue rules
  2. host/mkw_glue.c:469 records the capture length, but the native step at line 406 dereferences stack locations without enforcing it. A frame whose return slot is past the 128 KiB cap can read past the allocation before the final RSP check. After a partial capture, a register save can also be in the readable tail of the reused buffer beyond the bytes captured for this sample. Guard the actual capture boundary or validate every native read before allowing the step. Cover a copy that ends before a required save or return slot. Microsoft's x64 unwind operations

Evidence. The author reports 53/53 correct AVX instruction stops and 400/400 samples with a running target afterward. All four live-stack controls hung. Those checks ran on the pre-rewrite head, whose tree the author reports is identical. The fixtures exercise unwind fault recovery and the former lock ordering. The local Windows Market A/B, slow-frame capture, suspension cost, Linux checks and host build, and crash-record runtime coverage remain open. No switches changed. Author's test report · History rewrite

Test Farm. Keep the current Windows Market request pending. Once the snapshot path is fixed, the AMD CPU and AMD, Intel, and NVIDIA GPU coverage is relevant for crash behavior, readable profiles and p99 frame time. The local A/B needs to measure suspension time, sweep rate and stack depth. Current request

Reviewed. ba88b68d288d2b8be853eb5e81d6fa67abd2dbc7 against merge base 9dd41326e71094d8b774459dac5154eb5a3306d9 with the earlier 186660c6 review findings and the latest source and test changes. Source review only.

**Recommendation — Request changes.** Resuming the sampled thread before unwinding addresses the previous deadlock. The new copy path can cut off valid frames and can make native unwind read beyond the captured bytes. **Blocking** 1. `host/mkw_glue.c:439` only rebases registers at or above the sampled RSP. Take a normal frame-pointer epilogue `lea rsp,[r12+0x58]; pop r12; ret`, stopped at the pop. Its frame base is below the sampled RSP, but Windows only needs the pop and return slots, which the copy includes. The rebasing leaves R12 in the original address space and the frame-base precheck at line 403 rejects it before Windows can unwind it. Preserve native unwinding when all remaining reads are in the copy. Add a snapshot-path fixture for this ordinary epilogue. The existing frame-pointer fixture uses `vzeroupper` and takes the custom path at the pop. [Microsoft's x64 epilogue rules](https://learn.microsoft.com/en-us/cpp/build/prolog-and-epilog) 2. `host/mkw_glue.c:469` records the capture length, but the native step at line 406 dereferences stack locations without enforcing it. A frame whose return slot is past the 128 KiB cap can read past the allocation before the final RSP check. After a partial capture, a register save can also be in the readable tail of the reused buffer beyond the bytes captured for this sample. Guard the actual capture boundary or validate every native read before allowing the step. Cover a copy that ends before a required save or return slot. [Microsoft's x64 unwind operations](https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64) **Evidence.** The author reports 53/53 correct AVX instruction stops and 400/400 samples with a running target afterward. All four live-stack controls hung. Those checks ran on the pre-rewrite head, whose tree the author reports is identical. The fixtures exercise unwind fault recovery and the former lock ordering. The local Windows Market A/B, slow-frame capture, suspension cost, Linux checks and host build, and crash-record runtime coverage remain open. No switches changed. [Author's test report](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-66019) · [History rewrite](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-66614) **Test Farm.** Keep the current Windows Market request pending. Once the snapshot path is fixed, the AMD CPU and AMD, Intel, and NVIDIA GPU coverage is relevant for crash behavior, readable profiles and p99 frame time. The local A/B needs to measure suspension time, sweep rate and stack depth. [Current request](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-66620) **Reviewed.** `ba88b68d288d2b8be853eb5e81d6fa67abd2dbc7` against merge base `9dd41326e71094d8b774459dac5154eb5a3306d9` with the earlier `186660c6` review findings and the latest source and test changes. Source review only.
host/mkw_glue.c Outdated
@ -359,0 +436,4 @@
const uint64_t len = c.hi - c.lo;
for (unsigned r = 0; r < 16; r++) {
DWORD64 *const g = gpr(ctx, r);
if (*g - base < len) *g = *g - base + c.lo;
Member

A normal frame-pointer pop/ret epilogue can have a valid frame base below the sampled RSP after the stack adjustment. That register is left in the original address space, so line 403 rejects the step before Windows can read the captured pop and return slots. Cover this through copy_step.

A normal frame-pointer pop/ret epilogue can have a valid frame base below the sampled RSP after the stack adjustment. That register is left in the original address space, so line 403 rejects the step before Windows can read the captured pop and return slots. Cover this through copy_step.
host/mkw_glue.c Outdated
@ -359,0 +466,4 @@
(SIZE_T)(s.hi - ctx.Rsp < SAMPLE_COPY ? s.hi - ctx.Rsp : SAMPLE_COPY), &n); /* (n: what it read) */
if (ResumeThread(th) == (DWORD)-1) return -1;
if (!got) return 0;
const StackRange c = {(uint64_t)(uintptr_t)copy, (uint64_t)(uintptr_t)copy + (n & ~(SIZE_T)7)};
Member

The capture limit bounds the custom AVX reads, but RtlVirtualUnwind reads stack slots before its final RSP check. A large frame can read past the allocation, and a short copy leaves readable stale bytes in the reused buffer. Enforce the captured boundary for native reads and add a cutoff regression.

The capture limit bounds the custom AVX reads, but RtlVirtualUnwind reads stack slots before its final RSP check. A large frame can read past the allocation, and a short copy leaves readable stale bytes in the reused buffer. Enforce the captured boundary for native reads and add a cutoff regression.
siantm force-pushed fix/sampler-epilogue-unwind from ba88b68d28
Some checks failed
PR description / Description follows the template (pull_request_target) Successful in 4s
beanstalk/approval waiting for a BigBean's 👍 on the request
Website / Website on Cloudflare (pull_request_target) Has been skipped
CI / Conventional Commit title (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Has been cancelled
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Has been cancelled
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Has been cancelled
CI / Workflow lint (actionlint) (pull_request) Has been cancelled
CI / Website build and checks (pull_request) Has been cancelled
Guide screenshots / Guide images and local UI source review (pull_request) Has been cancelled
Third-party parts / As their notes say (pull_request) Has been cancelled
Third-party parts / The same as upstream (pull_request) Has been cancelled
to f6d9c754e1
Some checks are pending
CI / Workflow lint (actionlint) (pull_request) Blocked by required conditions
CI / Website build and checks (pull_request) Blocked by required conditions
CI / Conventional Commit title (pull_request) Blocked by required conditions
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Blocked by required conditions
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Blocked by required conditions
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Blocked by required conditions
Guide screenshots / Guide images and local UI source review (pull_request) Blocked by required conditions
Third-party parts / As their notes say (pull_request) Blocked by required conditions
Third-party parts / The same as upstream (pull_request) Blocked by required conditions
Website / Website on Cloudflare (pull_request) Blocked by required conditions
Website / Website on Cloudflare (pull_request_target) Has been skipped
PR description / Description follows the template (pull_request_target) Successful in 5s
beanstalk/approval waiting for a BigBean's 👍 on the request
2026-11-21 17:08:59 +00:00
Compare
Author
Contributor

Head f6d9c754 (main f8c130b1): Summary and Tested for futondestroyer's third review (plain frame-pointer epilogue; reads bounded by the copy).

Head f6d9c754 (main f8c130b1): Summary and Tested for futondestroyer's third review (plain frame-pointer epilogue; reads bounded by the copy).
Author
Contributor

@futondestroyer thank you (67046); both points are right and fixed, head f6d9c754 (on main @ f8c130b1; checks ran on the same commits at ea04ea95, range-diff all "=", main's new commits touch none of these files):

  • mkw_glue.c:439, the ordinary frame-pointer epilogue: test 69bd2665 (every stop of lea rsp, [r12 + 0x58]; pop r12; ret, on the stack and in the samplers' copy; fails before the fix), fix 19ed0e11: at the pops and the ret, in a function with a version 1 record, the step checks only the pops' slots and the return address and leaves the frame register alone. The lea stop itself is run by the walk, because RtlVirtualUnwind decoded lea rsp, [r12 + disp] without its SIB byte in the test (a wrong stack pointer and a return address of 0).
  • mkw_glue.c:469, native reads past the capture: test 4e4329b4 (cut_save, cut_return: a frame larger than the copy, the copy ending before a save or the return address, over a buffer holding an earlier sample's bytes; cut_save fails before the fix), fix f6d9c754: each sampler's copy is its own reservation, the copy placed right under a no-access guard, so any read past the bytes taken for this sample faults and the walk ends at that frame; below the copy the buffer is kept zero.
    At the head every case passes, with the given compiler and the default one; the in-game runs you list stay pending, and the farm request waits for this head as you asked.
@futondestroyer thank you ([67046](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-67046)); both points are right and fixed, head f6d9c754 (on `main` @ f8c130b1; checks ran on the same commits at ea04ea95, `range-diff` all "=", main's new commits touch none of these files): - [mkw_glue.c:439](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-67044), the ordinary frame-pointer epilogue: test 69bd2665 (every stop of `lea rsp, [r12 + 0x58]; pop r12; ret`, on the stack and in the samplers' copy; fails before the fix), fix 19ed0e11: at the pops and the `ret`, in a function with a version 1 record, the step checks only the pops' slots and the return address and leaves the frame register alone. The `lea` stop itself is run by the walk, because `RtlVirtualUnwind` decoded `lea rsp, [r12 + disp]` without its SIB byte in the test (a wrong stack pointer and a return address of 0). - [mkw_glue.c:469](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-67045), native reads past the capture: test 4e4329b4 (`cut_save`, `cut_return`: a frame larger than the copy, the copy ending before a save or the return address, over a buffer holding an earlier sample's bytes; `cut_save` fails before the fix), fix f6d9c754: each sampler's copy is its own reservation, the copy placed right under a no-access guard, so any read past the bytes taken for this sample faults and the walk ends at that frame; below the copy the buffer is kept zero. At the head every case passes, with the given compiler and the default one; the in-game runs you list stay pending, and the farm request waits for this head as you asked.
Author
Contributor

@Beanstalk This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. It has not run in the game on these PCs yet. Please start from the market-entrance save and play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides, the PR against main on the same PC, at least two starts a side, on a Windows PC with an AMD processor, and on Windows PCs with an AMD GPU, with an Intel GPU and with an NVIDIA GPU. No crash or hang on the PR's side (main may crash: that is the bug), and it must write a readable profile (some stacks may be shorter); frame time p99 equal to main's, within the run-to-run spread.

@Beanstalk This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. It has not run in the game on these PCs yet. Please start from the market-entrance save and play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides, the PR against main on the same PC, at least two starts a side, on a Windows PC with an AMD processor, and on Windows PCs with an AMD GPU, with an Intel GPU and with an NVIDIA GPU. No crash or hang on the PR's side (main may crash: that is the bug), and it must write a readable profile (some stacks may be shorter); frame time p99 equal to main's, within the run-to-run spread.
Member

@siantm only members of BigBeans can start the farm. One of them can approve this request by reacting 👍 to it or to this comment.

@siantm only members of `BigBeans` can start the farm. One of them can approve this request by reacting 👍 to it or to this comment.
Author
Contributor

@futondestroyer I measured the suspension time, sweep rate and stack depth you asked for in 65450 and 67046, game-free, on the i7-9700 (11 rounds of 300 samples; the table is in Measurements). This head is slower than main per sample: 13.30 against 9.00 us with 12 frames x 256 B, and 26.60 against 10.50 us with 48 x 2048 B. That means 75188 against 111111 and 37594 against 95238 samples a second, at the same depth (15 and 51 frames). The thread is held suspended 7.90 against 6.80 us and 14.60 against 8.50 us.
Against head-susp (this head's unwinder walked while the thread is suspended, no copy), the stack copy accounts for +3.80 / +13.60 us. Most of that comes in the walk in the copy after the resume, which reading the code does not explain. The unwinder accounts for +0.50 / +2.50 us, with its fault guard set up per step (host/mkw_glue.c:467-473).
Only runs with HOS_PROFILE=1, HOS_SAMPLE_ALL, HOS_SAMPLE or HOS_SLOW_FRAMES pay this. All four are off by default (gpu/vk/switches.def:158, :172, :173, :186; the samplers start at host/mkw_glue.c:1112-1123), and the crash walks run only after a crash. Every run pays one thread-local read per exception in the guard's handler, which is first in the vectored chain (:318-320); that is not measured.
If you want the cost down, there are two options. The guard can be set up once per walk; that saves at most the 0.50 / 2.50 us, needs the walk's locals made volatile across its restore, and means running the walk test again. Or the copy can be sized to the frames the sampler walks; that shortens the suspension but risks cutting deep game stacks, which only the play run can show. I'll make neither change unless you ask or the Market run shows suspension time or sweep rate hurting.

@futondestroyer I measured the suspension time, sweep rate and stack depth you asked for in [65450](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-65450) and [67046](https://git.magicbean.dev/MagicBeanDev/Longshot/pulls/1951#issuecomment-67046), game-free, on the i7-9700 (11 rounds of 300 samples; the table is in Measurements). This head is slower than `main` per sample: 13.30 against 9.00 us with 12 frames x 256 B, and 26.60 against 10.50 us with 48 x 2048 B. That means 75188 against 111111 and 37594 against 95238 samples a second, at the same depth (15 and 51 frames). The thread is held suspended 7.90 against 6.80 us and 14.60 against 8.50 us. Against head-susp (this head's unwinder walked while the thread is suspended, no copy), the stack copy accounts for +3.80 / +13.60 us. Most of that comes in the walk in the copy after the resume, which reading the code does not explain. The unwinder accounts for +0.50 / +2.50 us, with its fault guard set up per step (`host/mkw_glue.c:467-473`). Only runs with `HOS_PROFILE=1`, `HOS_SAMPLE_ALL`, `HOS_SAMPLE` or `HOS_SLOW_FRAMES` pay this. All four are off by default (`gpu/vk/switches.def:158`, `:172`, `:173`, `:186`; the samplers start at `host/mkw_glue.c:1112-1123`), and the crash walks run only after a crash. Every run pays one thread-local read per exception in the guard's handler, which is first in the vectored chain (`:318-320`); that is not measured. If you want the cost down, there are two options. The guard can be set up once per walk; that saves at most the 0.50 / 2.50 us, needs the walk's locals made volatile across its restore, and means running the walk test again. Or the copy can be sized to the frames the sampler walks; that shortens the suspension but risks cutting deep game stacks, which only the play run can show. I'll make neither change unless you ask or the Market run shows suspension time or sweep rate hurting.
Author
Contributor

@Beanstalk This replaces my request 67724 on this head (same head; restated so the run is paired with this head's merge base, main f8c130b1). This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. No switch of its own: a revert gives back main's code. Please start from the market-entrance save and take the picture 5 s (300 frames at 60 fps) after the first frame whose picture is not a single uniform colour, with no input in between (a picture during the load's fade-in from black is not comparable), with a main-against-itself picture on the same PC from the same point; then play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides; at least two starts a side, interleaved, the PR against main on the same PC, on Windows with a Ryzen 9 7900X and an RTX 4070, Windows with a Ryzen 9 5900X and an RX 9070 XT, and Windows with a Core i9-12900K and an Arc B580. No crash or hang on the PR's side (main may crash: that is the bug), and it must write a readable profile (some stacks may be shorter); The same picture as main within main's own difference from itself; frame time p99 equal to main's, within the run-to-run spread.

@Beanstalk This replaces my request 67724 on this head (same head; restated so the run is paired with this head's merge base, main f8c130b1). This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. No switch of its own: a revert gives back main's code. Please start from the market-entrance save and take the picture 5 s (300 frames at 60 fps) after the first frame whose picture is not a single uniform colour, with no input in between (a picture during the load's fade-in from black is not comparable), with a main-against-itself picture on the same PC from the same point; then play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides; at least two starts a side, interleaved, the PR against main on the same PC, on Windows with a Ryzen 9 7900X and an RTX 4070, Windows with a Ryzen 9 5900X and an RX 9070 XT, and Windows with a Core i9-12900K and an Arc B580. No crash or hang on the PR's side (main may crash: that is the bug), and it must write a readable profile (some stacks may be shorter); The same picture as main within main's own difference from itself; frame time p99 equal to main's, within the run-to-run spread.
Member

@siantm only members of BigBeans can start the farm. One of them can approve this request by reacting 👍 to it or to this comment.

@siantm only members of `BigBeans` can start the farm. One of them can approve this request by reacting 👍 to it or to this comment.
Author
Contributor

@Beanstalk This replaces my request 72576 on this head and the corrections under it, in a form the farm can run: it cannot time a picture from the first frame that is not a uniform colour (its answer on #2131), so each picture here follows a fixed wait after the map event. This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. No switch of its own: a revert gives back main's code. Please start from the market-entrance save and take the picture 10 s (600 frames at 60 fps) after the map event that ends the load, a fixed wait with no input in between (the farm cannot time it from the first frame that is not a uniform colour), with a main-against-itself picture on the same PC from the same point; then play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides; at least two starts a side, interleaved, the PR against main on the same PC, on Windows with a Ryzen 9 7900X and an RTX 4070, Windows with a Ryzen 9 5900X and an RX 9070 XT, and Windows with a Core i9-12900K and an Arc B580. No crash or hang on the PR's side (main may crash: that is the bug), and it must write a readable profile (some stacks may be shorter); The same picture as main within main's own difference from itself; frame time p99 equal to main's, within the run-to-run spread.

@Beanstalk This replaces my request 72576 on this head and the corrections under it, in a form the farm can run: it cannot time a picture from the first frame that is not a uniform colour (its answer on #2131), so each picture here follows a fixed wait after the map event. This fixes the host's stack walks on Windows (host/mkw_glue.c): the samplers' walk unwinds clang's vzeroupper epilogues itself and checks every read of a frame, so a profile no longer crashes in RtlVirtualUnwind; the samplers now copy the stack while the thread is suspended and walk it after it resumes. It acts only with HOS_PROFILE=1 (or the other samplers, the slow-frame recorder, or after a crash); no gameplay path changes. No switch of its own: a revert gives back main's code. Please start from the market-entrance save and take the picture 10 s (600 frames at 60 fps) after the map event that ends the load, a fixed wait with no input in between (the farm cannot time it from the first frame that is not a uniform colour), with a main-against-itself picture on the same PC from the same point; then play Castle Town Market for two minutes with HOS_PROFILE=1 on both sides; at least two starts a side, interleaved, the PR against main on the same PC, on Windows with a Ryzen 9 7900X and an RTX 4070, Windows with a Ryzen 9 5900X and an RX 9070 XT, and Windows with a Core i9-12900K and an Arc B580. No crash or hang on the PR's side (main may crash: that is the bug), and it must write a readable profile (some stacks may be shorter); The same picture as main within main's own difference from itself; frame time p99 equal to main's, within the run-to-run spread.
Member

@siantm only members of BigBeans can start the farm. One of them can approve this request by reacting 👍 to it or to this comment.

@siantm only members of `BigBeans` can start the farm. One of them can approve this request by reacting 👍 to it or to this comment.
Author
Contributor

The crash this fixes was seen again this morning, with the slow-frame recorder (HOS_SLOW_FRAMES), on a build that has #1343 and not this pull request: #1584 (comment)

The crash this fixes was seen again this morning, with the slow-frame recorder (`HOS_SLOW_FRAMES`), on a build that has #1343 and not this pull request: https://git.magicbean.dev/MagicBeanDev/Longshot/issues/1584#issuecomment-78651
Some checks are pending
CI / Workflow lint (actionlint) (pull_request) Blocked by required conditions
CI / Website build and checks (pull_request) Blocked by required conditions
CI / Conventional Commit title (pull_request) Blocked by required conditions
CI / Python source checks (ubuntu-24.04, part 1/2) (pull_request) Blocked by required conditions
CI / Python source checks (ubuntu-24.04, part 2/2) (pull_request) Blocked by required conditions
CI / SPIR-V fixtures (global narrow load/store, direct surface atomics, F2I immediate) (pull_request) Blocked by required conditions
Guide screenshots / Guide images and local UI source review (pull_request) Blocked by required conditions
Third-party parts / As their notes say (pull_request) Blocked by required conditions
Third-party parts / The same as upstream (pull_request) Blocked by required conditions
Website / Website on Cloudflare (pull_request) Blocked by required conditions
Website / Website on Cloudflare (pull_request_target) Has been skipped
PR description / Description follows the template (pull_request_target) Successful in 5s
beanstalk/approval waiting for a BigBean's 👍 on the request
This pull request is marked as a work in progress.
Some workflows are waiting to be reviewed.
This branch is out-of-date with the base branch
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u 'fix/sampler-epilogue-unwind:siantm-fix/sampler-epilogue-unwind'
git switch 'siantm-fix/sampler-epilogue-unwind'
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
4 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
MagicBeanDev/Longshot!1951
No description provided.