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
4 changes: 2 additions & 2 deletions docs/debugging.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,10 @@ since the start: those are a whole boot's, so seconds of them say nothing about
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. With it the loader keeps shims on the game's CreateEventW/A/ExW, CreateSemaphoreW/ExW, SetEvent,
ReleaseSemaphore, CloseHandle and WaitForSingleObject(Ex) (`WaitObjectShims`, removed otherwise), and the dump lists
ReleaseSemaphore, ResetEvent, CloseHandle, WaitForSingleObject(Ex) and WaitForMultipleObjects (`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`), and the game frames of the waiting call. A handle the shims did
since, how often and by which thread last (`WaitObjects`), its last 12 operations (signaled, reset, wait, woke, timed out, abandoned, with the thread, the time before the dump and the game's calling address, the innermost frame only: a signal another wait took or a reset dropped shows there; a wait on several objects records its timeout on each), and the game frames of the waiting call (a wait on several names them all, "one of N" or "all of N"). A handle the shims did
not see made is named when it is a thread's (a join). Frames come from a scan of the thread's stack for return addresses
into the game (`ReturnAddresses`): a walk stops in the shims' generated code, and #13's first report named no creator. 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
Expand Down
11 changes: 9 additions & 2 deletions src/FiveStar.Loader/Diagnostics/ThreadWait.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,12 @@

namespace FiveStar.Loader.Diagnostics;

/// <summary>A thread's wait in progress (<see cref="WaitObjects"/>): the handle, the timeout, the start in seconds, the game frames that called the wait.</summary>
internal readonly record struct ThreadWait(nint Handle, uint Milliseconds, double Since, nint[] Frames);
/// <summary>A thread's wait the shims saw: on <see cref="Handle"/>, or on <see cref="Several"/> (the first is <see cref="Handle"/>).</summary>
internal readonly record struct ThreadWait(nint Handle, uint Milliseconds, double Since, nint[] Frames)
{
/// <summary>Every object of a wait on several; null for a wait on one.</summary>
public nint[]? Several { get; init; }

/// <summary>Whether a wait on several waits for all of them, not any.</summary>
public bool All { get; init; }
}
43 changes: 41 additions & 2 deletions src/FiveStar.Loader/Diagnostics/WaitObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@ 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;

/// <summary>Operations kept per object (signals, resets, waits and wake-ups), for a lost wake-up.</summary>
private const int KeptOperations = 12;

private readonly object _gate = new();
private readonly nint[] _frames;
private readonly WaitOperation[] _operations = new WaitOperation[KeptOperations];
private uint _signaler;
private double _signaledAt = -1;
private long _signals;
private long _nextOperation;

public WaitObject(string kind, uint creator, double createdAt, nint[] frames)
{
Expand All @@ -32,16 +37,48 @@ public WaitObject(string kind, uint creator, double createdAt, nint[] frames)

public double CreatedAt { get; }

public void Signal(uint thread, double at)
public void Signal(uint thread, double at, nint caller)
{
lock (_gate)
{
_signaler = thread;
_signaledAt = at;
_signals++;
AddOperation(new WaitOperation("signaled", thread, at, caller));
}
}

/// <summary>Keeps <paramref name="operation"/> among the object's last <see cref="KeptOperations"/>.</summary>
public void Record(WaitOperation operation)
{
lock (_gate)
{
AddOperation(operation);
}
}

private void AddOperation(WaitOperation operation)
{
_operations[_nextOperation % KeptOperations] = operation;
_nextOperation++;
}

/// <summary>The kept operations, oldest first, as "-27.6 s signaled by 14500 at game+0x.., ..".</summary>
private string History(ImageTable images, double now)
{
long first = Math.Max(0, _nextOperation - KeptOperations);
var shown = new List<string>();

for (long index = first; index < _nextOperation; index++)
{
var operation = _operations[index % KeptOperations];
string at = operation.Caller == 0 ? string.Empty : " at " + Frames([operation.Caller], images);
shown.Add(string.Create(CultureInfo.InvariantCulture, $"-{now - operation.At:F1} s {operation.Verb} by {operation.Thread}{at}"));
}

return string.Join(", ", shown);
}

/// <summary>The frames in mapped images, as "game+0x.. &lt;- ..", or "no game frame found".</summary>
public static string Frames(nint[] frames, ImageTable images)
{
Expand All @@ -60,14 +97,16 @@ public string Describe(ImageTable images, double now)
{
string made = Frames(_frames, images);
string signal;
string history;

lock (_gate)
{
signal = _signals == 0
? "never signaled"
: string.Create(CultureInfo.InvariantCulture, $"signaled {_signals} times, last {now - _signaledAt:F1} s ago by thread {_signaler}");
history = History(images, now);
}

return string.Create(CultureInfo.InvariantCulture, $"{Kind} made by thread {Creator} at {CreatedAt:F1} s from {made}; {signal}");
return string.Create(CultureInfo.InvariantCulture, $"{Kind} made by thread {Creator} at {CreatedAt:F1} s from {made}; {signal}; recent: {history}");
}
}
158 changes: 150 additions & 8 deletions src/FiveStar.Loader/Diagnostics/WaitObjects.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ internal static unsafe class WaitObjects
/// <summary>Waits shorter than this are not reported.</summary>
private const double ReportedSeconds = 1;

// winbase.h: WAIT_OBJECT_0, WAIT_TIMEOUT and WAIT_ABANDONED_0.
private const uint WaitTimeout = 0x102;
private const uint WaitAbandoned0 = 0x80;

/// <summary>MAXIMUM_WAIT_OBJECTS (winnt.h).</summary>
private const uint MaximumWaitObjects = 64;

private static readonly ConcurrentDictionary<nint, WaitObject> Objects = new();
private static readonly ConcurrentDictionary<uint, ThreadWait> Waits = new();
private static readonly Stopwatch Clock = Stopwatch.StartNew();
Expand All @@ -37,15 +44,81 @@ public static void Created(nint handle, string kind)
return;
}

Objects[handle] = new WaitObject(kind, Native.Kernel32.GetCurrentThreadId(), Now, GameFrames());
Objects[handle] = new WaitObject(kind, Native.Kernel32.GetCurrentThreadId(), Now, GameFrames(Frames));
}

