fix(prof): a stack walk that faults cuts its sample short instead of ending the game #2790
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/mods
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
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!2790
Loading…
Reference in a new issue
No description provided.
Delete branch "HumanBean/Longshot:fix/prof-walk-fault"
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
With profiling on (
HOS_PROFILE=1,HOS_SAMPLE,HOS_SAMPLE_ALL,HOS_SLOW_FRAMES), the game could crash on Linux. Linux's thread sampler (host/posix/prof.c) walks each thread's stack from a signal, with libgcc's unwinder, starting from whatever instruction the thread was stopped on. Where the unwind data doesn't hold at that instruction (a driver's code, a function's prologue), the unwinder reads through a bad frame and faults. On an RX 580 (Mesa RADV, CachyOS) it took the game down twice in one evening of profiling:CRASH: exception 0xc0000005 (read 0xc) at libgcc_s.so.1+0x27869, which is_Unwind_Backtrace + 201, onmkw_vk recorder. Its last samples were insidelibvulkan_radeon.so.CRASH: exception 0xc0000005 (read 0) at libgcc_s.so.1+0x26617, inside libgcc's unwinder, onBaseProcExecutor5.Each crash then left a core dump of the game's ~10 GB of shared guest memory, which used up the PC's RAM for over ten minutes.
Now a fault during a walk jumps back to the sample that started it.
walk_faultis the first vectored handler; itsiglongjmps toon_sample, which keeps the frames found so far (the interrupted rip at least). The run goes on, and the log says so once:prof: a stack walk faulted (unwind data that does not hold there): its sample cut short, the run goes on.sampling_initnow runs once throughpthread_once, so whenHOS_SAMPLEandHOS_SAMPLE_ALLstart their samplers together, neither samples before the other has registeredwalk_faultand warmed up the unwinder. Windows already checks each step against the thread's stack (unwind_step,tests/test_sampler_stack_walk.py), so this brings Linux's walk to the same footing.Read first:
host/posix/prof.c(walk_fault,on_sample), thentests/test_prof_walk_fault.py.Testing
Tested:
tests/test_prof_walk_fault.pycompiles prof.c's own sampling code, from "one thread's stack, taken inside it" throughsampling_init, with the C compiler run_all.py gives it ({cc};CC, elsecc, on its own). The test starts a thread spinning in a function whose unwind data names a bad frame and sets up withsampling_init. A fault goes only to the vectored handlerssampling_initregistered, aswin32_posix.c'son_signalsends it. The test then samples the thread 200 times the waysample_onedoes and needs every sample back with the process alive. Both gcc and clang were checked.a walk through bad unwind data took the process down (signal 11).PASS: 200 walks through bad unwind data, each sample back and the process alive.AddVectoredExceptionHandler(1, walk_fault)line, it fails.dev.py packon the shared base compiledlongshotwith thisprof.ccleanly (Linux), including thepthread_oncechange.894683cfwith this branch (and #2789) merged.HOS_PROFILE=1for 20.7 minutes of laps: warp to the Market, walk back into Hyrule Field, then forward for 30 s. No crash. The fault this handles happened once and was handled: the log has oneprof: a stack walk faulted (unwind data that does not hold there): its sample cut short, the run goes on.perf.py reportread the profile as before (45,019 frames). Without this fix, two profiled runs on the same PC crashed the same evening. (That run was before review movedsampling_initontopthread_once. The compile and the test cover that change; it has not run in the game.)Still to test: Profiling on Tier 1 Linux hardware (NVIDIA, a newer AMD, the Steam Deck). I don't have it; a Test Farm run would cover it.
Measurements
Nothing to measure: the change only matters when a stack walk faults, and costs a
sigsetjmpper sample, which is a few nanoseconds next to the 2 ms interval.Risks
_dl_find_object). The worst case is a hung sampler thread instead of a crashed game.Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named). (Not run yet; the new test and a real build pass.)main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
mainand passes here.Assisted-by:/Co-Authored-By:trailers.Ready to merge
main, measured again or a comment says why the numbers still hold.🤖 Generated with Claude Code
Possibly related, for context:
@review
Recommendation: Request changes. The fault recovery works in the reported RX 580 run, but concurrent sampler startup can send a sample before the recovery handler is installed. The regression test also bypasses the production registration, so it would pass if that essential line were removed.
This keeps a Linux profiling run alive when an unwind faults, preserving the frames collected so far. It adds signal-handler recovery and a synthetic fault test; normal play without sampling is unaffected.
Blocking (1): must change before merging.
host/posix/prof.c:225: The recovery handler is installed after the unsynchronized initialization guard has let another sampler proceed. (more on the line) Do: Use a once primitive that makes all sampler threads wait until signal setup, handler registration and unwinder warm-up have completed before sampling starts.Should fix (3): not blocking, but worth doing before merging.
tests/test_prof_walk_fault.py:109: The test excludes sampling_init and calls walk_fault directly from its substitute fault handler, bypassing the production registration. (more on the line) Do: Exercise production initialization and exception dispatch in the harness, including registration of walk_fault, so removing that registration makes the test fail.tests/test_prof_walk_fault.py:22: The test hard-codes clang instead of honoring the configured C compiler. (more on the line) Do: Use the runner's {cc} compiler and the repository's compiler-argument parsing convention, and honor CC for standalone runs.tests/test_prof_walk_fault.py:54: The test publishes spinner between threads using volatile accesses rather than atomic synchronization. (more on the line) Do: Publish and read the thread ID with atomic release and acquire operations.Testing before merging (1) (runs on the systems it can change; it doesn't hold the recommendation)
host/posix/prof.c:206: The Linux sampler change still needs a run on affected Tier 1 hardware. (more on the line) Do: Run profiling on representative Tier 1 Linux hardware, exercising sampling and confirming the game and profile remain usable.@fixcan do L1, L2, L3 and L4.Checks: Failing on this head, which is behind its base, where they pass:
CI / Rust (rustfmt, clippy, cargo test, end to end) (pull_request),CI / Game-free checks (run_all.py, part 1/2) (pull_request),CI / Game-free checks (run_all.py, part 2/2) (pull_request).@rebase(or@fix) brings it up to date and runs them again; not held against it.More: does it help, other systems, switches, what was read
Does it help: Yes for the reported case: the author reports two crashes before the fix and one handled fault during a 20.7-minute RX 580 run with the fix. The synthetic test reportedly fails on the base and returns all 200 samples with the fix.
Other systems: The change runs on Linux for sampled threads regardless of GPU; Windows uses a separate sampler. The reported game run covers Mesa RADV on an RX 580, but does not cover Tier 1 Linux hardware or another Linux unwinder setup. Normal play without sampling does not enter the new walk path.
Switches: None added, changed or removed. Existing profiling switches enable the affected sampler.
Reviewed:
c06e8c2353against3ab4db6e91: Read AGENTS.md, CONTRIBUTING.md, the PR template, standards, both changed files, the diff and commit messages; read the sampler callers and POSIX exception dispatch around the changes. Skimmed the test runner and profiling switch setup. docs/review-checklist.md and the adjacent Tooling checkout were absent. No recorded runs, translations or generated files changed.; nothing run (a code review).Checked and fine:
Testing: Read-only review; no builds, tests or project scripts were run. The PR reports a synthetic 200-sample test, a Linux build and an in-game RX 580 run.
Overlaps and merge order: Not checked; the network is closed.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
@ -189,0 +203,4 @@sigjmp_buf escape;if (!sigsetjmp(escape, 1)) {walk_escape = &escape;_Unwind_Backtrace(walk_step, (void *)&w);L5 (should fix): The Linux sampler change still needs a run on affected Tier 1 hardware.
When: The only reported game run is on an RX 580; Linux Tier 1 NVIDIA, newer AMD and Steam Deck setups can execute the same signal and unwind path.
Do: Run profiling on representative Tier 1 Linux hardware, exercising sampling and confirming the game and profile remain usable.
@ -200,6 +222,7 @@ static void sampling_init(void) {sa.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;sigemptyset(&sa.sa_mask);sigaction(SAMPLE_SIG, &sa, NULL);AddVectoredExceptionHandler(1, walk_fault); /* (ahead of the game's: a walk's fault is never the guest's) */L1 (blocking): The recovery handler is installed after the unsynchronized initialization guard has let another sampler proceed.
When: With HOS_SAMPLE and HOS_SAMPLE_ALL enabled together, both sampler threads can enter sampling_init. One increments done and pauses before registering walk_fault; the other returns from sampling_init and can signal a thread whose unwind faults, taking the game down before the handler is installed.
Do: Use a once primitive that makes all sampler threads wait until signal setup, handler registration and unwinder warm-up have completed before sampling starts.
@ -0,0 +19,4 @@import sysimport tempfileRUN_ALL_ARGS = ["--cc", "clang"]L3 (should fix): The test hard-codes clang instead of honoring the configured C compiler.
When: On a supported Linux development setup with CC pointing to GCC and no clang on PATH, run_all skips this check even though a usable compiler is configured; it also never exercises the GCC build.
Do: Use the runner's {cc} compiler and the repository's compiler-argument parsing convention, and honor CC for standalone runs.
@ -0,0 +51,4 @@__asm__(".text\n.globl bad_cfi\n.type bad_cfi,@function\nbad_cfi:\n.cfi_startproc\n""mov $0x10, %r12\n.cfi_def_cfa %r12, 0\n1: pause\njmp 1b\n.cfi_endproc\n.size bad_cfi,.-bad_cfi\n");void bad_cfi(void);static volatile int spinner;L4 (should fix): The test publishes spinner between threads using volatile accesses rather than atomic synchronization.
When: The worker writes spinner while the main thread polls and reads it without synchronization, which is a C data race and makes the test's startup behavior undefined.
Do: Publish and read the thread ID with atomic release and acquire operations.
@ -0,0 +106,4 @@print("skip: the walk is Linux's, the bad frame x86-64's")returnsrc = (ROOT / "host/posix/prof.c").read_text(encoding="utf-8")piece = between(src, "/* ---- one thread's stack, taken inside it ---- */", "static void sampling_init(void)")L2 (should fix): The test excludes sampling_init and calls walk_fault directly from its substitute fault handler, bypassing the production registration.
When: Removing AddVectoredExceptionHandler(1, walk_fault) leaves this test unchanged and passing, while a fault in an actual sampled walk reaches the normal crash handler and ends the game.
Do: Exercise production initialization and exception dispatch in the harness, including registration of walk_fault, so removing that registration makes the test fail.
c06e8c2353a97818a433Review addressed in
aa9c9e16(test) anda97818a4(fix), pushed. Both commits were amended, and the two-commit shape is kept.sampling_init(signal setup,walk_fault's registration, unwinder warm-up) is nowsampling_setup.sampling_initruns it throughpthread_once, so every sampler thread waits until it has finished. (The olddone++guard came from main; it was racy there too, but only now does it guard something that matters.)sampling_init, and the harness calls it. The fault handler goes only through a list of vectored handlers, filled by anAddVectoredExceptionHandlerthat works likewin32_posix.c's. Nothing callswalk_faultby name any more. If the registration line is removed, the test fails: in the cut,walk_faultis then unused, which-Werrorrejects, the same warning the real build would give.RUN_ALL_ARGS = ["--cc", "{cc}"], the default isCCor elsecc, and the value is split withshlex. I ran it with both gcc and clang.spinneris now a plainint, stored with__ATOMIC_RELEASEand loaded with__ATOMIC_ACQUIRE.Results: on the test commit (main's
prof.c) the test fails with signal 11. On the fix it passes all 200 samples, with gcc and with clang. Onedev.py packon the shared base compiled cleanly. The in-game RX 580 run in the description predates thepthread_oncechange.WIP: fix(prof): a stack walk that faults cuts its sample short instead of ending the gameto fix(prof): a stack walk that faults cuts its sample short instead of ending the game