diff --git a/docs/debugging.md b/docs/debugging.md index 6f001666..dcfe14c5 100644 --- a/docs/debugging.md +++ b/docs/debugging.md @@ -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 diff --git a/src/FiveStar.Loader/Diagnostics/ThreadWait.cs b/src/FiveStar.Loader/Diagnostics/ThreadWait.cs index b7921bfe..4959102e 100644 --- a/src/FiveStar.Loader/Diagnostics/ThreadWait.cs +++ b/src/FiveStar.Loader/Diagnostics/ThreadWait.cs @@ -3,5 +3,12 @@ namespace FiveStar.Loader.Diagnostics; -/// A thread's wait in progress (): the handle, the timeout, the start in seconds, the game frames that called the wait. -internal readonly record struct ThreadWait(nint Handle, uint Milliseconds, double Since, nint[] Frames); +/// A thread's wait the shims saw: on , or on (the first is ). +internal readonly record struct ThreadWait(nint Handle, uint Milliseconds, double Since, nint[] Frames) +{ + /// Every object of a wait on several; null for a wait on one. + public nint[]? Several { get; init; } + + /// Whether a wait on several waits for all of them, not any. + public bool All { get; init; } +} diff --git a/src/FiveStar.Loader/Diagnostics/WaitObject.cs b/src/FiveStar.Loader/Diagnostics/WaitObject.cs index 43688b48..a0c9b425 100644 --- a/src/FiveStar.Loader/Diagnostics/WaitObject.cs +++ b/src/FiveStar.Loader/Diagnostics/WaitObject.cs @@ -12,11 +12,16 @@ 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; + /// Operations kept per object (signals, resets, waits and wake-ups), for a lost wake-up. + 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) { @@ -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)); } } + /// Keeps among the object's last . + public void Record(WaitOperation operation) + { + lock (_gate) + { + AddOperation(operation); + } + } + + private void AddOperation(WaitOperation operation) + { + _operations[_nextOperation % KeptOperations] = operation; + _nextOperation++; + } + + /// The kept operations, oldest first, as "-27.6 s signaled by 14500 at game+0x.., ..". + private string History(ImageTable images, double now) + { + long first = Math.Max(0, _nextOperation - KeptOperations); + var shown = new List(); + + 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); + } + /// The frames in mapped images, as "game+0x.. <- ..", or "no game frame found". public static string Frames(nint[] frames, ImageTable images) { @@ -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}"); } } diff --git a/src/FiveStar.Loader/Diagnostics/WaitObjects.cs b/src/FiveStar.Loader/Diagnostics/WaitObjects.cs index a41ccceb..3a3e3a68 100644 --- a/src/FiveStar.Loader/Diagnostics/WaitObjects.cs +++ b/src/FiveStar.Loader/Diagnostics/WaitObjects.cs @@ -23,6 +23,13 @@ internal static unsafe class WaitObjects /// Waits shorter than this are not reported. 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; + + /// MAXIMUM_WAIT_OBJECTS (winnt.h). + private const uint MaximumWaitObjects = 64; + private static readonly ConcurrentDictionary Objects = new(); private static readonly ConcurrentDictionary Waits = new(); private static readonly Stopwatch Clock = Stopwatch.StartNew(); @@ -37,7 +44,7 @@ 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)); } /// The object was set or released by the calling thread. @@ -45,7 +52,73 @@ 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()); + } + } + + /// The event was reset by the calling thread: a signal nobody waited for is gone. + public static void Reset(nint handle) + { + Record(handle, "reset"); + } + + /// The calling thread starts waiting on any (or all, ) of . + public static void WaitingOnSeveral(ReadOnlySpan 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)); + } + } + + /// + /// A wait on any (or all, ) of returned : 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. + /// + public static void DoneOnSeveral(ReadOnlySpan 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); } } @@ -58,13 +131,68 @@ public static void Closed(nint handle) /// The calling thread starts waiting on for . 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)); } - /// The calling thread's wait ended. - public static void Done() + /// The calling thread's wait on returned (WAIT_OBJECT_0, WAIT_TIMEOUT, ..). + 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)); + } + } + + /// + /// 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. + /// + private static nint Caller() + { + return First(GameFrames(1)); + } + + private static nint First(nint[] frames) + { + if (frames.Length == 0) + { + return 0; + } + + return frames[0]; } /// @@ -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)) { @@ -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}"; } + /// What a wait is on: its handle, or for a wait on several which of them (the first is described). + 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}"; + } + /// A handle the shims did not see created: a thread's (a join on it), or another object. private static string NotSeen(nint handle) { @@ -137,7 +279,7 @@ private static string Timeout(uint milliseconds) } /// The game frames of the calling thread above the shim, innermost first (); none without a runtime. - private static nint[] GameFrames() + private static nint[] GameFrames(int count) { var runtime = Shims.ShimContext.ActiveRuntime; @@ -146,6 +288,6 @@ private static nint[] GameFrames() return []; } - return ReturnAddresses.Scan(runtime.Images, Frames); + return ReturnAddresses.Scan(runtime.Images, count); } } diff --git a/src/FiveStar.Loader/Diagnostics/WaitOperation.cs b/src/FiveStar.Loader/Diagnostics/WaitOperation.cs new file mode 100644 index 00000000..5c12b837 --- /dev/null +++ b/src/FiveStar.Loader/Diagnostics/WaitOperation.cs @@ -0,0 +1,7 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace FiveStar.Loader.Diagnostics; + +/// 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). +internal readonly record struct WaitOperation(string Verb, uint Thread, double At, nint Caller); diff --git a/src/FiveStar.Loader/Native/Kernel32.cs b/src/FiveStar.Loader/Native/Kernel32.cs index ec0f4b4b..e4ab1dd3 100644 --- a/src/FiveStar.Loader/Native/Kernel32.cs +++ b/src/FiveStar.Loader/Native/Kernel32.cs @@ -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); + /// GetCurrentThreadStackLimits: the calling thread's stack, lowest and highest address. [DllImport(Library)] public static extern void GetCurrentThreadStackLimits(nuint* low, nuint* high); diff --git a/src/FiveStar.Loader/Shims/WaitObjectShims.cs b/src/FiveStar.Loader/Shims/WaitObjectShims.cs index 924d0e78..83dfb63f 100644 --- a/src/FiveStar.Loader/Shims/WaitObjectShims.cs +++ b/src/FiveStar.Loader/Shims/WaitObjectShims.cs @@ -9,7 +9,7 @@ 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 +/// resets, closes and waits on one or several objects 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 @@ -20,11 +20,15 @@ internal static unsafe partial class WaitObjectShims /// CREATE_EVENT_MANUAL_RESET. private const uint ManualResetFlag = 1; + /// MAXIMUM_WAIT_OBJECTS: the most handles one wait takes. + private const uint MaximumWaitObjects = 64; + /// The shims, as "module!symbol" for . public static readonly string[] Names = [ "*!CreateEventW", "*!CreateEventA", "*!CreateEventExW", "*!CreateSemaphoreW", "*!CreateSemaphoreExW", "*!SetEvent", - "*!ReleaseSemaphore", "*!CloseHandle", "*!WaitForSingleObject", "*!WaitForSingleObjectEx", + "*!ReleaseSemaphore", "*!CloseHandle", "*!WaitForSingleObject", "*!WaitForSingleObjectEx", "*!ResetEvent", + "*!WaitForMultipleObjects", ]; [Shim("*", "CreateEventW", SetsLastError = true)] @@ -223,11 +227,53 @@ 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(); + WaitObjects.Done(handle, result); return result; } + [Shim("*", "ResetEvent", SetsLastError = true)] + [UnmanagedCallersOnly] + private static int ResetEvent(nint handle) + { + try + { + WaitObjects.Reset(handle); + int done = Kernel32.ResetEvent(handle); + ShimContext.Runtime.LastError.Set(Marshal.GetLastPInvokeError()); + + return done; + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.ResetEvent"); + + return default; + } + } + + [Shim("*", "WaitForMultipleObjects", SetsLastError = true)] + [UnmanagedCallersOnly] + private static uint WaitForMultipleObjects(uint count, nint* handles, int waitAll, uint milliseconds) + { + try + { + var span = new ReadOnlySpan(handles, (int)Math.Min(count, MaximumWaitObjects)); + WaitObjects.WaitingOnSeveral(span, waitAll != 0, milliseconds); + uint result = Kernel32.WaitForMultipleObjects(count, handles, waitAll, milliseconds); + ShimContext.Runtime.LastError.Set(Marshal.GetLastPInvokeError()); + WaitObjects.DoneOnSeveral(span, waitAll != 0, result); + + return result; + } + catch (Exception exception) + { + UnmanagedGuard.Caught(exception, "WaitObjectShims.WaitForMultipleObjects"); + + return WaitFailed; + } + } + private static string EventKind(int manualReset) { if (manualReset != 0) diff --git a/tests/FiveStar.Loader.Tests/WaitObjectsTests.cs b/tests/FiveStar.Loader.Tests/WaitObjectsTests.cs index a946ed41..5b744cd0 100644 --- a/tests/FiveStar.Loader.Tests/WaitObjectsTests.cs +++ b/tests/FiveStar.Loader.Tests/WaitObjectsTests.cs @@ -33,14 +33,15 @@ public void A_blocked_wait_names_its_event_and_its_last_signal() WaitObjects.Waiting(never, uint.MaxValue); blocked.Set(); _ = Kernel32.WaitForSingleObjectEx(never, uint.MaxValue, 0); - WaitObjects.Done(); + WaitObjects.Done(never, 0); }); 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; waiting at no game frame found", report, StringComparison.Ordinal); + Assert.Contains("never signaled; recent: ", report, StringComparison.Ordinal); + Assert.Contains("; waiting at no game frame found", report, StringComparison.Ordinal); // The signal is recorded with its thread, and the wait ends. WaitObjects.Signaled(never); @@ -57,6 +58,89 @@ public void A_blocked_wait_names_its_event_and_its_last_signal() } } + [Fact] + public void A_blocked_wait_lists_the_last_operations_on_its_object() + { + nint idle = Kernel32.CreateEventW(0, 0, 0, null); + nint other = Kernel32.CreateEventW(0, 0, 0, null); + uint self = Kernel32.GetCurrentThreadId(); + + try + { + WaitObjects.Created(idle, "auto-reset event"); + WaitObjects.Created(other, "auto-reset event"); + + // A signal, a wait on several objects that it ends, then a reset: the signal the next waiter expects is gone. + WaitObjects.Signaled(idle); + WaitObjects.WaitingOnSeveral([other, idle], all: false, uint.MaxValue); + WaitObjects.DoneOnSeveral([other, idle], all: false, 1); + WaitObjects.Reset(idle); + + uint waiterId = 0; + using var blocked = new ManualResetEventSlim(); + var waiter = new Thread(() => + { + waiterId = Kernel32.GetCurrentThreadId(); + WaitObjects.Waiting(idle, uint.MaxValue); + blocked.Set(); + uint result = Kernel32.WaitForSingleObjectEx(idle, uint.MaxValue, 0); + WaitObjects.Done(idle, result); + }); + + waiter.Start(); + blocked.Wait(); + + string report = WaitObjects.Report(new ImageTable(), Prefix, 0); + Assert.Matches($@"recent: -\d+\.\d s signaled by {self}, -\d+\.\d s wait on any of 2 by {self}, -\d+\.\d s woke by {self}, -\d+\.\d s reset by {self}, -\d+\.\d s wait by {waiterId}", report); + + Assert.NotEqual(0, Kernel32.SetEvent(idle)); + waiter.Join(); + WaitObjects.Waiting(idle, 0); + Assert.Contains($"woke by {waiterId}", WaitObjects.Report(new ImageTable(), Prefix, 0), StringComparison.Ordinal); + WaitObjects.Done(idle, 0x102); + } + finally + { + WaitObjects.Closed(idle); + WaitObjects.Closed(other); + _ = Kernel32.CloseHandle(idle); + _ = Kernel32.CloseHandle(other); + } + } + + /// A wait on several objects is reported as one of them, and its timeout is kept by every one. + [Fact] + public void A_wait_on_several_objects_names_them_all_and_its_timeout_stays_on_each() + { + nint first = Kernel32.CreateEventW(0, 0, 0, null); + nint second = Kernel32.CreateEventW(0, 0, 0, null); + uint self = Kernel32.GetCurrentThreadId(); + + try + { + WaitObjects.Created(first, "auto-reset event"); + WaitObjects.Created(second, "auto-reset event"); + + WaitObjects.WaitingOnSeveral([first, second], all: false, 10); + Assert.Contains($"on one of 2 handles (0x{first:x}, 0x{second:x}), the first 0x{first:x}: ", WaitObjects.Report(new ImageTable(), Prefix, 0), StringComparison.Ordinal); + WaitObjects.DoneOnSeveral([first, second], all: false, 0x102); + + foreach (var handle in new[] { first, second }) + { + WaitObjects.Waiting(handle, 0); + Assert.Matches($@"-\d+\.\d s timed out by {self}", WaitObjects.Report(new ImageTable(), Prefix, 0)); + WaitObjects.Done(handle, 0x102); + } + } + finally + { + WaitObjects.Closed(first); + WaitObjects.Closed(second); + _ = Kernel32.CloseHandle(first); + _ = Kernel32.CloseHandle(second); + } + } + [Fact] public void A_wait_on_a_thread_handle_names_the_thread_it_joins() { @@ -68,7 +152,7 @@ public void A_wait_on_a_thread_handle_names_the_thread_it_joins() { WaitObjects.Waiting(handle, uint.MaxValue); var report = WaitObjects.Report(new ImageTable(), Prefix, 0); - WaitObjects.Done(); + WaitObjects.Done(handle, 0); Assert.Contains($"on handle 0x{handle:x}: the handle of thread {Kernel32.GetCurrentThreadId()} (waiting for it to end)", report, StringComparison.Ordinal); }