/// <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);
item.Signal(Native.Kernel32.GetCurrentThreadId(), Now, Caller());
}
}

/// <summary>The event was reset by the calling thread: a signal nobody waited for is gone.</summary>
public static void Reset(nint handle)
{
Record(handle, "reset");
}

/// <summary>The calling thread starts waiting on any (or all, <paramref name="all"/>) of <paramref name="handles"/>.</summary>
public static void WaitingOnSeveral(ReadOnlySpan<nint> handles, bool all, uint milliseconds)
{
if (handles.IsEmpty)
{
return;
}

var frames = GameFrames(Frames);
Waits[Native.Kernel32.GetCurrentThreadId()] = new ThreadWait(handles[0], milliseconds, Now, frames) { Several = handles.ToArray(), All = all };
string verb = $"wait on any of {handles.Length}";

if (all)
{
verb = $"wait on all of {handles.Length}";
}

foreach (var handle in handles)
{
Record(handle, verb, First(frames));
}
}

/// <summary>
/// A wait on any (or all, <paramref name="all"/>) of <paramref name="handles"/> returned <paramref name="result"/>: the
/// object that woke it gets the wake-up (each one for a wait on all), an abandoned mutex its abandonment, and every
/// object a timeout or a failure.
/// </summary>
public static void DoneOnSeveral(ReadOnlySpan<nint> handles, bool all, uint result)
{
Waits.TryRemove(Native.Kernel32.GetCurrentThreadId(), out _);
nint caller = Caller();

if (result < handles.Length)
{
if (!all)
{
Record(handles[(int)result], "woke", caller);

return;
}
}
else if (result - WaitAbandoned0 < handles.Length)
{
if (!all)
{
Record(handles[(int)(result - WaitAbandoned0)], "abandoned", caller);

return;
}
}

string verb = Outcome(result);

foreach (var handle in handles)
{
Record(handle, verb, caller);
}
}

Expand All @@ -58,13 +131,68 @@ public static void Closed(nint handle)
/// <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, GameFrames());
var frames = GameFrames(Frames);
Waits[Native.Kernel32.GetCurrentThreadId()] = new ThreadWait(handle, milliseconds, Now, frames);
Record(handle, "wait", First(frames));
}

/// <summary>The calling thread's wait ended.</summary>
public static void Done()
/// <summary>The calling thread's wait on <paramref name="handle"/> returned <paramref name="result"/> (WAIT_OBJECT_0, WAIT_TIMEOUT, ..).</summary>
public static void Done(nint handle, uint result)
{
Waits.TryRemove(Native.Kernel32.GetCurrentThreadId(), out _);
Record(handle, Outcome(result));
}

