RynthCore/src/RynthCore.Engine/CrashDump.cs
Daniel Wallace 636f5d307a Engine robustness re-review follow-ups: crash-log flush ring, cast refusal, dump hold cap
- The native crash logger keeps the last 16 first-chance records in a static ring
  (pushed in the VEH: no I/O, no allocation, no loader call). A flush writes the ones
  not yet written, oldest first, each record once. Flushed from the last-chance filter
  and, through the new export RC_FlushCrashLog, from the engine's ExitProcess /
  TerminateProcess / RtlExitUserProcess / NtTerminateProcess detours on a crash code
  (raw unmanaged function pointer, resolved and primed at install). Recovers the fatal
  repeat of an address seen before, which the dedupe skips and which never reaches the
  last-chance filter when a handler terminates the process.
- EnqueueCast refuses during a world transition (CastSlot, pure) and counts the
  refusal in TransitionRejectedCount. The cast slot now owns the stop-wait note the
  cast drain keeps per cast (CastSlot.StopWaitNoted, reset by each queued cast before
  the publishing Volatile.Write of Pending), and DrainCasts reads the queue time once.
- The launcher's dump hold is capped at 15 min per client (DumpInProgressRule.Decide);
  past it the kill checks resume.
- CrashExitRule: ExitProcess(-1) (0xFFFFFFFF) is no longer a crash exit; the rest of
  the 0xC0000000-and-up range is unchanged, so CLR/C++ unhandled-exception exits
  (0xE0434352, 0xE06D7363) still skip managed work.
- The heartbeat line carries qrej=<TransitionRejectedCount>.

Tests: EngineRobustnessTests (adds CastSlot stop-wait and ActionRing.TryPeekAt checks),
CrashLogFilterTests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-12 17:18:00 -07:00

297 lines
13 KiB
C#

