Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/debugging.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/loader.md
Original file line number Diff line number Diff line change
Expand Up @@ -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\|<compute>,<geometry>,<pixel>` | 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 |
Expand Down
14 changes: 14 additions & 0 deletions src/FiveStar.Loader/Diagnostics/GameHangWatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> _counters;
private readonly Func<ulong, ulong, string> _fenceWait;
private readonly LoaderLog _log;
Expand All @@ -55,6 +56,7 @@ internal sealed unsafe class GameHangWatch
private GameHangWatch(ImageTable images, Func<string> counters, Func<ulong, ulong, string> fenceWait, LoaderLog log)
{
_stacks = new ThreadStacks(images, MaxFrames);
_images = images;
_counters = counters;
_fenceWait = fenceWait;
_log = log;
Expand Down Expand Up @@ -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();
}
}

/// <summary>The game's events and semaphores that blocked threads wait on (<see cref="WaitObjects"/>), when any.</summary>
private void LogWaitObjects()
{
string report = WaitObjects.Report(_images, Prefix);

if (report.Length != 0)
{
_log.Info(report);
}
}

/// <summary>
/// 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).
Expand Down
7 changes: 7 additions & 0 deletions src/FiveStar.Loader/Diagnostics/ThreadWait.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Copyright (c) 2026 Five Star Recomp contributors.
// SPDX-License-Identifier: GPL-3.0-or-later

namespace FiveStar.Loader.Diagnostics;

/// <summary>A thread's wait in progress (<see cref="WaitObjects"/>): the handle, the timeout, the start in seconds.</summary>
internal readonly record struct ThreadWait(nint Handle, uint Milliseconds, double Since);
60 changes: 60 additions & 0 deletions src/FiveStar.Loader/Diagnostics/WaitObject.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>An event or semaphore of the game (<see cref="WaitObjects"/>): how it was made and when it was last signaled.</summary>
internal sealed class WaitObject
{
/// <summary>Frames of the creating call shown: those in mapped images (the game and its manual modules).</summary>
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++;
}
}

/// <summary>"auto-reset event made by thread T at S s from game+0x.. &lt;- ..; signaled N times, last ..".</summary>
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}");
}
}
138 changes: 138 additions & 0 deletions src/FiveStar.Loader/Diagnostics/WaitObjects.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// The game's events and semaphores and the threads that wait on them (<c>--watch-hang</c>, through
/// <see cref="Shims.WaitObjectShims"/>): 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.
/// </summary>
internal static unsafe class WaitObjects
{
/// <summary>The return addresses kept per creation.</summary>
private const int Frames = 12;

/// <summary>Waits shorter than this are not reported.</summary>
private const double ReportedSeconds = 1;

private static readonly ConcurrentDictionary<nint, WaitObject> Objects = new();
private static readonly ConcurrentDictionary<uint, ThreadWait> Waits = new();
private static readonly Stopwatch Clock = Stopwatch.StartNew();

private static double Now => Clock.Elapsed.TotalSeconds;

/// <summary>A created object: its kind, the creating thread and the return addresses of the creating call.</summary>
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);
}

/// <summary>The object was set or released by the calling thread.</summary>
public static void Signaled(nint handle)
{
if (Objects.TryGetValue(handle, out var item))
{
item.Signal(Native.Kernel32.GetCurrentThreadId(), Now);
}
}

/// <summary>The handle was closed: a later object may get the same value.</summary>
public static void Closed(nint handle)
{
Objects.TryRemove(handle, out _);
}

/// <summary>The calling thread starts waiting on <paramref name="handle"/> for <paramref name="milliseconds"/>.</summary>
public static void Waiting(nint handle, uint milliseconds)
{
Waits[Native.Kernel32.GetCurrentThreadId()] = new ThreadWait(handle, milliseconds, Now);
}

/// <summary>The calling thread's wait ended.</summary>
public static void Done()
{
Waits.TryRemove(Native.Kernel32.GetCurrentThreadId(), out _);
}

/// <summary>
/// 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.
/// </summary>
public static string Report(ImageTable images, string prefix)
{
return Report(images, prefix, ReportedSeconds);
}

/// <summary>The same for waits of <paramref name="seconds"/> or more.</summary>
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";
}

/// <summary>The return addresses above the shim, innermost first (the managed and stub frames are dropped later).</summary>
private static int Kernel32Frames(nint* frames)
{
return Native.Kernel32.RtlCaptureStackBackTrace(0, Frames, frames, null);
}
}
9 changes: 9 additions & 0 deletions src/FiveStar.Loader/Host/LoaderHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
19 changes: 19 additions & 0 deletions src/FiveStar.Loader/Native/Kernel32.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

/// <summary>RtlCaptureStackBackTrace: the return addresses of the calling thread, innermost first.</summary>
[DllImport(Library)]
public static extern ushort RtlCaptureStackBackTrace(uint skip, uint count, nint* frames, uint* hash);

/// <summary>GetFileInformationByHandle: <paramref name="information"/> is a BY_HANDLE_FILE_INFORMATION.</summary>
[DllImport(Library, SetLastError = true)]
public static extern int GetFileInformationByHandle(nint file, void* information);
Expand Down
Loading
Loading