private static string Outcome(uint result)
{
if (result == WaitTimeout)
{
return "timed out";
}

if (result >= WaitAbandoned0 && result < WaitAbandoned0 + MaximumWaitObjects)
{
return "abandoned";
}

if (result < MaximumWaitObjects)
{
return "woke";
}

return $"wait returned 0x{result:x}";
}

private static void Record(nint handle, string verb)
{
Record(handle, verb, Caller());
}

private static void Record(nint handle, string verb, nint caller)
{
if (Objects.TryGetValue(handle, out var item))
{
item.Record(new WaitOperation(verb, Native.Kernel32.GetCurrentThreadId(), Now, caller));
}
}

/// <summary>
/// The game's innermost return address above the shim, 0 when none was found. One frame only: it is taken on every
/// signal and wake-up, the very calls whose timing the hang watch is watching.
/// </summary>
private static nint Caller()
{
return First(GameFrames(1));
}

private static nint First(nint[] frames)
{
if (frames.Length == 0)
{
return 0;
}

return frames[0];
}

/// <summary>
Expand All @@ -91,7 +219,7 @@ public static string Report(ImageTable images, string prefix, double seconds)
continue;
}

text.Append(CultureInfo.InvariantCulture, $"\n{prefix} thread {thread} waits {waited:F1} s ({Timeout(wait.Milliseconds)}) on handle 0x{wait.Handle:x}: ");
text.Append(CultureInfo.InvariantCulture, $"\n{prefix} thread {thread} waits {waited:F1} s ({Timeout(wait.Milliseconds)}) on {Target(wait)}: ");

if (Objects.TryGetValue(wait.Handle, out var item))
{
Expand All @@ -113,6 +241,20 @@ public static string Report(ImageTable images, string prefix, double seconds)
return $"{prefix}threads blocked on the game's events and semaphores:{text}";
}

/// <summary>What a wait is on: its handle, or for a wait on several which of them (the first is described).</summary>
private static string Target(ThreadWait wait)
{
if (wait.Several is not { Length: > 1 } several)
{
return $"handle 0x{wait.Handle:x}";
}

string which = wait.All ? "all" : "one";
string handles = string.Join(", ", several.Select(handle => $"0x{handle:x}"));

return $"{which} of {several.Length} handles ({handles}), the first 0x{wait.Handle:x}";
}

/// <summary>A handle the shims did not see created: a thread's (a join on it), or another object.</summary>
private static string NotSeen(nint handle)
{
Expand All @@ -137,7 +279,7 @@ private static string Timeout(uint milliseconds)
}

/// <summary>The game frames of the calling thread above the shim, innermost first (<see cref="ReturnAddresses"/>); none without a runtime.</summary>
private static nint[] GameFrames()
private static nint[] GameFrames(int count)
{
var runtime = Shims.ShimContext.ActiveRuntime;

Expand All @@ -146,6 +288,6 @@ private static nint[] GameFrames()
return [];
}

return ReturnAddresses.Scan(runtime.Images, Frames);
return ReturnAddresses.Scan(runtime.Images, count);
}
}
7 changes: 7 additions & 0 deletions src/FiveStar.Loader/Diagnostics/WaitOperation.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>One operation on a wait object: what happened ("signaled", "reset", "wait", "woke", ..), by which thread, when, and the game's calling address (0: none found).</summary>
internal readonly record struct WaitOperation(string Verb, uint Thread, double At, nint Caller);
6 changes: 6 additions & 0 deletions src/FiveStar.Loader/Native/Kernel32.cs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,12 @@ internal static unsafe class Kernel32
[DllImport(Library, SetLastError = true)]
public static extern uint WaitForSingleObjectEx(nint handle, uint milliseconds, int alertable);

[DllImport(Library, SetLastError = true)]
public static extern int ResetEvent(nint handle);

[DllImport(Library, SetLastError = true)]
public static extern uint WaitForMultipleObjects(uint count, nint* handles, int waitAll, uint milliseconds);

/// <summary>GetCurrentThreadStackLimits: the calling thread's stack, lowest and highest address.</summary>
[DllImport(Library)]
public static extern void GetCurrentThreadStackLimits(nuint* low, nuint* high);
Expand Down
Loading
Loading