SOURCE DUMP v1

This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit fb20299e9d
4 changed files with 768360 additions and 0 deletions

View file

@ -0,0 +1,516 @@
using System.Globalization;
using System.Text;
using System.Threading.Channels;
using Brutal.Monitor.Common;
using Microsoft.Extensions.Logging;
namespace Brutal.Monitor.Logging;
/// <summary>
/// Writes log lines to file from a background thread fed by a bounded channel, so a log
/// call only ever touches memory. On overflow the oldest lines are dropped and counted.
/// Custom formatting runs on the writer thread, never the caller's.
/// </summary>
internal sealed class BackgroundLogWriter : IDisposable
{
private const int QueueCapacity = 8192;
private const int DrainWaitMs = 100;
// Platform newline as UTF-8, appended after each encoded line
private static readonly byte[] NewLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
// A raw line (null category) skips the formatter: markers and recovery notes
private readonly record struct Entry(LogLevel Level, string? Category, string Message);
private readonly Channel<Entry> _queue;
private FileStream? _file;
private byte[] _lineBuffer = new byte[8192]; // Writer-thread only, grown geometrically to fit the largest line seen
private Thread? _thread;
private long _totalDropped;
private long _reportedDropped; // Writer-thread only: drops already reported into the log
private long _linesWritten;
private long _bytesWritten;
private long _linesDiscarded; // Writer-thread only: lines drained with no file to take them
private volatile bool _writerFailed;
private int _disposed;
public BackgroundLogWriter()
{
// DropOldest counts each eviction, and a completed channel refuses writes quietly.
// One atomic per drop: the writer thread works out what is new to report from the total
_queue = Channel.CreateBounded<Entry>(
new BoundedChannelOptions(QueueCapacity)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
},
_ => Interlocked.Increment(ref _totalDropped)
);
}
/// <summary>Lines waiting for the writer thread, cheap enough to poll per frame.</summary>
public int QueueDepth => _queue.Reader.Count;
/// <summary>Lines the queue holds before the oldest are dropped.</summary>
public int Capacity => QueueCapacity;
/// <summary>Lines written to the log file so far.</summary>
public long LinesWritten => Interlocked.Read(ref _linesWritten);
/// <summary>UTF-8 bytes written to the log file so far.</summary>
public long BytesWritten => Interlocked.Read(ref _bytesWritten);
/// <summary>Lines lost to queue overflow so far.</summary>
public long LinesDropped => Interlocked.Read(ref _totalDropped);
/// <summary>Lines that reached the writer thread with no log file to take them.</summary>
public long LinesDiscarded => Interlocked.Read(ref _linesDiscarded);
/// <summary>True once the log file was given up after a write or flush failure.</summary>
public bool WriterFailed => _writerFailed;
/// <summary>Queue a raw line. Never blocks or throws; drops the oldest line when full.</summary>
public void Add(string message)
{
_queue.Writer.TryWrite(new Entry(LogLevel.None, null, message));
}
/// <summary>
/// Queue a log message. Formatting happens later on the writer thread.
/// </summary>
public void Add(LogLevel level, string category, string message)
{
_queue.Writer.TryWrite(new Entry(level, category, message));
}
/// <summary>Path being written to. Null if no file could be opened.</summary>
public string? LogFilePath { get; private set; }
/// <summary>Optional line formatter, read on the writer thread so it never costs a caller.</summary>
public Func<LogLevel, string, string, string>? LogFormatter { get; set; }
/// <summary>
/// Sweep dead runs' leftovers, then open this run's log file ("&lt;name&gt;.&lt;stamp&gt;.&lt;pid&gt;.log")
/// and start the writer thread. The directory must already exist.
/// </summary>
public void Open(LoggerOptions options, string name)
{
if (_thread is not null)
throw new InvalidOperationException("BackgroundLogWriter is already open");
// The caller creates the directory; resolved to a full path so the subprocess's own cwd never matters
var directory = Path.GetFullPath(options.LogDirectory);
if (!Directory.Exists(directory))
throw new DirectoryNotFoundException($"Log directory '{directory}' does not exist.");
// Nothing past this point may throw into startup; housekeeping is best effort
try
{
SweepDeadRuns(directory, name, options.MaxArchives);
}
catch (Exception) { }
var stem = MonitorFileNames.Stem(name, MonitorFileNames.ProcessStamp, Environment.ProcessId);
var logFilePath = Path.Combine(directory, $"{stem}.log");
try
{
// Unix would let the open succeed on a held file, so ownership is probed explicitly
if (File.Exists(logFilePath) && !LogArchiver.IsUnheld(logFilePath))
throw new IOException($"{logFilePath} already has a live writer");
// A raw stream: lines are encoded to UTF-8 once here, so a StreamWriter would only re-encode
_file = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read);
LogFilePath = logFilePath;
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
var flushInterval = Math.Max(options.FlushIntervalMs, DrainWaitMs);
_thread = new Thread(() => WriteLoop(flushInterval)) { Name = "Brutal.Monitor.LogWriter", IsBackground = true };
_thread.Start();
// Hosts that never dispose the Monitor would otherwise lose the queue tail
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
}
private void OnProcessExit(object? sender, EventArgs e)
{
Dispose();
}
/// <summary>
/// Recover dead runs' crash tails and archive their logs; files held by a live holder are left alone.
/// </summary>
private void SweepDeadRuns(string directory, string name, int maxArchives)
{
foreach (var ring in Directory.GetFiles(directory, $"{name}.*.ring"))
{
// A ring is named <name>.<stamp>.<pid>.log.ring, so two extensions off gives the stem
var stem = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(ring));
if (!IsRunFile(stem + ".log", name) || !LogArchiver.IsUnheld(ring))
continue;
var recovered = CrashTailSnapshot.TryWrite(ring, Path.Combine(directory, $"{stem}.previous-crash.log"));
if (recovered > 0)
Add($"[Brutal.Monitor] recovered {recovered} log lines from {Path.GetFileName(ring)}");
// A failed snapshot leaves the only copy of the tail in the ring; keep it for the next run to retry
if (recovered == CrashTailSnapshot.SnapshotFailed)
continue;
try
{
File.Delete(ring);
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
foreach (var log in Directory.GetFiles(directory, $"{name}.*.log"))
{
// A locked log fails rotation and belongs to a live instance anyway
if (IsRunFile(log, name))
LogArchiver.TryRotate(log, name, maxArchives);
}
PruneRecoveredTails(directory, name, maxArchives);
}
/// <summary>
/// Tails recovered from dead runs pile up beside the logs, so they get the same retention
/// as archives: the newest maxArchives are kept, and zero keeps every one.
/// </summary>
private static void PruneRecoveredTails(string directory, string name, int maxArchives)
{
if (maxArchives <= 0)
return;
var tails = new List<FileInfo>();
foreach (var path in Directory.GetFiles(directory, $"{name}.*.log"))
{
if (IsRecoveredTail(path, name))
tails.Add(new FileInfo(path));
}
foreach (var expired in tails.OrderByDescending(tail => tail.LastWriteTimeUtc).Skip(maxArchives))
{
try
{
expired.Delete();
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
}
// "<name>.<stamp>.<pid>.previous-crash.log" and "<name>.<stamp>.<pid>.<timestamp>.abnormal-exit.log"
private static bool IsRecoveredTail(string fileName, string name)
{
return MonitorFileNames.OwnedSuffix(fileName, name) is { Length: >= 3 } suffix
&& MonitorFileNames.IsStamp(suffix[0])
&& int.TryParse(suffix[1], out _)
&& suffix[^1] is "previous-crash" or "abnormal-exit";
}
// Matches "<name>.<stamp>.<pid>" and nothing looser, so a stray user file is never archived
private static bool IsRunFile(string fileName, string name)
{
return MonitorFileNames.OwnedSuffix(fileName, name) is { Length: 2 } suffix
&& MonitorFileNames.IsStamp(suffix[0])
&& int.TryParse(suffix[1], out _);
}
private void WriteLoop(int flushInterval)
{
// Nothing may escape: an unhandled exception here would take the game down
try
{
DrainLoop(flushInterval);
}
catch (Exception) { }
finally
{
// The writer thread owns closing the file, so a Dispose that gave up waiting can't leak it
DisableWriter();
}
}
private void DrainLoop(int flushInterval)
{
var reader = _queue.Reader;
var pendingFlush = false;
var lastFlush = Environment.TickCount64;
// One outstanding wait at a time, kept across timeouts so idle flushes still happen
Task<bool>? waiting = null;
while (true)
{
waiting ??= reader.WaitToReadAsync().AsTask();
// The timeout is only there to flush what is buffered, so an idle writer waits for a line
var waitMs = pendingFlush ? DrainWaitMs : Timeout.Infinite;
if (waiting.Wait(waitMs))
{
var hasLines = waiting.Result;
waiting = null;
if (!hasLines)
break; // Completed and fully drained
// Bounded, so producers that outpace the writer can't starve the drop report and flush below
var batch = 0;
while (batch++ < QueueCapacity && reader.TryRead(out var entry))
WriteLine(entry);
pendingFlush = true;
}
if (ReportDrops())
pendingFlush = true;
// Flush is page-cache only, so a short cadence is cheap
if (pendingFlush && Environment.TickCount64 - lastFlush >= flushInterval)
{
Flush();
pendingFlush = false;
lastFlush = Environment.TickCount64;
}
}
ReportDrops();
Flush();
}
private void WriteLine(in Entry entry)
{
// Counted, so a file that died mid-session shows in the stats instead of losing lines silently
if (_file is null)
{
_linesDiscarded++;
return;
}
var line = FormatLine(entry);
try
{
// One UTF-8 pass per line: encode into a reusable buffer, and the same pass yields the byte stat
var maxBytes = Encoding.UTF8.GetMaxByteCount(line.Length) + NewLineBytes.Length;
if (_lineBuffer.Length < maxBytes)
{
var doubled = (int)Math.Min((long)_lineBuffer.Length * 2, Array.MaxLength);
_lineBuffer = new byte[Math.Max(maxBytes, doubled)];
}
var byteCount = Encoding.UTF8.GetBytes(line.AsSpan(), _lineBuffer);
NewLineBytes.CopyTo(_lineBuffer.AsSpan(byteCount));
byteCount += NewLineBytes.Length;
_file.Write(_lineBuffer, 0, byteCount);
// Only this thread writes these; readers take a whole 64-bit value via Interlocked.Read
_linesWritten++;
_bytesWritten += byteCount;
}
catch (Exception)
{
// A full or disconnected disk gives up the file, not the process
FailWriter();
}
}
private string FormatLine(in Entry entry)
{
// A custom formatter runs here so its strings never cost a game thread
var formatter = LogFormatter;
if (entry.Category is null || formatter is null)
return entry.Message;
try
{
// A formatter returning null would otherwise disable the log file for good
return formatter(entry.Level, entry.Category, entry.Message) ?? entry.Message;
}
catch (Exception)
{
// A broken formatter costs its decoration, not the log
return entry.Message;
}
}
private void Flush()
{
try
{
_file?.Flush();
}
catch (Exception)
{
FailWriter();
}
}
// A failure gives up the file like a normal close does, but leaves a mark the stats can show
private void FailWriter()
{
_writerFailed = true;
DisableWriter();
}
// Give up on the log file and keep draining, so producers never block or throw
private void DisableWriter()
{
var file = Interlocked.Exchange(ref _file, null);
if (file is null)
return;
try
{
file.Dispose();
}
catch (Exception) { }
}
// True when a report was written, since that line needs flushing like any other
private bool ReportDrops()
{
var dropped = Interlocked.Read(ref _totalDropped) - _reportedDropped;
if (dropped <= 0)
return false;
WriteLine(new Entry(LogLevel.None, null, $"[Brutal.Monitor] dropped {dropped} log messages (queue overflow)"));
_reportedDropped += dropped;
return true;
}
public void Dispose()
{
// Idempotent - reached from both Monitor disposal and the ProcessExit hook
if (Interlocked.Exchange(ref _disposed, 1) != 0)
return;
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
_queue.Writer.TryComplete();
// Bounded so a stuck disk can't stall process exit; the writer thread closes the file either way
if (_thread is null)
DisableWriter();
else
_thread.Join(TimeSpan.FromSeconds(2));
}
}
/// <summary>
/// Moves a finished log into an Archives folder as &lt;archive name&gt;.yyMMdd.n.log,
/// keeping at most maxArchives per name (zero keeps all).
/// </summary>
internal static class LogArchiver
{
// FileShare.None maps to an exclusive flock on Unix, so a live holder conflicts on every platform
internal static bool IsUnheld(string path)
{
try
{
using var probe = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
return true;
}
catch (FileNotFoundException)
{
// Deleted between the caller's existence check and this probe: no file, no holder
return true;
}
catch (IOException)
{
return false;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
/// <summary>Returns false when the log could not be archived, so the caller can move on.</summary>
public static bool TryRotate(string logFilePath, string archiveName, int maxArchives)
{
try
{
Rotate(logFilePath, archiveName, maxArchives);
return true;
}
catch (IOException)
{
return false;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
public static void Rotate(string logFilePath, string archiveName, int maxArchives)
{
if (!File.Exists(logFilePath))
return;
// Unix happily renames an open file, so a held log must be refused here, not by the move
if (!IsUnheld(logFilePath))
throw new IOException($"{logFilePath} is held open by a live instance");
var directory = Path.GetDirectoryName(logFilePath)!;
var currentFile = new FileInfo(logFilePath);
var currentFileTimeStamp = currentFile.LastWriteTime.ToString("yyMMdd", CultureInfo.InvariantCulture);
var archiveDirectory = Path.Combine(directory, "Archives");
var extension = Path.GetExtension(logFilePath);
if (!Directory.Exists(archiveDirectory))
Directory.CreateDirectory(archiveDirectory);
// Only this name's own archives, so names sharing a folder keep separate histories
var archives = new List<(string Path, int TimeStamp, int Index)>();
foreach (var path in Directory.GetFiles(archiveDirectory, $"{archiveName}.*{extension}"))
{
if (MonitorFileNames.TryParseArchive(path, archiveName, out var timeStamp, out var index))
archives.Add((path, timeStamp, index));
}
archives.Sort((a, b) => a.TimeStamp != b.TimeStamp ? a.TimeStamp - b.TimeStamp : a.Index - b.Index);
// Suffix an index when today already has an archive
var archiveIndex = 0;
foreach (var archive in archives)
{
if (archive.TimeStamp.ToString("D6") == currentFileTimeStamp)
archiveIndex = Math.Max(archiveIndex, archive.Index + 1);
}
// Another instance sweeping the same folder can claim an index first, so a collision retries the next
for (var attempt = 0; ; attempt++)
{
var archivePath = Path.Combine(
archiveDirectory,
$"{archiveName}.{currentFileTimeStamp}.{archiveIndex}{extension}"
);
try
{
currentFile.MoveTo(archivePath);
break;
}
catch (IOException) when (attempt < 5 && File.Exists(archivePath))
{
archiveIndex++;
}
}
if (maxArchives <= 0)
return;
// Counts the archive just added, so the folder settles at maxArchives
var toDelete = archives.Count + 1 - maxArchives;
for (int i = 0; i < toDelete && i < archives.Count; i++)
{
// A stale archive we cannot delete is not worth failing startup over
try
{
File.Delete(archives[i].Path);
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
}
}

View file

@ -0,0 +1,243 @@
using Brutal.Monitor.Common;
using Microsoft.Extensions.Logging;
namespace Brutal.Monitor.Logging;
/// <summary>
/// Provides the MonitorLogger. Messages are queued for the background writer and mirrored
/// into the crash-tail ring, so a log call only ever touches memory.
/// </summary>
public class MonitorLoggerProvider : ILoggerProvider
{
private readonly BackgroundLogWriter _writer = new();
private CrashTailRing? _tailRing;
private volatile bool _disposed;
// Backed by an int so the hot-path read is a plain load rather than a property call on an enum field
private volatile int _minimumLevel = (int)LogLevel.Trace;
public MonitorLoggerProvider() { }
public MonitorLoggerProvider(LogLevel minimumLevel)
{
MinimumLevel = minimumLevel;
}
/// <summary>
/// Messages below this level are dropped before anything is formatted, so trace spam
/// costs a compare instead of a string, a ring write and a queue slot. Defaults to Trace.
/// </summary>
public LogLevel MinimumLevel
{
get => (LogLevel)_minimumLevel;
set => _minimumLevel = (int)value;
}
/// <summary>True when this level is worth building a message for.</summary>
public bool IsEnabled(LogLevel level)
{
return level != LogLevel.None && (int)level >= _minimumLevel;
}
/// <summary>
/// Optional formatter for log file lines, given the level, category and message. Runs on
/// the background writer thread, so its strings never cost a game thread, and the
/// crash-tail ring always gets the plain message. Set it before logging starts.
/// </summary>
public Func<LogLevel, string, string, string>? LogFormatter
{
get => _writer.LogFormatter;
set => _writer.LogFormatter = value;
}
/// <summary>Crash-tail ring path, once file logging is configured.</summary>
public string? CrashTailPath => _tailRing?.FilePath;
/// <summary>This run's log file path, once file logging is configured.</summary>
public string? LogFilePath => _writer.LogFilePath;
/// <summary>Counters for the logging pipeline, cheap enough to poll every frame.</summary>
public MonitorLoggingStats GetStats()
{
return new MonitorLoggingStats
{
QueueDepth = _writer.QueueDepth,
QueueCapacity = _writer.Capacity,
LinesWritten = _writer.LinesWritten,
BytesWritten = _writer.BytesWritten,
LinesDropped = _writer.LinesDropped,
LinesDiscarded = _writer.LinesDiscarded,
WriterFailed = _writer.WriterFailed,
RingSequence = _tailRing?.Sequence ?? 0,
RingSlotCount = _tailRing?.SlotCount ?? 0,
RingSlotSize = _tailRing?.SlotSize ?? 0,
};
}
/// <summary>
/// Open the log file and start the background writer, flushing anything already queued.
/// Call once, during startup.
/// </summary>
public void Configure(LoggerOptions options, string name)
{
_writer.Open(options, name);
// The ring carries the log file's name, so the subprocess can match the two
var logFilePath = _writer.LogFilePath;
if (logFilePath is null)
return;
try
{
_tailRing = new CrashTailRing(logFilePath + ".ring");
}
catch (Exception)
{
// Any unusable path or mapping loses the crash tail; none of it may fail startup
_tailRing = null;
}
// A host that exits without disposing must still retire the ring, or a clean exit reads as a crash next run
if (_tailRing is not null)
{
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
// A crash unwinds through Dispose even without last-chance dumps, so the ring is preserved here too
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
}
}
private void OnProcessExit(object? sender, EventArgs e)
{
Dispose();
}
// The subscription cannot be exercised in-process without dying, so tests call this directly
internal void OnUnhandledException(object? sender, UnhandledExceptionEventArgs e)
{
PreserveCrashTail();
}
/// <summary>Keep this run's crash tail for the next run; a dying host unwinds through this disposal.</summary>
internal void PreserveCrashTail()
{
_tailRing?.Preserve();
}
public ILogger CreateLogger(string categoryName)
{
return new MonitorLogger(categoryName, this);
}
public void AddMessage(string message)
{
AddMessage(LogLevel.None, null, message);
}
/// <summary>
/// Queue a log message. The ring gets the plain message; formatting happens at the writer.
/// </summary>
public void AddMessage(LogLevel level, string? category, string message)
{
if (_disposed)
return;
// Raw lines (null category) are markers and recovery notes, so they are never filtered
if (category is not null && !IsEnabled(level))
return;
// Threads can still be logging while another disposes, and ILogger.Log must not throw
try
{
_tailRing?.Write(message);
if (category is null)
_writer.Add(message);
else
_writer.Add(level, category, message);
}
catch (ObjectDisposedException) { }
}
public void Dispose()
{
_disposed = true;
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
AppDomain.CurrentDomain.UnhandledException -= OnUnhandledException;
_writer.Dispose();
_tailRing?.Dispose();
}
}
/// <summary>Counters describing the logging pipeline's current state.</summary>
public struct MonitorLoggingStats
{
public int QueueDepth;
public int QueueCapacity;
public long LinesWritten;
public long BytesWritten;
public long LinesDropped;
// Lines drained with no usable log file, and whether the file was lost to a write failure
public long LinesDiscarded;
public bool WriterFailed;
public long RingSequence;
public int RingSlotCount;
public int RingSlotSize;
public MonitorLoggingStats() { }
}
/// <summary>
/// This logger queues messages for the background writer and crash-tail ring
/// </summary>
internal sealed class MonitorLogger : ILogger
{
private readonly string _categoryName;
private readonly MonitorLoggerProvider _provider;
public MonitorLogger(string categoryName, MonitorLoggerProvider provider)
{
_provider = provider;
_categoryName = categoryName;
}
public void Dispose() { }
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter
)
{
// Gated before the formatter runs, so a filtered-out call allocates nothing at all
if (!_provider.IsEnabled(logLevel))
return;
// A throwing ToString in the state or exception costs its line, never the game thread
try
{
var message = formatter(state, exception);
// The default formatter leaves the exception out, and a crash log without the stack is useless
if (exception is not null)
message = $"{message}{Environment.NewLine}{exception}";
_provider.AddMessage(logLevel, _categoryName, message);
}
catch (Exception) { }
}
public bool IsEnabled(LogLevel logLevel)
{
return _provider.IsEnabled(logLevel);
}
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull
{
return null;
}
}

View file

@ -0,0 +1,447 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using Brutal.Logging;
using Brutal.Monitor.Common;
using Brutal.Monitor.Logging;
using Microsoft.Extensions.Logging;
namespace Brutal.Monitor
{
public class Monitor : IDisposable
{
private const int ThrottleExpirationMs = 10000; // Minimum milliseconds between first-chance collections
private const int TimeOutMs = 1000; // Timeout for subprocess command acknowledgements
private const int DefaultDumpTimeOutMs = 60000; // Matches CollectorOptions.DumpTimeoutMs
// Bounded, so a best-effort dump still writing cannot make shutdown look hung
private const int ShutdownGraceMs = 2000;
private Process? _monitorProcess;
private ProcessResponseReader? _responses;
private long _nextFirstChance; // Earliest TickCount64 the next first-chance collection may start
private volatile bool _firstChancePending;
private volatile bool _subprocessExited;
// Set before the subprocess is told to stop, so a crash handler already past its guard turns back
private volatile bool _stopping;
// Captured the moment the subprocess exits, so reading it later cannot race or throw
private volatile int _subprocessExitCode = -1;
private readonly LogCategory _monitorLog;
private readonly string _name;
/// <summary>The ILoggerProvider this Monitor logs through, owned and disposed by it.</summary>
public MonitorLoggerProvider LogProvider { get; }
private CollectorOptions? _collectorOptions = null;
// Tracked via the Exited event so the first-chance path checks a field, not the process
public bool SubprocessRunning => _monitorProcess != null && !_subprocessExited;
/// <summary>Exit code of the subprocess once it has exited, or -1 while it is still running.</summary>
public int SubprocessExitCode => _subprocessExitCode;
/// <summary>
/// The name (like "Gruntz.client") plus this run's start time and pid names every
/// file this run produces, so instances sharing a folder never collide. It must be
/// usable as a plain file name. Messages below minimumLevel are dropped before
/// anything is formatted, which is where trace spam gets expensive.
/// </summary>
public Monitor(string name, LogLevel minimumLevel = LogLevel.Trace)
{
ArgumentException.ThrowIfNullOrEmpty(name);
// The name seeds file names and retention globs, so wildcards or separators could sweep others' files
if (name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || name.IndexOfAny(['*', '?', '/', '\\']) >= 0)
throw new ArgumentException(
$"Monitor name '{name}' must be usable as a plain file name, without wildcards or separators.",
nameof(name)
);
_name = name;
_monitorLog = LogCategory.Make("Monitor");
LogProvider = new MonitorLoggerProvider(minimumLevel);
Start();
}
public void Dispose()
{
Stop();
LogProvider.Dispose();
}
public void AddLogger(LoggerOptions loggerOptions)
{
// In-process logging, so this works with or without the subprocess
LogProvider.Configure(loggerOptions, _name);
// An unusable path disables file logging rather than failing, so it is reported here
if (LogProvider.LogFilePath is null)
_monitorLog.Warning(
$"Monitor could not open a log file in '{loggerOptions.LogDirectory}'. "
+ "File logging is disabled for this session."
);
// Read once: Stop can null the field between this and the write
var process = _monitorProcess;
if (process != null && !_subprocessExited && LogProvider.CrashTailPath is not null)
{
process.WriteLineSync($"LogTail\t{LogProvider.CrashTailPath}");
_monitorLog.Info($"Monitor subprocess log tail: {WaitFor("LogTail", TimeOutMs) ?? "no response"}.");
}
}
public void AddCollector(CollectorOptions collectorOptions)
{
// The game creates the directory; resolved to a full path so the subprocess's own cwd never matters
collectorOptions.DumpPath = Path.GetFullPath(collectorOptions.DumpPath);
if (!Directory.Exists(collectorOptions.DumpPath))
throw new DirectoryNotFoundException($"Dump directory '{collectorOptions.DumpPath}' does not exist.");
_collectorOptions = collectorOptions;
// Detach first, so configuring twice replaces the handlers instead of doubling them
DetachCollectorHandlers();
if (_collectorOptions.Value.FirstChance != DumpType.None)
AppDomain.CurrentDomain.FirstChanceException += OnFirstChance;
if (_collectorOptions.Value.LastChance != DumpType.None)
AppDomain.CurrentDomain.UnhandledException += OnLastChance;
// Read once: Stop can null the field between this and the write
var process = _monitorProcess;
if (process == null || _subprocessExited)
return;
// Tab-separated because dump paths contain spaces
process.WriteLineSync(
$"AddCollector\t{collectorOptions.DumpPath}\t{(int)collectorOptions.FirstChance}"
+ $"\t{(int)collectorOptions.LastChance}\t{collectorOptions.KeepCount}"
+ $"\t{collectorOptions.DumpTimeoutMs}"
);
_monitorLog.Info($"Monitor subprocess collector: {WaitFor("AddCollector", TimeOutMs) ?? "no response"}.");
}
private void Start()
{
var rid = "win-x64";
if (OperatingSystem.IsLinux())
rid = "linux-x64";
else if (OperatingSystem.IsMacOS())
rid = "osx-arm64";
var thisDirectory = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory);
var subprocessName = "Brutal.Monitor.Subprocess";
var extension = OperatingSystem.IsWindows() ? ".exe" : "";
var monitorExe = FindSubprocessExecutable(thisDirectory, rid, subprocessName + extension);
if (monitorExe is null)
{
_monitorLog.Error(
$"Brutal.Monitor subprocess was not found beside the application or in "
+ $"runtimes/{rid}/native. Crash dump collection is disabled."
);
return;
}
_monitorLog.Info($"Running Monitor subprocess from {thisDirectory}.");
var startInfo = new ProcessStartInfo()
{
CreateNoWindow = true,
FileName = monitorExe,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = thisDirectory,
};
// The subprocess names its dumps and tails from these, matching this run's log
startInfo.ArgumentList.Add($"{Environment.ProcessId}");
startInfo.ArgumentList.Add(_name);
startInfo.ArgumentList.Add(MonitorFileNames.ProcessStamp);
try
{
_monitorProcess = Process.Start(startInfo);
}
catch (Win32Exception)
{
_monitorProcess = null;
}
if (_monitorProcess == null)
{
_monitorLog.Warning(
$"Monitor subprocess ({monitorExe}) could not be started. "
+ "Falling back to logging and crash handling from the main process."
);
return;
}
// Subscribed before events are enabled, or an already-dead subprocess fires Exited into no handler
_subprocessExited = false;
_monitorProcess.Exited += OnMonitorExit;
_monitorProcess.EnableRaisingEvents = true;
// Owns the only reader of the subprocess's stdout
_responses = new ProcessResponseReader(_monitorProcess);
_monitorLog.Info("Monitor subprocess started successfully");
// Redirect the error stream to Log as Errors instead
_monitorProcess
.StandardError.ReadToEndAsync()
.ContinueWith(task =>
{
// Touching Exception observes a torn-down stream instead of raising UnobservedTaskException
if (task.Exception is not null || !task.IsCompletedSuccessfully)
return;
var errorOutput = task.Result;
if (!string.IsNullOrEmpty(errorOutput))
{
_monitorLog.Warning($"Monitor subprocess error output: {errorOutput}");
}
});
}
public void Stop()
{
// Closes the collect paths first, so a handler that entered before this cannot
// write a command to a subprocess that is already on its way out
_stopping = true;
// Even when no subprocess started, or the handlers would root this Monitor for the process lifetime
DetachCollectorHandlers();
var process = _monitorProcess;
if (process != null)
{
process.Exited -= OnMonitorExit;
// This runs from Dispose, so shutting the subprocess down must always finish
try
{
if (!_subprocessExited)
{
process.WriteLineSync("Stop");
_monitorLog.Info($"Monitor subprocess stop: {WaitFor("Stop", TimeOutMs) ?? "no response"}.");
}
// A first-chance dump still writing is best effort, so shutdown abandons it
// rather than waiting out its whole budget and looking hung
if (process.WaitForExit(ShutdownGraceMs))
RecordExit(process);
else
Terminate(process);
}
catch (Exception) { }
finally
{
_responses?.Dispose();
_responses = null;
process.Dispose();
_monitorProcess = null;
}
}
}
private void RecordExit(Process process)
{
// Safe to read here: the wait returning means it has exited
_subprocessExitCode = process.ExitCode;
if (_subprocessExitCode != 0)
_monitorLog.Error($"Monitor process {process.Id} exited with error {_subprocessExitCode}");
else
_monitorLog.Info($"Monitor process {process.Id} exited successfully.");
}
// The subprocess can exit before the kill lands, so Kill throwing is normal and the wait is bounded
private void Terminate(Process process)
{
_monitorLog.Info($"Monitor process {process.Id} exit timeout. Force termination.");
try
{
process.Kill(true);
}
catch (Exception) { }
// Kill is asynchronous, and touching ExitCode before it lands throws
try
{
if (process.WaitForExit(TimeOutMs))
RecordExit(process);
else
_monitorLog.Warning($"Monitor process {process.Id} did not exit after being terminated.");
}
catch (Exception) { }
}
// Removing a handler that was never added is a no-op, so this is safe to call any time
private void DetachCollectorHandlers()
{
AppDomain.CurrentDomain.FirstChanceException -= OnFirstChance;
AppDomain.CurrentDomain.UnhandledException -= OnLastChance;
}
private void OnMonitorExit(object? sender, EventArgs e)
{
_subprocessExited = true;
// Nothing may escape a runtime callback; a dead subprocess costs crash dumps, not the application
try
{
// The sender is the process that just exited, so this never races Stop for the field
if (sender is Process exited)
_subprocessExitCode = exited.ExitCode;
_monitorLog.Warning(
$"Monitor subprocess exited early with exit code {_subprocessExitCode}. "
+ "Crash dump collection is disabled for the rest of this session."
);
}
catch (Exception) { }
}
private void OnFirstChance(object? sender, FirstChanceExceptionEventArgs e)
{
// Runs on every exception in the process, so the throttled path is a read and a compare
var now = Environment.TickCount64;
var next = Volatile.Read(ref _nextFirstChance);
if (now < next)
return;
// One winner per window; a loser was beaten by a concurrent exception this same instant
if (Interlocked.CompareExchange(ref _nextFirstChance, now + ThrottleExpirationMs, next) != next)
return;
if (_collectorOptions == null || _collectorOptions.Value.FirstChance == DumpType.None)
return;
if (!SubprocessRunning)
return;
try
{
CollectFirstChanceDump(e.Exception);
}
catch (Exception) { }
}
private void OnLastChance(object? sender, UnhandledExceptionEventArgs e)
{
// A main-thread crash runs this Monitor's Dispose on the way out, which would retire the ring
LogProvider.PreserveCrashTail();
if (_collectorOptions == null || _collectorOptions.Value.LastChance == DumpType.None)
return;
// Guarded so a throwing ToString on the dying exception cannot suppress the dump
try
{
_monitorLog.Error($"Unhandled exception {e.ExceptionObject}.");
}
catch (Exception) { }
if (!SubprocessRunning)
return;
// Unthrottled: sharing the first-chance permit let a benign throw skip the real dump
try
{
CollectLastChanceDump();
}
catch (Exception) { }
}
/// <summary>Commands are serial, so the budget covers a first-chance dump ahead of us, if enabled.</summary>
internal static int LastChanceWait(CollectorOptions? collectorOptions)
{
var dumpTimeOut = collectorOptions?.DumpTimeoutMs ?? DefaultDumpTimeOutMs;
var firstChanceCanQueue = collectorOptions is { } options && options.FirstChance != DumpType.None;
return firstChanceCanQueue ? dumpTimeOut * 2 + TimeOutMs : dumpTimeOut + TimeOutMs;
}
private int LastChanceWaitMs => LastChanceWait(_collectorOptions);
private string? WaitFor(string command, int timeOut) => _responses?.WaitFor(command, timeOut);
private void CollectFirstChanceDump(Exception exception)
{
// Read once: Stop can null the field between this and the write
var process = _monitorProcess;
if (_stopping || process == null || _subprocessExited)
return;
// One dump in flight at a time, or a burst of throws pushes the fatal dump past its wait budget
if (_firstChancePending)
{
if (WaitFor("FirstChance", 0) is null)
return;
_firstChancePending = false;
}
// Never wait: the throwing thread is not dying, so blocking it is a frame hitch for nothing
process.WriteLineSync("FirstChance");
_firstChancePending = true;
// Formatted only for the exception being dumped, and a throwing ToString costs the line, not the dump
try
{
_monitorLog.Error($"First chance dump requested for {exception}.");
}
catch (Exception) { }
}
private void CollectLastChanceDump()
{
// Read once: Stop can null the field between the check and the write
var process = _monitorProcess;
// A subprocess already told to stop will never answer, and waiting on it would stall the dying process
if (_stopping || process == null || _subprocessExited)
{
_monitorLog.Warning("Last chance dump: the monitor subprocess is shutting down or gone.");
return;
}
// This wait is what keeps the dying process alive long enough to be dumped
process.WriteLineSync("LastChance");
LogCollectResponse("Last chance dump", WaitFor("LastChance", LastChanceWaitMs));
}
private void LogCollectResponse(string kind, string? response)
{
if (string.IsNullOrEmpty(response))
{
_monitorLog.Warning($"{kind}: no response from the monitor subprocess.");
return;
}
if (response.StartsWith("Failed", StringComparison.Ordinal) || response == "timed out")
_monitorLog.Warning($"{kind}: {response}.");
else
_monitorLog.Info($"{kind}: {response}.");
}
/// <summary>
/// Locate the subprocess executable: beside the app for local builds, or under
/// runtimes/&lt;rid&gt;/native as the package delivers it. Returns null if neither exists.
/// </summary>
private static string? FindSubprocessExecutable(string baseDirectory, string rid, string fileName)
{
var beside = Path.Combine(baseDirectory, fileName);
if (File.Exists(beside))
return beside;
var packaged = Path.Combine(baseDirectory, "runtimes", rid, "native", fileName);
return File.Exists(packaged) ? packaged : null;
}
}
}

View file

@ -0,0 +1,29 @@
<Project>
<!-- NuGet extraction does not preserve executable permissions for the NativeAOT watchdog. -->
<Target
Name="MakeMonitorBuildExecutable"
AfterTargets="CopyFilesToOutputDirectory"
Condition="!$([MSBuild]::IsOSPlatform('Windows')) and '$(TargetDir)' != ''"
>
<ItemGroup>
<_MonitorBuildExecutable Include="$(TargetDir)Brutal.Monitor.Subprocess;$(TargetDir)runtimes/*/native/Brutal.Monitor.Subprocess" />
</ItemGroup>
<Exec
Command="chmod +x &quot;%(_MonitorBuildExecutable.Identity)&quot;"
Condition="Exists('%(_MonitorBuildExecutable.Identity)')"
/>
</Target>
<Target
Name="MakeMonitorPublishExecutable"
AfterTargets="Publish"
Condition="!$([MSBuild]::IsOSPlatform('Windows')) and '$(PublishDir)' != ''"
>
<ItemGroup>
<_MonitorPublishExecutable Include="$(PublishDir)Brutal.Monitor.Subprocess;$(PublishDir)runtimes/*/native/Brutal.Monitor.Subprocess" />
</ItemGroup>
<Exec
Command="chmod +x &quot;%(_MonitorPublishExecutable.Identity)&quot;"
Condition="Exists('%(_MonitorPublishExecutable.Identity)')"
/>
</Target>
</Project>