// ============================================================================
// RynthCore.Engine - CrashDump.cs
// Writes a minidump of THIS process via dbghelp!MiniDumpWriteDump. Used by
// MainThreadHangWatchdog to capture a real post-mortem the moment AC's main
// thread is confirmed permanently wedged — a targeted replacement for
// always-on procdump (which also dumped on every clean exit and every handled
// first-chance AV, so a .dmp's existence never meant a real crash).
//
// Also writes ONE full-memory dump when AC shows its OUT OF MEMORY box
// (MessageBoxHooks): that box is modal, so the process never crashes and Windows
// never writes a dump; the launcher later kills the client as wedged
// (AutoRestartWedgedClients, kept as it is). The hang dump is a small type and
// holds no heap, which is what an out-of-memory needs.
//
// Safe to call from a background thread: MiniDumpWriteDump suspends all other
// threads internally while it snapshots them, which is exactly what we want for
// a hang. The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire).
// ============================================================================
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine;
internal static class CrashDump
{
[DllImport("dbghelp.dll", SetLastError = true)]
private static extern bool MiniDumpWriteDump(
IntPtr hProcess,
uint processId,
SafeHandle hFile,
uint dumpType,
IntPtr exceptionParam,
IntPtr userStreamParam,
IntPtr callbackParam);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
// MINIDUMP_TYPE. ⚠ AC ships an ANCIENT dbghelp.dll 6.1 (2003) in its own
// directory; it's already loaded by base name, so [DllImport("dbghelp.dll")]
// binds to THAT, not the modern OS v10. dbghelp 6.1 predates
// MiniDumpWithThreadInfo (0x1000, added in 6.5) and REJECTS it with
// ERROR_INVALID_PARAMETER (87) — which is why every hang dump failed
// (diagnosed 2026-06-10). Use only flags 6.1 supports: MiniDumpNormal already
// carries ALL thread stacks (enough to read a deadlock's lock holder);
// WithHandleData (0x4, since 5.1) is kept. On any failure we retry bare Normal.
private const uint DumpTypePreferred = 0x00000000 | 0x00000004; // Normal + WithHandleData
private const uint DumpTypeFallback = 0x00000000; // Normal only (universally supported)
// MiniDumpWithFullMemory (0x2) is as old as MiniDumpNormal, so dbghelp 6.1 takes it.
private const uint DumpTypeFull = 0x00000002 | 0x00000004; // FullMemory + WithHandleData
private const uint DumpTypeFullFallback = 0x00000002; // FullMemory only
// dbghelp is single-threaded: every MiniDumpWriteDump in this process goes through this
// lock, so the hang watchdog's small dump can never run alongside the OOM full dump.
private static readonly object DumpLock = new();
/// <summary>
/// Write a minidump of the current process to Logs\dumps\. Best-effort;
/// never throws. Returns true on success and sets <paramref name="dumpPath"/>.
/// </summary>
internal static bool WriteSelfDump(string reason, out string dumpPath, string prefix = "hang")
{
dumpPath = string.Empty;
try
{
string dir = Path.Combine(LogPaths.LogDirectory, "dumps");
Directory.CreateDirectory(dir);
string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{stamp}.dmp");
return WriteDumpFile(dumpPath, DumpTypePreferred, DumpTypeFallback, reason);
}
catch (Exception ex)
{
RynthLog.Error($"CrashDump: exception {ex.GetType().Name}: {ex.Message}");
return false;
}
}
// Writes one dump to <paramref name="path"/>. On ERROR_INVALID_PARAMETER (87: AC's ancient
// dbghelp 6.1 rejected a flag) retries with <paramref name="fallbackType"/>. Never leaves a
// 0-byte or partial .dmp behind (it reads as a crash marker during triage; observed:
// hang_17692_20260611_114430.dmp, 0 bytes, main thread suspended mid-exception-dispatch).
private static bool WriteDumpFile(string path, uint type, uint fallbackType, string reason)
{
lock (DumpLock)
{
bool ok;
int err;
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
type, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
err = ok ? 0 : Marshal.GetLastWin32Error();
if (!ok && err == 87 && fallbackType != type)
{
fs.SetLength(0);
ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
fallbackType, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
err = ok ? 0 : Marshal.GetLastWin32Error();
if (ok) RynthLog.Error($"CrashDump: flags 0x{type:X} rejected by AC's old dbghelp 6.1 - wrote type 0x{fallbackType:X}, reason={reason}");
}
}
if (!ok)
{
RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} type=0x{type:X} reason={reason}");
try { File.Delete(path); } catch { }
return false;
}
long size = 0;
try { size = new FileInfo(path).Length; } catch { }
RynthLog.Error($"CrashDump: wrote {path} ({size / 1024}KB) reason={reason}");
return true;
}
}
// -- OUT OF MEMORY full-memory dump --------------------------------------
/// <summary>Full dumps kept in the Dumps folder (a full dump is about the size of the process).</summary>
internal const int OutOfMemoryDumpsKept = 3;
internal const string OutOfMemoryDumpPrefix = "acclient_oom_";
// Longest the showing thread waits for the dump writer before letting the box open anyway.
private const int FullDumpWaitMs = 300_000;
private static int _oomDumpLatch;
private static volatile bool _fullDumpInProgress;
private static volatile string? _fullDumpWrittenPath;
/// <summary>True while the OUT OF MEMORY full dump is being written (the watchdog holds off).</summary>
internal static bool FullDumpInProgress => _fullDumpInProgress;
/// <summary>The OUT OF MEMORY full dump written this session, or null.</summary>
internal static string? FullDumpWrittenPath => _fullDumpWrittenPath;
/// <summary>C:\Games\RynthCore\Dumps by default (beside Logs, under the install folder).</summary>
internal static string OutOfMemoryDumpDirectory => Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "Dumps");
/// <summary>
/// Once per process: write a full-memory dump to <see cref="OutOfMemoryDumpDirectory"/>, log
/// its path, and keep only the newest <see cref="OutOfMemoryDumpsKept"/> of these dumps.
/// Called on the thread about to show AC's OUT OF MEMORY box, which waits here until the
/// dump is written (on its own thread, so the showing thread's stack is captured at rest).
/// Never throws.
/// </summary>
internal static void WriteOutOfMemoryDumpOnce(string? reason)
{
if (Interlocked.Exchange(ref _oomDumpLatch, 1) != 0) return;
string why = "AC OUT OF MEMORY box: " + (reason ?? "?");
_fullDumpInProgress = true;
// The launcher reads this marker (DumpInProgressRule): MiniDumpWriteDump suspends every
// thread, so the log goes silent for the whole dump, which would otherwise read as a dead
// engine and get the client killed mid-dump.
try { RynthLog.Error($"{DumpMarkerStarted} pid={Environment.ProcessId} - AC OUT OF MEMORY box; writing one full-memory dump before it shows."); }
catch { }
Thread? writer = null;
try
{
writer = new Thread(() =>
{
// The flag stays up until the writer itself is done, even past a timed-out Join.
try { WriteOutOfMemoryDumpCore(why); }
finally { FinishFullDump(); }
}) { IsBackground = true, Name = "RynthCore.OomDump" };
writer.Start();
}
catch (Exception ex)
{
// No thread to be had (out of memory, after all): write it from this one.
try { RynthLog.Error($"CrashDump: dump thread failed to start ({ex.GetType().Name}) - writing on the calling thread."); } catch { }
writer = null;
}
try
{
if (writer == null)
{
try { WriteOutOfMemoryDumpCore(why); }
finally { FinishFullDump(); }
}
else if (!writer.Join(FullDumpWaitMs))
{
RynthLog.Error($"CrashDump: full dump still writing after {FullDumpWaitMs / 1000}s - letting the box open (the writer keeps going).");
}
}
catch (Exception ex)
{
try { RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}"); } catch { }
}
}
/// <summary>Log line written before the OUT OF MEMORY full dump starts (read by the launcher).</summary>
internal const string DumpMarkerStarted = RynthCore.Install.DumpInProgressRule.MarkerStarted;
/// <summary>Log line written once the writer has finished, whatever the outcome.</summary>
internal const string DumpMarkerEnded = RynthCore.Install.DumpInProgressRule.MarkerEnded;
private static void FinishFullDump()
{
_fullDumpInProgress = false;
try { RynthLog.Error($"{DumpMarkerEnded} pid={Environment.ProcessId}."); } catch { }
}
private static void WriteOutOfMemoryDumpCore(string reason)
{
try
{
string dir = OutOfMemoryDumpDirectory;
Directory.CreateDirectory(dir);
string path = Path.Combine(dir, $"{OutOfMemoryDumpPrefix}{Environment.ProcessId}_{DateTime.Now:yyyyMMdd_HHmmss}.dmp");
if (WriteDumpFile(path, DumpTypeFull, DumpTypeFullFallback, reason))
{
_fullDumpWrittenPath = path;
RynthLog.Error($"CrashDump: OUT OF MEMORY full-memory dump: {path}");
// Only after the new dump succeeded: a failed write never costs an older one.
PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept);
}
else
{
RynthLog.Error("CrashDump: OUT OF MEMORY full-memory dump FAILED; writing the small hang-type dump instead.");
WriteSelfDump(reason, out _, "oom-small");
}
}
catch (Exception ex)
{
RynthLog.Error($"CrashDump: OOM dump writer failed {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>
/// Deletes all but the newest <paramref name="keep"/> <paramref name="prefix"/>*.dmp files in
/// <paramref name="dir"/>. The folder is shared by every client: a dump whose name carries
/// the pid of ANOTHER process that is still running is never deleted (it may still be
/// writing it, or about to report it), and is not counted against <paramref name="keep"/>.
/// Never throws.
/// </summary>
internal static int PruneDumps(string dir, string prefix, int keep)
{
int deleted = 0;
try
{
FileInfo[] files = new DirectoryInfo(dir).GetFiles(prefix + "*.dmp");
Array.Sort(files, (a, b) => b.LastWriteTimeUtc.CompareTo(a.LastWriteTimeUtc));
int kept = 0;
int self = Environment.ProcessId;
foreach (FileInfo f in files)
{
int pid = DumpPid(f.Name, prefix);
if (pid > 0 && pid != self && IsProcessAlive(pid))
continue; // another live client's dump: not ours to delete
if (kept < Math.Max(0, keep)) { kept++; continue; }
string name = f.Name;
long length = 0;
try { length = f.Length; } catch { }
try
{
f.Delete();
deleted++;
RynthLog.Info($"CrashDump: pruned old dump {name} ({length / (1024 * 1024)}MB).");
}
catch { /* in use by a debugger, or already gone */ }
}
}
catch { }
return deleted;
}
/// <summary>The pid in "prefix&lt;pid&gt;_...dmp", or 0.</summary>
internal static int DumpPid(string fileName, string prefix)
{
if (!fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return 0;
int start = prefix.Length, end = start;
while (end < fileName.Length && char.IsDigit(fileName[end])) end++;
return end > start && int.TryParse(fileName.AsSpan(start, end - start), out int pid) ? pid : 0;
}
private static bool IsProcessAlive(int pid)
{
try
{
using var p = System.Diagnostics.Process.GetProcessById(pid);
return !p.HasExited;
}
catch
{
return false;
}
}
}