diff --git a/docs/debugging.md b/docs/debugging.md index 6f44e095..672fc09e 100644 --- a/docs/debugging.md +++ b/docs/debugging.md @@ -134,7 +134,12 @@ since the start: those are a whole boot's, so seconds of them say nothing about `fivestar-loader --watch-hang` reads these globals every 100 ms and logs the main state, the loading-screen flags, the session byte, the pause flag and the handler when they change, a heartbeat that moves again after 2 s or more, and the loader counters and every thread's stack (64 frames, with thread names) when the heartbeat has stood still for 5, -15 and 25 s. For each thread in the game's fence wait (0x144fb0ad0) it also names what the wait depends on +15 and 25 s. With it the loader keeps shims on the game's CreateEventW/A, CreateSemaphoreExW, SetEvent, +ReleaseSemaphore, CloseHandle and WaitForSingleObject(Ex) (`WaitObjectShims`, removed otherwise), and the dump lists +every thread blocked a second or more in one of those waits: the handle, the timeout, how the object was made (event +kind or semaphore counts, creating thread and time, the game frames of the creating call) and whether it was signaled +since, how often and by which thread last (`WaitObjects`). A stall whose waiter sits on an object nobody signals any +more (a lost wake-up) then names that object and its creator. For each thread in the game's fence wait (0x144fb0ad0) it also names what the wait depends on (`StallCulprit`): the queue that was asked to signal that fence to the awaited value and the last six executions it was given before that Signal, newest first, each with its last pipeline and whether it finished, and any Wait on another fence among them; or, when no queue was asked yet, the fence's last Signal. The queues keep their last 1,024 calls in diff --git a/docs/loader.md b/docs/loader.md index d720bf3f..a3d9362b 100644 --- a/docs/loader.md +++ b/docs/loader.md @@ -390,7 +390,7 @@ fivestar-loader --load $dump\XboxBvhBuilder.dll --load $dump\Bink2Scarlett.dll - | `--d3d12-breadcrumbs` | a GPU marker before every draw and dispatch, so a stalled queue names the operation and pipeline it stopped at ([d3d12x-shim.md](d3d12x-shim.md#queue-progress)) | | `--watch-transient` | checks the game's transient-memory pool every 5 ms and logs the first corrupted node list with the memory around it and the queues ([debugging.md](debugging.md#transient-pool-watch)) | | `--watch-pool-pages` | finds the game's small-block pool pages (16 KiB, header at the page start) in its coherent graphics memory and checks their headers, and their pools' current pages, every 100 ms; a header its allocator cannot have written (an offset outside the page, a garbage next-offset, a counter that did not move forward) is logged with the page, its first bytes and every queue's executions retired since the last check ([debugging.md](debugging.md#pool-page-watch)) | -| `--watch-hang` | logs the game's main state, loading-screen flags and watchdog handler as they change, and every thread's stack while the heartbeat its 30 s hang watchdog checks stands still ([debugging.md](debugging.md#hang-watchdog)) | +| `--watch-hang` | logs the game's main state, loading-screen flags and watchdog handler as they change, and every thread's stack while the heartbeat its 30 s hang watchdog checks stands still, with the event or semaphore each blocked thread waits on, its creator and its last signal ([debugging.md](debugging.md#hang-watchdog)) | | `--skip-compute-chains` | skips the rest of a command list's dispatches and ExecuteIndirects after one skipped for a stand-in (off by default; [d3d12x-pipelines.md](d3d12x-pipelines.md#stand-ins)) | | `--loop-caps victory\|default\|,,` | loop caps of programs made on demand ([shader-translation.md](shader-translation.md#loop-guard)); part of the program cache identity | | `--host-pipelines` | pipelines of more than 2 MB of DXIL are built first in a pipeline host held to memory and time limits ([d3d12x-pipelines.md](d3d12x-pipelines.md#stand-ins)); off by default | diff --git a/src/FiveStar.Loader/Diagnostics/GameHangWatch.cs b/src/FiveStar.Loader/Diagnostics/GameHangWatch.cs index cf74d068..8bead4ca 100644 --- a/src/FiveStar.Loader/Diagnostics/GameHangWatch.cs +++ b/src/FiveStar.Loader/Diagnostics/GameHangWatch.cs @@ -47,6 +47,7 @@ internal sealed unsafe class GameHangWatch private const double StallSeconds = 2; private readonly ThreadStacks _stacks; + private readonly ImageTable _images; private readonly Func _counters; private readonly Func _fenceWait; private readonly LoaderLog _log; @@ -55,6 +56,7 @@ internal sealed unsafe class GameHangWatch private GameHangWatch(ImageTable images, Func counters, Func fenceWait, LoaderLog log) { _stacks = new ThreadStacks(images, MaxFrames); + _images = images; _counters = counters; _fenceWait = fenceWait; _log = log; @@ -120,10 +122,22 @@ private void Run() string stall = BlockingWaits.Summary("loader waits since the heartbeat last moved, all threads", BlockingWaits.Snapshot(), waitsAtBeat); _log.Info($"{Prefix}{now:F1} s: heartbeat still for {now - beatAt:F1} s; {stall}; {BlockingWaits.Summary()}; {_counters()}"); _stacks.Log(_log, Prefix); + LogWaitObjects(); LogFenceWaits(); } } + /// The game's events and semaphores that blocked threads wait on (), when any. + private void LogWaitObjects() + { + string report = WaitObjects.Report(_images, Prefix); + + if (report.Length != 0) + { + _log.Info(report); + } + } + /// /// Each thread in the game's fence-wait loop (0x144fb0ad0, which keeps the target value in RSI and the polled cell in /// RDI): the value it waits for, the cell's value now and the fence behind the cell (last Signal, desktop value). diff --git a/src/FiveStar.Loader/Diagnostics/ThreadWait.cs b/src/FiveStar.Loader/Diagnostics/ThreadWait.cs new file mode 100644 index 00000000..76c3e5ec --- /dev/null +++ b/src/FiveStar.Loader/Diagnostics/ThreadWait.cs @@ -0,0 +1,7 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace FiveStar.Loader.Diagnostics; + +/// A thread's wait in progress (): the handle, the timeout, the start in seconds. +internal readonly record struct ThreadWait(nint Handle, uint Milliseconds, double Since); diff --git a/src/FiveStar.Loader/Diagnostics/WaitObject.cs b/src/FiveStar.Loader/Diagnostics/WaitObject.cs new file mode 100644 index 00000000..ce08cce3 --- /dev/null +++ b/src/FiveStar.Loader/Diagnostics/WaitObject.cs @@ -0,0 +1,60 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +using System.Globalization; +using FiveStar.Loader.Loading; + +namespace FiveStar.Loader.Diagnostics; + +/// An event or semaphore of the game (): how it was made and when it was last signaled. +internal sealed class WaitObject +{ + /// Frames of the creating call shown: those in mapped images (the game and its manual modules). + private const int ShownFrames = 6; + + private readonly object _gate = new(); + private readonly nint[] _frames; + private uint _signaler; + private double _signaledAt = -1; + private long _signals; + + public WaitObject(string kind, uint creator, double createdAt, nint[] frames) + { + Kind = kind; + Creator = creator; + CreatedAt = createdAt; + _frames = frames; + } + + public string Kind { get; } + + public uint Creator { get; } + + public double CreatedAt { get; } + + public void Signal(uint thread, double at) + { + lock (_gate) + { + _signaler = thread; + _signaledAt = at; + _signals++; + } + } + + /// "auto-reset event made by thread T at S s from game+0x.. <- ..; signaled N times, last ..". + public string Describe(ImageTable images, double now) + { + var made = _frames.Where(frame => images.FindByAddress(frame) is not null).Take(ShownFrames).Select(images.Describe); + string signal; + + lock (_gate) + { + signal = _signals == 0 + ? "never signaled" + : string.Create(CultureInfo.InvariantCulture, $"signaled {_signals} times, last {now - _signaledAt:F1} s ago by thread {_signaler}"); + } + + return string.Create(CultureInfo.InvariantCulture, $"{Kind} made by thread {Creator} at {CreatedAt:F1} s from {string.Join(" <- ", made)}; {signal}"); + } +} diff --git a/src/FiveStar.Loader/Diagnostics/WaitObjects.cs b/src/FiveStar.Loader/Diagnostics/WaitObjects.cs new file mode 100644 index 00000000..c51f52a1 --- /dev/null +++ b/src/FiveStar.Loader/Diagnostics/WaitObjects.cs @@ -0,0 +1,138 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Globalization; +using System.Text; +using FiveStar.Loader.Loading; + +namespace FiveStar.Loader.Diagnostics; + +/// +/// The game's events and semaphores and the threads that wait on them (--watch-hang, through +/// ): who created each object (the game frames of the creating call), when it was +/// last signaled and by which thread, and which object each blocked thread waits on since when. A lost wake-up, a +/// wait whose object nobody signals any more, then names the object and its creator instead of only the waiting stack. +/// +internal static unsafe class WaitObjects +{ + /// The return addresses kept per creation. + private const int Frames = 12; + + /// Waits shorter than this are not reported. + private const double ReportedSeconds = 1; + + private static readonly ConcurrentDictionary Objects = new(); + private static readonly ConcurrentDictionary Waits = new(); + private static readonly Stopwatch Clock = Stopwatch.StartNew(); + + private static double Now => Clock.Elapsed.TotalSeconds; + + /// A created object: its kind, the creating thread and the return addresses of the creating call. + public static void Created(nint handle, string kind) + { + if (handle == 0) + { + return; + } + + nint* frames = stackalloc nint[Frames]; + int count = Kernel32Frames(frames); + var addresses = new nint[count]; + + for (int index = 0; index < count; index++) + { + addresses[index] = frames[index]; + } + + Objects[handle] = new WaitObject(kind, Native.Kernel32.GetCurrentThreadId(), Now, addresses); + } + + /// The object was set or released by the calling thread. + public static void Signaled(nint handle) + { + if (Objects.TryGetValue(handle, out var item)) + { + item.Signal(Native.Kernel32.GetCurrentThreadId(), Now); + } + } + + /// The handle was closed: a later object may get the same value. + public static void Closed(nint handle) + { + Objects.TryRemove(handle, out _); + } + + /// The calling thread starts waiting on for . + public static void Waiting(nint handle, uint milliseconds) + { + Waits[Native.Kernel32.GetCurrentThreadId()] = new ThreadWait(handle, milliseconds, Now); + } + + /// The calling thread's wait ended. + public static void Done() + { + Waits.TryRemove(Native.Kernel32.GetCurrentThreadId(), out _); + } + + /// + /// One line per thread blocked for a second or more in a wait the shims saw, longest first: the object, its + /// creator and its last signal. Empty when there is none. + /// + public static string Report(ImageTable images, string prefix) + { + return Report(images, prefix, ReportedSeconds); + } + + /// The same for waits of or more. + public static string Report(ImageTable images, string prefix, double seconds) + { + double now = Now; + var text = new StringBuilder(); + + foreach (var (thread, wait) in Waits.ToArray().OrderBy(pair => pair.Value.Since)) + { + double waited = now - wait.Since; + + if (waited < seconds) + { + continue; + } + + text.Append(CultureInfo.InvariantCulture, $"\n{prefix} thread {thread} waits {waited:F1} s ({Timeout(wait.Milliseconds)}) on handle 0x{wait.Handle:x}: "); + + if (Objects.TryGetValue(wait.Handle, out var item)) + { + text.Append(item.Describe(images, now)); + } + else + { + text.Append("not created through the shims"); + } + } + + if (text.Length == 0) + { + return string.Empty; + } + + return $"{prefix}threads blocked on the game's events and semaphores:{text}"; + } + + private static string Timeout(uint milliseconds) + { + if (milliseconds == uint.MaxValue) + { + return "no timeout"; + } + + return $"timeout {milliseconds} ms"; + } + + /// The return addresses above the shim, innermost first (the managed and stub frames are dropped later). + private static int Kernel32Frames(nint* frames) + { + return Native.Kernel32.RtlCaptureStackBackTrace(0, Frames, frames, null); + } +} diff --git a/src/FiveStar.Loader/Host/LoaderHost.cs b/src/FiveStar.Loader/Host/LoaderHost.cs index 22ffba49..bce01d0b 100644 --- a/src/FiveStar.Loader/Host/LoaderHost.cs +++ b/src/FiveStar.Loader/Host/LoaderHost.cs @@ -38,6 +38,15 @@ public LoaderHost(HostOptions options, LoaderRuntime runtime, LoaderLog log, int public int Run() { + // The wait-object shims cost a managed call on every wait; only the hang watch reads what they record. + if (!_options.WatchHang) + { + foreach (string shim in WaitObjectShims.Names) + { + _runtime.Shims.Disable(shim); + } + } + foreach (string spec in _options.DisabledShims) { if (!_runtime.Shims.Disable(spec)) diff --git a/src/FiveStar.Loader/Native/Kernel32.cs b/src/FiveStar.Loader/Native/Kernel32.cs index 5bbfa40e..feef7df0 100644 --- a/src/FiveStar.Loader/Native/Kernel32.cs +++ b/src/FiveStar.Loader/Native/Kernel32.cs @@ -179,6 +179,25 @@ internal static unsafe class Kernel32 [DllImport(Library, SetLastError = true)] public static extern nint CreateEventW(nint security, int manualReset, int initialState, char* name); + [DllImport(Library, SetLastError = true)] + public static extern nint CreateEventA(nint security, int manualReset, int initialState, byte* name); + + [DllImport(Library, SetLastError = true)] + public static extern nint CreateSemaphoreExW(nint security, int initial, int maximum, char* name, uint flags, uint access); + + [DllImport(Library, SetLastError = true)] + public static extern int SetEvent(nint handle); + + [DllImport(Library, SetLastError = true)] + public static extern int ReleaseSemaphore(nint handle, int count, int* previous); + + [DllImport(Library, SetLastError = true)] + public static extern uint WaitForSingleObjectEx(nint handle, uint milliseconds, int alertable); + + /// RtlCaptureStackBackTrace: the return addresses of the calling thread, innermost first. + [DllImport(Library)] + public static extern ushort RtlCaptureStackBackTrace(uint skip, uint count, nint* frames, uint* hash); + /// GetFileInformationByHandle: is a BY_HANDLE_FILE_INFORMATION. [DllImport(Library, SetLastError = true)] public static extern int GetFileInformationByHandle(nint file, void* information); diff --git a/src/FiveStar.Loader/Shims/WaitObjectShims.cs b/src/FiveStar.Loader/Shims/WaitObjectShims.cs new file mode 100644 index 00000000..4ea6c655 --- /dev/null +++ b/src/FiveStar.Loader/Shims/WaitObjectShims.cs @@ -0,0 +1,197 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +using System.Runtime.InteropServices; +using FiveStar.Loader.Diagnostics; +using FiveStar.Loader.Native; + +namespace FiveStar.Loader.Shims; + +/// +/// The game's events and semaphores, seen for (--watch-hang): creation, signals, +/// closes and single-object waits pass through to kernel32 unchanged. The loader removes these shims unless the hang +/// watch is on (), so a normal run calls kernel32 directly. +/// +internal static unsafe partial class WaitObjectShims +{ + /// The shims, as "module!symbol" for . + /// WAIT_FAILED. + private const uint WaitFailed = 0xFFFFFFFF; + + public static readonly string[] Names = + [ + "*!CreateEventW", "*!CreateEventA", "*!CreateSemaphoreExW", "*!SetEvent", "*!ReleaseSemaphore", "*!CloseHandle", + "*!WaitForSingleObject", "*!WaitForSingleObjectEx", + ]; + + [Shim("*", "CreateEventW", SetsLastError = true)] + [UnmanagedCallersOnly] + private static nint CreateEventW(nint security, int manualReset, int initialState, char* name) + { + try + { + nint handle = Kernel32.CreateEventW(security, manualReset, initialState, name); + ShimContext.Runtime.LastError.Set(Marshal.GetLastPInvokeError()); + WaitObjects.Created(handle, EventKind(manualReset)); + + return handle; + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.CreateEventW"); + + return default; + } + } + + [Shim("*", "CreateEventA", SetsLastError = true)] + [UnmanagedCallersOnly] + private static nint CreateEventA(nint security, int manualReset, int initialState, byte* name) + { + try + { + nint handle = Kernel32.CreateEventA(security, manualReset, initialState, name); + ShimContext.Runtime.LastError.Set(Marshal.GetLastPInvokeError()); + WaitObjects.Created(handle, EventKind(manualReset)); + + return handle; + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.CreateEventA"); + + return default; + } + } + + [Shim("*", "CreateSemaphoreExW")] + [UnmanagedCallersOnly] + private static nint CreateSemaphoreExW(nint security, int initial, int maximum, char* name, uint flags, uint access) + { + try + { + nint handle = Kernel32.CreateSemaphoreExW(security, initial, maximum, name, flags, access); + WaitObjects.Created(handle, $"semaphore (initial {initial}, maximum {maximum})"); + + return handle; + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.CreateSemaphoreExW"); + + return default; + } + } + + [Shim("*", "SetEvent", SetsLastError = true)] + [UnmanagedCallersOnly] + private static int SetEvent(nint handle) + { + try + { + WaitObjects.Signaled(handle); + int done = Kernel32.SetEvent(handle); + ShimContext.Runtime.LastError.Set(Marshal.GetLastPInvokeError()); + + return done; + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.SetEvent"); + + return default; + } + } + + [Shim("*", "ReleaseSemaphore", SetsLastError = true)] + [UnmanagedCallersOnly] + private static int ReleaseSemaphore(nint handle, int count, int* previous) + { + try + { + WaitObjects.Signaled(handle); + int done = Kernel32.ReleaseSemaphore(handle, count, previous); + ShimContext.Runtime.LastError.Set(Marshal.GetLastPInvokeError()); + + return done; + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.ReleaseSemaphore"); + + return default; + } + } + + [Shim("*", "CloseHandle", SetsLastError = true)] + [UnmanagedCallersOnly] + private static int CloseHandle(nint handle) + { + try + { + WaitObjects.Closed(handle); + int done = Kernel32.CloseHandle(handle); + ShimContext.Runtime.LastError.Set(Marshal.GetLastPInvokeError()); + + return done; + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.CloseHandle"); + + return default; + } + } + + [Shim("*", "WaitForSingleObject", SetsLastError = true)] + [UnmanagedCallersOnly] + private static uint WaitForSingleObject(nint handle, uint milliseconds) + { + try + { + return Wait(handle, milliseconds, 0); + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.WaitForSingleObject"); + + return WaitFailed; + } + } + + [Shim("*", "WaitForSingleObjectEx", SetsLastError = true)] + [UnmanagedCallersOnly] + private static uint WaitForSingleObjectEx(nint handle, uint milliseconds, int alertable) + { + try + { + return Wait(handle, milliseconds, alertable); + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.WaitForSingleObjectEx"); + + return WaitFailed; + } + } + + private static uint Wait(nint handle, uint milliseconds, int alertable) + { + WaitObjects.Waiting(handle, milliseconds); + uint result = Kernel32.WaitForSingleObjectEx(handle, milliseconds, alertable); + ShimContext.Runtime.LastError.Set(Marshal.GetLastPInvokeError()); + WaitObjects.Done(); + + return result; + } + + private static string EventKind(int manualReset) + { + if (manualReset != 0) + { + return "manual-reset event"; + } + + return "auto-reset event"; + } +} diff --git a/tests/FiveStar.Loader.Tests/WaitObjectsTests.cs b/tests/FiveStar.Loader.Tests/WaitObjectsTests.cs new file mode 100644 index 00000000..6054eb51 --- /dev/null +++ b/tests/FiveStar.Loader.Tests/WaitObjectsTests.cs @@ -0,0 +1,58 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +using FiveStar.Loader.Diagnostics; +using FiveStar.Loader.Loading; +using FiveStar.Loader.Native; +using Xunit; + +namespace FiveStar.Loader.Tests; + +/// +/// A thread blocked on one of the game's events is reported with the object it waits on, how it was made and whether +/// anyone signaled it since: a lost wake-up names its object instead of only the waiting stack. +/// +public sealed unsafe class WaitObjectsTests +{ + private const string Prefix = " [hang] "; + + [Fact] + public void A_blocked_wait_names_its_event_and_its_last_signal() + { + nint never = Kernel32.CreateEventW(0, 1, 0, null); + nint released = Kernel32.CreateEventW(0, 0, 0, null); + + try + { + WaitObjects.Created(never, "manual-reset event"); + WaitObjects.Created(released, "auto-reset event"); + using var blocked = new ManualResetEventSlim(); + var waiter = new Thread(() => + { + WaitObjects.Waiting(never, uint.MaxValue); + blocked.Set(); + _ = Kernel32.WaitForSingleObjectEx(never, uint.MaxValue, 0); + WaitObjects.Done(); + }); + waiter.Start(); + blocked.Wait(); + + var report = WaitObjects.Report(new ImageTable(), Prefix, 0); + Assert.Contains($"(no timeout) on handle 0x{never:x}: manual-reset event made by thread {Kernel32.GetCurrentThreadId()}", report, StringComparison.Ordinal); + Assert.Contains("never signaled", report, StringComparison.Ordinal); + + // The signal is recorded with its thread, and the wait ends. + WaitObjects.Signaled(never); + Assert.NotEqual(0, Kernel32.SetEvent(never)); + waiter.Join(); + Assert.DoesNotContain($"0x{never:x}", WaitObjects.Report(new ImageTable(), Prefix, 0), StringComparison.Ordinal); + } + finally + { + WaitObjects.Closed(never); + WaitObjects.Closed(released); + _ = Kernel32.CloseHandle(never); + _ = Kernel32.CloseHandle(released); + } + } +}