WIP: fix(host): the stack walks run clang's AVX return suffix themselves and every step under a fault guard #1951
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/renderer
area/saves
area/tooling
area/upscaling
beanstalk: approved
beanstalk: failed
beanstalk: needs approval
beanstalk: running
beanstalk: tested
ci: approved
good first issue
gpu/amd
gpu/igpu
gpu/intel
gpu/nvidia
help wanted
kind
bug
kind
chore
kind
docs
kind
feature
kind
performance
kind
question
needs measurements
platform/linux
platform/macos
platform/steam-deck
platform/windows
preview
priority
critical
priority
high
priority
low
regression
risk
high
risk
low
risk
medium
status
blocked
status
confirmed
status
duplicate
status
invalid
status
needs-info
status
wontfix
ci: approved
No milestone
No project
No assignees
4 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!1951
Loading…
Reference in a new issue
No description provided.
Delete branch "siantm/Longshot:fix/sampler-epilogue-unwind"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Fixes #1584. The all-thread sampler (
HOS_SAMPLE_ALL, whichHOS_PROFILE=1starts), 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 gamecould still close with
0xc0000005insideRtlVirtualUnwind, 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 itspops, then a
vzeroupper, then theret. Windows' unwinder knows an epilogue only as anadd/leatorsp, pops anda
retor jump, so a thread stopped on those pops or on thevzeroupperis unwound as if it were in the function'sbody: 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, neverrsp),vzeroupper(c5 f8 77), a plainret(c3), every byte inside the function's ownRUNTIME_FUNCTIONrange, theregisters written through
CONTEXT's named members, the pops and the return address checked against the walkedthread's stack first. Everything else (the
add/leabefore the pops, where the body's unwind is still right;ret imm16; jumps; an epilogue without thevzeroupper, which Windows recognises itself) goes toRtlVirtualUnwind. Arecord 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 astep 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 acopy of its stack from the stack pointer up (128 KB at most, through
ReadProcessMemory, which reports an unreadablepage 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 copyis a reservation of its own (
stack_copy_open): 128 KB read-write right under 64 MB reserved without access, thecopy 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.
retof an ordinary frame-pointer epilogue (lea rsp, [r12 + disp]; pop r12; ret) the frameregister 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
leaitself is run by the walk (unwind_r12_lea), sinceRtlVirtualUnwinddecodes it without its SIB byte.walk_init:NtQueryInformationThreadand the handler are set up on the main thread inhos_commit_init, and againbefore the samplers' threads start in
hos_prof_start, so no sampler resolves anything on first use.host_stackinhost/hos_crash_record.c) steps through the same guardedunwind_step(
hos_crash_record_unwinder) instead of callingRtlVirtualUnwinditself.To see the bugs without the game:
python -I -B tests/test_sampler_stack_walk.pyon Windows at1b0c78fe(the samplerwalking a suspended thread hangs), at
99cc86f3(the new cases on this PR's first fix) or at this branch's first commite339fad8(the earlier test alone onmain).Read first:
sample_stack,copy_step,unwind_avx_return,step_frame,walk_guardedandunwind_stepinhost/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 ontomain@f8c130b1asf6d9c754(git range-diff: every commit "="; main's new commits touch none of this PR's files, so thechecks were not run again):
tests/test_sampler_stack_walk.pyat the epilogue test commit 69bd2665: fails (thelea, the pops and theretofan ordinary frame-pointer epilogue do not unwind, on the stack and in the samplers' copy); at the cut-off test commit
c0d66d2d: fails (
cut_savewalks on to the caller with a save read past the copy); at the head ea04ea95: passes,every case, with
--ccand with the default compiler, incl.fp_epilogue,cut_save,cut_return, the 53-stepAVX frame and the 400-sample lock case; its control (the walk with the thread suspended) hung after 0 of 400.
host/mkw_glue.candhost/hos_crash_record.ccompiled-fsyntax-onlyat ea04ea95: no error.run_all --changedwas not run again this round.Round 3, on this branch rebased onto
main@9dd41326, head2ee9b8f9:python -I -B tests/test_sampler_stack_walk.py --cc <llvm-mingw clang>at1b0c78fe(the lock test on this PR'sprevious fix): fails:
sampler_lock"the sampler hung after 0 of 400 samples, the thread left suspended" (thesamplers 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 "53steps 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(thedefault 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.main@f1f2dc5b): with the authored cases on this PR's first fix (f3ed9d4b, now99cc86f3)8 of 11 cases failed; at
186660c6all 11 passed. They are unchanged since and pass at the head (above).host/mkw_glue.candhost/hos_crash_record.ccompiled-fsyntax-onlywith 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/mainat the fix (2ddabf67, before the test's syntax-onlycompile 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 onmain@9dd41326too, run by name in the samequeue job; the seventh,
test_sampler_stack_walk.py, stopped at that unused-function error and passes at the head(above).
test_crash_record.pystops at a renderer source check before it builds the record, so the record'sstep is covered only by the syntax check and the walk test's source check.
Still to test:
HOS_PROFILE=1in Castle Town's market, 120 s standing andturning, this PR and
mainalternated (A B B A A B), expecting noCRASH:line from the walk, a readable profile(
python -I scripts/perf.py reporton the run's profile folder), the time each sampled thread stays suspended, thesweeps a second and the stack depths on both sides (the game-free fixture in Measurements shows this PR slower than
mainthere), and the frame-time tails about as onmain, withHOS_PROFILE=1and with the slow-frame recorder (by hand,queued)
python3 -I -B tests/test_sampler_stack_walk.py, expecting the source checks to pass and "source only" (thewalk is Windows' only); the host build (by hand)
HOS_PROFILE=1, this PR againstmain, expecting no crash on this PR's side (@Beanstalk play Castle Town's marketfor 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@fc4a6769stay 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 and26.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 sidethrough 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, onmain@f1f2dc5b; the lock case on the second fix,1b0c78fe, onmain@9dd41326), as the bugs fixedhere are in this PR's own earlier code.
99cc86f3(row 1) and @1b0c78fe(row 2), with the new tests2ee9b8f9tests/test_sampler_stack_walk.py: authored cases and the stepped AVX frame (99cc86f3)tests/test_sampler_stack_walk.pysampler_lock: samples of a thread adding and removing vectored handlers (1b0c78fe)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'swalk helpers from
host/mkw_glue.c, cut astests/test_sampler_stack_walk.pycuts them, sample a thread of theharness'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 theResumeThreadcall (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-framerecorder) 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'sunwind_step, resume. This is how the samplers sample onmain.f6d9c754:sample_stack. It suspends the thread, takes the context, the stack's limits and a copy of thestack (at most 128 KiB) and resumes it; then it walks the copy.
main(the test'swalk_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
mainthe unwinder's.main@f8c130b1f6d9c754f6d9c754, walked while suspended)Where the cost comes from (12 x 256 B / 48 x 2048 B):
sample_stackcopies 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 thewalk in the copy. Reading the code does not explain that part:
copy_step's register remap (:477-489) is a fewcompares a step, and it was not measured apart.
main, both walking while suspended): +0.50 / +2.50 us a sample. This covers thefault guard, set up for every step where once per walk would do (
unwind_stepcallswalk_guarded, anRtlCaptureContexteach step::467-473,:453-464), and the AVX-suffix andleadecoders (:395-450). Theywere 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; thesampler_lockcase above). Every read the walk makes is bounded by the copy and itsno-access guard (
:490-507). The AVX return suffix andlea rsp, [r12 + disp]stops unwind right (:395-418).Who pays: only runs with the diagnostic sampling switches. These are
HOS_PROFILE=1(which setsHOS_SAMPLE_ALL),HOS_SAMPLE_ALL,HOS_SAMPLEwithHOS_PROFILE_EVERY, andHOS_SLOW_FRAMES, all off by default(
gpu/vk/switches.def:158,:172,:173,:186). The samplers' threads start only inhos_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 ingpu/vk/vk_hangdump.cpp, which this PR does not touch. Every run, profiled or not, pays one thing, not measured:walk_faultis first in theprocess's vectored-handler chain (
hos_commit_init→walk_init,:682,:330). Each exception, a commit-on-touchfault 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 shorterbacktrace or sample, as a refused step did before; a mistake in
unwind_avx_returnwould show as wrong callers in aprofile 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_stackmakes only system calls(
GetThreadContext,NtQueryInformationThread,ReadProcessMemory) and reads the thread's TEB, so a fault in a walkis dispatched with no thread suspended (before, one could wait for a lock the suspended thread held and hang both:
the test's
sampler_lockcase hangs at1b0c78fe). A suspension now costs the copy of the stack the thread uses, up to128 KB: in the game-free fixture a sample takes 4.30 to 16.10 us more than on
mainand holds the thread 1.10 to 6.10 uslonger (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_unwinderset(its test fixture) walks frame pointers. A revert is enough; players notice nothing.
Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named).main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
mainand passes here.tests/that reads changed source is updated, not weakened.Assisted-by:/Co-Authored-By:trailers.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
vzeroupperbefore 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
-mavxunconditionally for its runtime fixture, which needs a runtime feature check or a baseline-safe fixture.Reviewed:
7231d69ef1against2e1f6c32d3: 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:
Assisted-by:trailers. The patch has one topic and changes no game-derived files, generated files, vendor code, shaders or renderer API definitions._WIN32and 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.fc4a6769to2e1f6c32does not touch either changed file.git diff --checkwas clean.Blocking (to change before merge)
leadecoder 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 reads0x58as apop 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.CONTEXTmembers through&ctx->Raxas though the members were elements of a C array. Apop r15writes 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.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.on_stackcheck still accepts an RSP ofUINT64_MAX - 7becausep + 8wraps. 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.HOS_SAMPLEandHOS_PROFILEare enabled. They can enterthread_stacktogether and race on the plainlookedandqueryglobals. 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.record_exceptioncallshos_crash_record_write, whosehost_stackin host/hos_crash_record.c directly callsRtlVirtualUnwind. 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.vzeroupperbefore 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.-mavxafter 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.clang, andRUN_ALL_ARGSalso supplies--cc clang. On Windows withCCpointing 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. HonorCCwhen--ccis absent and report source-only and runtime passes separately.Waiting on the author (a run, a measurement or a decision; no edit does it)
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.
@ -308,2 +308,2 @@unable to fault rather than guarded: a step whose stack pointer, or frame register, is outside [lo, hi), the thread'scommitted 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 walkthere, and the sample is only cut short. What RtlVirtualUnwind will read is worked out from the frame's unwind codesThe persisted crash writer runs first and has its own unchecked
RtlVirtualUnwindinhost/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) {Both samplers can enter this existing lazy lookup at once. Resolve and publish
querybefore starting the sampler threads.@ -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; }p + 8can wrap and accept a corrupt RSP. Reusespan_onhere and make actual stack reads fail cleanly on inaccessible pages inside the interval.@ -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 */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.
@ -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;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.
@ -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;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.
@ -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;Indexing from
&ctx->Raxcrosses distinct C struct members. Use named members or a register-to-member mapping for the restores and frame-register reads.@ -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;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;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");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);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 @@returnexe = 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")Honor
CCunless--ccis 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",Check AVX availability before executing an AVX binary, or use a baseline-safe fixture that decodes the instruction bytes without executing them.
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:
7231d69ef136e2696108dc53de3067479847c54dagainst merge base2e1f6c32d30ec3582093743a968c8447bb435962. Queried verified revision-matched Graphify maps forunwind_stepand 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
host/mkw_glue.c:378recognizes opcode0xc2(ret imm16), but the success path at line 394 advances RSP by eight bytes only. If the stop is on aret 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 reportedvzeroupperfollowed by plainretand keep other cases on a fault-contained native path, or correctly decode and validate the full adjustment.host/mkw_glue.c:459enters 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 V3These 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.
@ -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 */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.
@ -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) */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.
7231d69ef1186660c677WIP: fix(host): the samplers' stack walk unwinds clang's vzeroupper epilogues itself and checks every read of a frameto WIP: fix(host): the stack walks run clang's AVX return suffix themselves and every step under a fault guardThanks for the review (61976). The branch is rebased onto
main@f1f2dc5b(the two earlier commits unchanged,git range-diff), with the checks inf3ed9d4band the fix in186660c6; head186660c6. Where futondestroyer's review asked for the same thing (a narrower handler), I followed it.186660c6. Every byte the decoder reads is inside theRUNTIME_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.186660c6. The custom path is only pops,vzeroupper, plainret; no jump of any kind is taken there. Theavx_nativecase stops on ajmp r11in a body with its frame allocated: wrong atf3ed9d4b, the caller at this head.186660c6by not decodingleaany more (at theleathe body's unwind is still right, and Windows does it). Thelea_sibcase (lea rsp, [r12 + 0x58]) was unwound wrong atf3ed9d4band gives the caller at this head, at theleaand at the pop after it.&ctx->Raxindexing: fixed in186660c6:gpr()maps register numbers toCONTEXT's named members, for the pops and the frame register.186660c6:frame_on_stackis gone; ordinary frames take one guardedRtlVirtualUnwind, a record that is not version 1 or 2 ends the walk. Thebad_chaincase (a chain into unmapped unwind data) crashed atf3ed9d4bin the preflight and ends the walk at this head;version3ends it too.186660c6:on_stackisspan_on(subtraction), and reads of a no-access page inside the range are contained by the guard. Thewrap,no_access_suffixandno_access_bodycases failed atf3ed9d4b(on_stacktook UINT64_MAX - 7; the two no-access cases exited 0xc0000005) and pass at this head.186660c6:walk_initresolvesNtQueryInformationThread(and registers the guard) on the main thread inhos_commit_initand again before the samplers'CreateThreads inhos_prof_start;thread_stackonly reads it. Checked by the test's source checks (no state inthread_stack,walk_initbefore the firstCreateThread).186660c6:host_stacksteps through the same guardedunwind_step(set byhos_crash_record_unwinderat startup) and no longer callsRtlVirtualUnwind; without it (the record's own fixture) it walks frame pointers. Checked by a source check andtests/test_crash_record.py(which stops at a renderer source check before it builds the record, onmain@f1f2dc5btoo, so here only a-fsyntax-onlycompile with the host flags covers the file); no runtime case puts a bad frame under the record.f3ed9d4b:epi_avxis assembled with the exact suffix and its own unwind data, andavx_suffixunwinds every stop on its pops and itsvzeroupper(the compiler-made frame stays as extra coverage, and now fails if it has novzeroupperstop).frame_on_stack) are removed in186660c6, and the reads go toRtlVirtualUnwindunder 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.f3ed9d4b: the authored cases are never executed; the compiler-made frame istarget("avx")in a baseline build and runs only when CPUID and XGETBV report AVX (else "skip avx_steps").CC: fixed inf3ed9d4b:--cc, thenCC, thenLONGSHOT_MINGW's clang, then clang/gcc on PATH, astests/test_fastfp_regions.py;RUN_ALL_ARGSdropped; the last line says "runtime" or "source only".f3ed9d4b: the registration, the wait (120 s) andGetExitCodeThreadare 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.pyatf3ed9d4bfails 8 of 11 cases (avx_native,ret_imm16,lea_sib,version3,wrap;bad_chain,no_access_suffix,no_access_bodyexit 0xc0000005); at186660c6all 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--ccand with the default compiler.run_all.py --strict --changed origin/mainat 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 onmain@f1f2dc5btoo.host/mkw_glue.candhost/hos_crash_record.cpass a-fsyntax-onlycompile 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.
@futondestroyer thanks for the review (62708). Fixed in
186660c6(checks inf3ed9d4b), rebased ontomain@f1f2dc5b, head186660c6:ret imm16): the walk now runs only the reported suffix itself: pops,vzeroupper(c5 f8 77), then a plainret(c3), every byte inside the function's own range.ret imm16, jumps, theadd/leabefore the pops and epilogues without thevzerouppergo toRtlVirtualUnwind, which now runs under a fault guard (a vectored handler; a fault ends the walk). The test'sret_imm16case (pop rbx, vzeroupper,ret 16) failed atf3ed9d4b(the old decoder gave an RSP 16 bytes low) and passes at this head;plain_returnchecks an ordinary pop/ret epilogue and itsret, left to Windows.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 byRtlVirtualUnwindunder the guard. The test'sversion3case (a hand-made version 3 record) andbad_chaincase (a chain into unmapped unwind data) end the walk without a fault; atf3ed9d4bbad_chaincrashed (exit 0xc0000005) in the old preflight andversion3returned 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.pyatf3ed9d4bfails 8 of 11 cases (avx_native,ret_imm16,lea_sib,version3,wrap;bad_chain,no_access_suffix,no_access_bodyexit 0xc0000005); at186660c6all 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--ccand with the default compiler.run_all.py --strict --changed origin/mainat 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 onmain@f1f2dc5btoo.host/mkw_glue.candhost/hos_crash_record.cpass a-fsyntax-onlycompile 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.
@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.
@siantm only members of
BigBeanscan start the farm.One of them can approve this request by reacting 👍 to it or to this comment.This request was for186660c, and the PR has changed since (2ee9b8f), so a 👍 no longer approves it. Comment@Beanstalkagain to ask for the new commit.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.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
host/mkw_glue.c:418runs the potentially faulting step before either sampler reachesResumeThread(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 invokingwalk_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_stepcallsRtlLookupFunctionEntrybeforewalk_guardedtoday). 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 updateDoes it help? The author reports 11/11 Windows fixture cases passing at
186660c6versus 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 byvzeroupperand plainret, 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
186660c677296995bb238f709523c4688f9313a5against merge basef1f2dc5bd2821cef061798ba40a043d281ac1707, including the interdiff from7231d69e. 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@ -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);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.
186660c6772ee9b8f9ec@futondestroyer thanks for the second look (65451, 65450). Fixed in
2ee9b8f9(test in1b0c78fe), rebased ontomain@9dd41326. The earlier commits are unchanged pergit range-diff.sample_stack. While the thread is suspended it takes only the context, the stack's limits (NtQueryInformationThreadand the TEB) and a copy of the stack from the stack pointer up: at most 128 KB, throughReadProcessMemory, 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.sampler_lockintests/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. At1b0c78fethe 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). At2ee9b8f9all 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.pypasses at2ee9b8f9("PASS (runtime: every case ran)"), with--ccand with the default compiler.host/mkw_glue.candhost/hos_crash_record.ccompile-fsyntax-onlywith the host build's flags.run_all.py --strict --changed origin/mainat the fix: 5 passed and 7 failed. Six of the 7 also fail onmain@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 in1b0c78fe, 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.
@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.@siantm only members of
BigBeanscan start the farm.One of them can approve this request by reacting 👍 to it or to this comment.This request was for2ee9b8f, and the PR has changed since (ba88b68), so a 👍 no longer approves it. Comment@Beanstalkagain to ask for the new commit.2ee9b8f9ecba88b68d28The 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 at2ee9b8f9stand, and the earlier heads stay reachable until an admin removes them.@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.
@siantm only members of
BigBeanscan start the farm.One of them can approve this request by reacting 👍 to it or to this comment.This request was forba88b68, and the PR has changed since (f6d9c75), so a 👍 no longer approves it. Comment@Beanstalkagain to ask for the new commit.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
host/mkw_glue.c:439only rebases registers at or above the sampled RSP. Take a normal frame-pointer epiloguelea 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 usesvzeroupperand takes the custom path at the pop. Microsoft's x64 epilogue ruleshost/mkw_glue.c:469records 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 operationsEvidence. 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.
ba88b68d288d2b8be853eb5e81d6fa67abd2dbc7against merge base9dd41326e71094d8b774459dac5154eb5a3306d9with the earlier186660c6review findings and the latest source and test changes. Source review only.@ -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;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.
@ -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)};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.
ba88b68d28f6d9c754e1Head
f6d9c754(mainf8c130b1): Summary and Tested for futondestroyer's third review (plain frame-pointer epilogue; reads bounded by the copy).@futondestroyer thank you (67046); both points are right and fixed, head
f6d9c754(onmain@f8c130b1; checks ran on the same commits at ea04ea95,range-diffall "=", main's new commits touch none of these files):lea rsp, [r12 + 0x58]; pop r12; ret, on the stack and in the samplers' copy; fails before the fix), fix19ed0e11: at the pops and theret, 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. Theleastop itself is run by the walk, becauseRtlVirtualUnwinddecodedlea rsp, [r12 + disp]without its SIB byte in the test (a wrong stack pointer and a return address of 0).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_savefails before the fix), fixf6d9c754: 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.
@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.
@siantm only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this comment.@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
mainper 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_SAMPLEorHOS_SLOW_FRAMESpay this. All four are off by default (gpu/vk/switches.def:158,:172,:173,:186; the samplers start athost/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.
@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.@siantm only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this comment.@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.
@siantm only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this 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: #1584 (comment)View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.