Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of DiagLayer v0.1.0
BepInEx/plugins/DiagLayer/DiagLayer.dll
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("DiagLayer")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("DiagLayer")] [assembly: AssemblyTitle("DiagLayer")] [assembly: InternalsVisibleTo("DiagLayer.Tests")] [assembly: AssemblyVersion("0.1.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] internal sealed class SetsRequiredMembersAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] internal sealed class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] internal sealed class CompilerFeatureRequiredAttribute : Attribute { public string FeatureName { get; } public bool IsOptional { get; init; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } } namespace DiagLayer { internal enum Severity { Info, Warning, Problem } internal static class ChestDiagnostics { internal sealed class Finding { internal DateTime Utc; internal Severity Severity; internal string Kind = ""; internal string Line = ""; internal string Extra = ""; internal string[] Context = Array.Empty<string>(); } internal sealed class Marker { internal DateTime Utc; internal string Who = ""; internal string Note = ""; internal string[] Context = Array.Empty<string>(); internal string[] Activity = Array.Empty<string>(); } private enum Column { Utc, Session, Role, Severity, Event, Operation, Chest, Peer, Owner, DataRevision, LoadedRevision, LocalUse, ReplicatedUse, Stacks, FreeSlots, Items, Payload, Details } private readonly struct ChestState { internal readonly Container? Chest; internal readonly ZDO? Zdo; internal readonly ZDOID? Id; internal readonly Inventory? Inventory; internal readonly long Peer; internal readonly long Owner; internal ChestState(Container? chest) { Chest = chest; Zdo = ContainerTracker.LiveZdo(chest); Id = ContainerTracker.IdOf(chest); Inventory = ((chest == null) ? null : chest.GetInventory()); Peer = ((ZDOMan.instance == null) ? 0 : ZDOMan.GetSessionID()); ZDO? zdo = Zdo; Owner = ((zdo != null) ? zdo.GetOwner() : 0); } } internal sealed class SessionSnapshot { internal required Finding[] Findings { get; init; } internal required int Dropped { get; init; } internal required Marker[] Markers { get; init; } internal required string[] Recent { get; init; } internal required string[] Activity { get; init; } internal required KeyValuePair<string, int>[] Counts { get; init; } internal required string[] Failures { get; init; } } private static readonly string Header = TsvColumns.Header<Column>(); private static readonly int ColumnCount = TsvColumns.Count<Column>(); private const string EventPrefix = "DiagLayer-events-"; private static readonly HashSet<string> ActivityKinds = new HashSet<string>(StringComparer.Ordinal) { "operation-end", "operation-settled", "player-items", "craft-result", "craft-handoff-cancelled", "craft-output-without-consumption", "craft-consumed-without-output" }; private const int ActivityLimit = 200; private const int ActivityMinutes = 20; private const int MarkerActivity = 40; private const int RecentLimit = 600; private const int ChestHistory = 12; private const int FindingLimit = 80; private const int KeptEarlyFindings = 10; private const int MarkerLimit = 30; private const int SessionsRetained = 20; private const int PartsPerSession = 16; internal static readonly string Session = Guid.NewGuid().ToString("N").Substring(0, 12); internal static readonly DateTime Started = DateTime.UtcNow; private static readonly object gate = new object(); private static readonly Queue<(DateTime Utc, string Line)> recent = new Queue<(DateTime, string)>(); private static readonly Queue<(DateTime Utc, string Line)> activity = new Queue<(DateTime, string)>(); private static readonly Dictionary<ZDOID, Queue<string>> histories = new Dictionary<ZDOID, Queue<string>>(); private static readonly List<Finding> findings = new List<Finding>(); private static readonly List<Marker> markers = new List<Marker>(); private static readonly Dictionary<string, int> counts = new Dictionary<string, int>(StringComparer.Ordinal); private static readonly HashSet<string> reportedFailures = new HashSet<string>(StringComparer.Ordinal); private static string? directory; private static string? writeError; private static string role = "client"; private static StreamWriter? writer; private static long bytes; private static long limit; private static int part; private static int droppedFindings; private static int problems; private static int warnings; private static bool enabled; private static bool writeFailed; [ThreadStatic] private static bool recording; internal static string Operation = ""; internal static bool Enabled => enabled; internal static bool Recording => recording; internal static string? Directory => directory; internal static string Role => role; internal static int Problems { get { lock (gate) { return problems; } } } internal static int Warnings { get { lock (gate) { return warnings; } } } internal static int Version { get; private set; } private static string EventStem => "DiagLayer-events-" + role + "-"; internal static void Configure(string path, bool server, long maxBytes) { Disable(); role = (server ? "server" : "client"); try { if (!Path.IsPathRooted(path)) { throw new ArgumentException("Use an absolute diagnostics directory.", "path"); } directory = Path.GetFullPath(path); } catch (Exception ex) when (((ex is ArgumentException || ex is NotSupportedException || ex is SecurityException) ? 1 : 0) != 0) { DiagLog.Error("DiagLayer disabled because the configured directory is invalid: " + ex); return; } limit = maxBytes; part = 0; writeFailed = false; enabled = true; Record("session-start", null, "version=" + typeof(Plugin).Assembly.GetName().Version?.ToString() + ";role=" + role); DiagLog.Info("DiagLayer: logs and reports in " + directory + ". Type /dl_report in chat to collect a report."); } internal static void Record(string kind, Container? chest, string details = "", Severity severity = Severity.Info, string extra = "") { RecordChest(kind, chest, details, severity, extra, null); } internal static void RecordContents(string kind, Container chest, string items) { RecordChest(kind, chest, "", Severity.Info, "", items); } private static void RecordChest(string kind, Container? chest, string details, Severity severity, string extra, string? summarized) { if (!enabled || recording) { return; } string text = null; string text2 = null; recording = true; try { ChestState chestState = new ChestState(chest); string items = summarized ?? ((chestState.Inventory == null) ? "" : Items(chestState.Inventory)); DateTime utcNow = DateTime.UtcNow; string[] fields = Row(utcNow, kind, severity, Operation, details, extra, chestState, items); string line = Line(kind, severity, details, chestState, items, utcNow); lock (gate) { Store(kind, severity, chestState.Id, line, extra, fields); text2 = writeError; writeError = null; } } catch (Exception ex) { text = kind + ": " + ex; } finally { recording = false; } if (text2 != null) { DiagLog.Error(text2); } if (text != null) { ReportFailure(kind, text); } } private static string LoadedOf(Container? chest) { if (chest == null) { return ""; } uint num = ContainerTracker.LoadedRevision(chest); if (num == uint.MaxValue) { return "none"; } return num.ToString(CultureInfo.InvariantCulture); } private static string InUse(Container? chest) { if (chest == null) { return ""; } if (!chest.IsInUse()) { return "0"; } return "1"; } private static string OwnerOf(long owner, long peer) { if (owner == 0L) { return "none"; } if (owner != peer) { return owner.ToString(CultureInfo.InvariantCulture); } return "self"; } private static string[] Row(DateTime now, string kind, Severity severity, string operation, string details, string extra, ChestState? state, string items) { string[] array = new string[ColumnCount]; for (int i = 0; i < array.Length; i++) { array[i] = ""; } array[0] = now.ToString("O", CultureInfo.InvariantCulture); array[1] = Session; array[2] = role; array[3] = severity.ToString(); array[4] = kind; array[5] = operation; array[17] = details + ((extra.Length == 0) ? "" : (" | " + extra)); if (state.HasValue) { ChestState valueOrDefault = state.GetValueOrDefault(); FillChestColumns(array, valueOrDefault, items); } return array; } private static void FillChestColumns(string[] row, ChestState state, string items) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) ref readonly ZDOID? id = ref state.Id; row[6] = (id.HasValue ? ((object)id.GetValueOrDefault()/*cast due to .constrained prefix*/).ToString() : null) ?? ""; long peer = state.Peer; row[7] = peer.ToString(CultureInfo.InvariantCulture); object obj; if (state.Zdo != null) { peer = state.Owner; obj = peer.ToString(CultureInfo.InvariantCulture); } else { obj = ""; } row[8] = (string)obj; ZDO? zdo = state.Zdo; row[9] = ((zdo != null) ? zdo.DataRevision.ToString(CultureInfo.InvariantCulture) : null) ?? ""; row[10] = LoadedOf(state.Chest); row[11] = InUse(state.Chest); row[12] = ((state.Zdo == null) ? "" : state.Zdo.GetInt(ZDOVars.s_inUse, 0).ToString(CultureInfo.InvariantCulture)); Inventory? inventory = state.Inventory; row[13] = ((inventory != null) ? inventory.NrOfItems().ToString(CultureInfo.InvariantCulture) : null) ?? ""; row[14] = FreeSlots(state.Inventory); row[15] = items; row[16] = ((state.Zdo == null) ? "" : Short(ContainerTracker.PayloadHash(state.Zdo))); } private static string FreeSlots(Inventory? inventory) { if (inventory != null) { return Math.Max(0, inventory.GetWidth() * inventory.GetHeight() - inventory.NrOfItems()).ToString(CultureInfo.InvariantCulture); } return ""; } private static string Line(string kind, Severity severity, string details, ChestState state, string items, DateTime now) { //IL_0091: Unknown result type (might be due to invalid IL or missing references) StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)).Append(' '); if (severity != Severity.Info) { stringBuilder.Append((severity == Severity.Problem) ? "PROBLEM " : "WARNING "); } stringBuilder.Append(kind); if (Operation.Length > 0) { stringBuilder.Append(" [").Append(Operation).Append(']'); } if (state.Id.HasValue) { stringBuilder.Append(" chest=").Append(state.Id.Value); } AppendZdo(stringBuilder, state); if (state.Inventory != null) { stringBuilder.Append(" items=").Append(Clip((items.Length == 0) ? "empty" : items, 200)); } if (details.Length > 0) { stringBuilder.Append(" | ").Append(Clip(details, 400)); } return stringBuilder.ToString(); } private static void AppendZdo(StringBuilder line, ChestState state) { if (state.Zdo == null) { if (state.Id.HasValue) { line.Append(" (unloaded)"); } } else { line.Append(" owner=").Append(OwnerOf(state.Owner, state.Peer)).Append(" rev=") .Append(state.Zdo.DataRevision) .Append('/') .Append(LoadedOf(state.Chest)) .Append(" use=") .Append(InUse(state.Chest)) .Append('/') .Append(state.Zdo.GetInt(ZDOVars.s_inUse, 0).ToString(CultureInfo.InvariantCulture)) .Append(" payload=") .Append(Short(ContainerTracker.PayloadHash(state.Zdo))); } } internal static void RecordText(string kind, string details) { if (!enabled || recording) { return; } string text = null; string text2 = null; recording = true; try { DateTime utcNow = DateTime.UtcNow; string[] fields = Row(utcNow, kind, Severity.Info, "", details, "", null, ""); string line = utcNow.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture) + " " + kind + " | " + Clip(details, 400); lock (gate) { Store(kind, Severity.Info, null, line, "", fields); text2 = writeError; writeError = null; } } catch (Exception ex) { text = kind + ": " + ex; } finally { recording = false; } if (text2 != null) { DiagLog.Error(text2); } if (text != null) { ReportFailure(kind, text); } } internal static void Mark(string who, string note) { if (!enabled) { return; } Record("player-marker", null, "player=" + who + ";note=" + note); lock (gate) { DateTime now = DateTime.UtcNow; markers.Add(new Marker { Utc = now, Who = who, Note = note, Context = (from entry in recent where (now - entry.Utc).TotalSeconds <= 90.0 select entry.Line).Reverse().Take(30).Reverse() .ToArray(), Activity = (from entry in activity where (now - entry.Utc).TotalMinutes <= 20.0 select entry.Line).Reverse().Take(40).Reverse() .ToArray() }); if (markers.Count > 30) { markers.RemoveAt(0); } Version++; } } private static void Store(string kind, Severity severity, ZDOID? id, string line, string extra, string[] fields) { counts[kind] = ((!counts.TryGetValue(kind, out var value)) ? 1 : (value + 1)); string[] context = RecordHistory(id, severity, line); RecordRecent(kind, line); RecordFinding(kind, severity, line, extra, context); Version++; Write(fields); } private static string[] RecordHistory(ZDOID? id, Severity severity, string line) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (id.HasValue) { if (!histories.TryGetValue(id.Value, out Queue<string> value)) { if (histories.Count > 2048) { histories.Clear(); } value = (histories[id.Value] = new Queue<string>()); } string[] result = ((severity != Severity.Info) ? value.ToArray() : Array.Empty<string>()); value.Enqueue(line); if (value.Count > 12) { value.Dequeue(); } return result; } if (severity == Severity.Info) { return Array.Empty<string>(); } return (from entry in recent.Skip(Math.Max(0, recent.Count - 8)) select entry.Line).ToArray(); } private static void RecordRecent(string kind, string line) { recent.Enqueue((DateTime.UtcNow, line)); if (recent.Count > 600) { recent.Dequeue(); } if (ActivityKinds.Contains(kind)) { activity.Enqueue((DateTime.UtcNow, line)); if (activity.Count > 200) { activity.Dequeue(); } } } private static void RecordFinding(string kind, Severity severity, string line, string extra, string[] context) { switch (severity) { case Severity.Info: return; case Severity.Problem: problems++; break; default: warnings++; break; } findings.Add(new Finding { Utc = DateTime.UtcNow, Severity = severity, Kind = kind, Line = line, Extra = extra, Context = context }); if (findings.Count > 80) { findings.RemoveAt(10); droppedFindings++; } } private static void Write(string[] fields) { if (writeFailed || directory == null) { return; } try { string text = string.Join("\t", fields.Select(Escape)) + "\n"; int byteCount = Encoding.UTF8.GetByteCount(text); if (writer == null || bytes + byteCount > limit) { Rotate(); } if (writer != null) { writer.Write(text); writer.Flush(); bytes += byteCount; } } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { writeFailed = true; Close(); reportedFailures.Add("event log: " + ex.Message); writeError = "DiagLayer stopped writing the event log; reports still work from memory. " + ex; } } private static void ReportFailure(string kind, string failure) { if (FirstFailure(kind)) { LogFailure(kind, failure); } } private static bool FirstFailure(string kind) { lock (gate) { return reportedFailures.Add(kind); } } private static void LogFailure(string kind, string failure) { DiagLog.Error("DiagLayer could not record '" + kind + "'; gameplay continues. " + failure); } internal static void Fault(string hook, Exception error) { if (FirstFailure(hook)) { string text = hook + ": " + error; LogFailure(hook, text); RecordText("diagnostics-hook-error", text); } } internal static SessionSnapshot Snapshot(int recentLines) { lock (gate) { return new SessionSnapshot { Findings = findings.ToArray(), Dropped = droppedFindings, Markers = markers.ToArray(), Recent = Tail(recent, recentLines), Activity = Tail(activity, recentLines), Counts = counts.OrderByDescending<KeyValuePair<string, int>, int>((KeyValuePair<string, int> entry) => entry.Value).ThenBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> entry) => entry.Key, StringComparer.Ordinal).ToArray(), Failures = reportedFailures.ToArray() }; } } internal static string[] RecentLines(int count) { lock (gate) { return Tail(recent, count); } } private static string[] Tail(Queue<(DateTime Utc, string Line)> lines, int count) { return (from entry in lines.Skip(Math.Max(0, lines.Count - count)) select entry.Line).ToArray(); } internal static string Items(Inventory inventory) { return string.Join(";", from @group in (from item in inventory.GetAllItems() where item?.m_shared != null group item by new { item.m_shared.m_name, item.m_quality, item.m_worldLevel }).OrderBy(@group => @group.Key.m_name, StringComparer.Ordinal).ThenBy(@group => @group.Key.m_quality).ThenBy(@group => @group.Key.m_worldLevel) select @group.Key.m_name + ":q" + @group.Key.m_quality + ":w" + @group.Key.m_worldLevel + "=" + @group.Sum((ItemData item) => item.m_stack)); } internal static Dictionary<string, int> Counts(IEnumerable<Inventory> inventories) { Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal); foreach (Inventory inventory in inventories) { foreach (ItemData allItem in inventory.GetAllItems()) { if (allItem?.m_shared != null) { string key = allItem.m_shared.m_name + ":q" + allItem.m_quality + ":w" + allItem.m_worldLevel; dictionary[key] = (dictionary.TryGetValue(key, out var value) ? value : 0) + allItem.m_stack; } } } return dictionary; } internal static Dictionary<string, int> Delta(Dictionary<string, int> before, Dictionary<string, int> after) { Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal); foreach (string item in before.Keys.Union(after.Keys)) { int value; int value2; int num = (after.TryGetValue(item, out value) ? value : 0) - (before.TryGetValue(item, out value2) ? value2 : 0); if (num != 0) { dictionary[item] = num; } } return dictionary; } internal static string Format(Dictionary<string, int> delta) { if (delta.Count != 0) { return string.Join(";", from entry in delta.OrderBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> entry) => entry.Key, StringComparer.Ordinal) select entry.Key + "=" + ((entry.Value > 0) ? "+" : "") + entry.Value); } return "none"; } internal static string Short(string hash) { if (hash.Length <= 12) { return hash; } return hash.Substring(0, 12); } internal static string Stack(int skip, int frames) { StackTrace stackTrace = new StackTrace(skip + 1, fNeedFileInfo: false); return string.Join(" < ", (from method in stackTrace.GetFrames()?.Select((StackFrame frame) => frame.GetMethod()).OfType<MethodBase>() select (method.DeclaringType?.FullName ?? "?") + "." + method.Name into name where !name.StartsWith("DiagLayer.ChestDiagnostics", StringComparison.Ordinal) && !name.StartsWith("DiagLayer.CompatBridge", StringComparison.Ordinal) select name).Take(frames) ?? Array.Empty<string>()); } private static string Clip(string value, int length) { if (value.Length > length) { return value.Substring(0, length) + "..."; } return value; } private static string Escape(string value) { return value.Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\r", "\\r") .Replace("\n", "\\n"); } private static void Rotate() { string text = directory; if (text == null) { return; } Close(); System.IO.Directory.CreateDirectory(text); writer = new StreamWriter(new FileStream(Path.Combine(text, EventFile(++part)), FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); string[] obj = new string[13] { "# DiagLayer ", typeof(Plugin).Assembly.GetName().Version?.ToString(), " ", role, " session ", Session, " started ", null, null, null, null, null, null }; DateTime started = Started; obj[7] = started.ToString("O", CultureInfo.InvariantCulture); obj[8] = " part "; obj[9] = part.ToString(); obj[10] = "\n"; obj[11] = Header; obj[12] = "\n"; string text2 = string.Concat(obj); writer.Write(text2); bytes = Encoding.UTF8.GetByteCount(text2); FileInfo[] files = new DirectoryInfo(text).GetFiles(EventStem + "*.tsv"); foreach (IGrouping<string, FileInfo> item in (from file in files group file by SessionOf(file.Name) into @group orderby @group.Max((FileInfo file) => file.LastWriteTimeUtc) descending where @group.Key != Session select @group).Skip(19)) { foreach (FileInfo item2 in item) { item2.Delete(); } } foreach (FileInfo item3 in from file in files.Where((FileInfo file) => SessionOf(file.Name) == Session).OrderByDescending<FileInfo, string>((FileInfo file) => file.Name, StringComparer.Ordinal).Skip(16) where !file.Name.EndsWith(PartSuffix(1), StringComparison.Ordinal) select file) { item3.Delete(); } } private static string PartSuffix(int number) { return "-" + number.ToString("D3", CultureInfo.InvariantCulture) + ".tsv"; } private static string EventFile(int number) { string[] obj = new string[5] { EventStem, null, null, null, null }; DateTime started = Started; obj[1] = started.ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture); obj[2] = "-"; obj[3] = Session; obj[4] = PartSuffix(number); return string.Concat(obj); } private static string SessionOf(string file) { string[] array = Path.GetFileNameWithoutExtension(file).Split(new char[1] { '-' }); if (array.Length < 2) { return file; } return array[^2]; } internal static void Close() { StreamWriter streamWriter = writer; writer = null; try { streamWriter?.Dispose(); } catch (IOException ex) { DiagLog.Error("DiagLayer could not finish closing the event log: " + ex); } } internal static void Disable() { lock (gate) { Close(); enabled = false; directory = null; } } internal static void Clear() { lock (gate) { recent.Clear(); activity.Clear(); histories.Clear(); findings.Clear(); markers.Clear(); counts.Clear(); reportedFailures.Clear(); droppedFindings = (problems = (warnings = 0)); Version++; } ItemLedger.Reset(); } } internal static class CompatBridge { private static readonly Action<string, Container?, string, int, string> onEventHandler = HandleEvent; private static readonly Func<string, Action?> onOperationScopeHandler = HandleOperationScope; private static readonly Func<Player, string, IReadOnlyList<Inventory>, bool, Action<Exception?>?> onCraftHandler = HandleCraft; private static readonly Func<string, Player, float, (Action<IReadOnlyList<Container>, IReadOnlyList<(Container Chest, float Distance)>> TrackChests, Action<Exception?> End)?> onOperationHandler = HandleOperation; private static Type? attachedType; private static IDisposable? registration; private static MethodInfo? patchOutcomesMethod; private static PropertyInfo? chestSettingsSummaryProperty; private static PropertyInfo? isIdleSettledProperty; private static PropertyInfo? idleSyncStatsProperty; internal static bool Attached => registration != null; internal static void Attach() { if (registration != null) { return; } string[] array = new string[2] { "CrossModCompat", "DeepNorthCompat" }; foreach (string text in array) { if (Chainloader.PluginInfos.TryGetValue(text, out var value) && !((Object)(object)value.Instance == (Object)null)) { Type type = ((object)value.Instance).GetType().Assembly.GetType(text + ".CompatEvents", throwOnError: false); if (type == null) { DiagLog.Info("DiagLayer: " + text + " has no CompatEvents; skipping " + text + " events."); } else { Attach(type); } break; } } } internal static void Attach(Type eventsType) { if (attachedType == eventsType && registration != null) { return; } Detach(); string fullName = eventsType.FullName; string name = eventsType.Assembly.GetName().Name; try { MethodInfo method = eventsType.GetMethod("Register", BindingFlags.Static | BindingFlags.Public, null, new Type[4] { onEventHandler.GetType(), onOperationScopeHandler.GetType(), onCraftHandler.GetType(), onOperationHandler.GetType() }, null); if (method == null || !typeof(IDisposable).IsAssignableFrom(method.ReturnType)) { DiagLog.Warning("DiagLayer: " + fullName + " signature did not match; skipping " + name + " events."); } else if (!(method.Invoke(null, new object[4] { onEventHandler, onOperationScopeHandler, onCraftHandler, onOperationHandler }) is IDisposable disposable)) { DiagLog.Warning("DiagLayer: " + fullName + " already has an observer; skipping " + name + " events."); } else { attachedType = eventsType; registration = disposable; patchOutcomesMethod = eventsType.GetMethod("PatchOutcomes", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null); chestSettingsSummaryProperty = eventsType.GetProperty("ChestSettingsSummary", BindingFlags.Static | BindingFlags.Public); isIdleSettledProperty = eventsType.GetProperty("IsIdleSettled", BindingFlags.Static | BindingFlags.Public); idleSyncStatsProperty = eventsType.GetProperty("IdleSyncStats", BindingFlags.Static | BindingFlags.Public); DiagLog.Info("DiagLayer: attached to " + fullName + "."); } } catch (Exception ex) { Detach(); DiagLog.Warning("DiagLayer: could not attach to " + fullName + "; skipping " + name + " events. " + ex); } } internal static void Detach() { IDisposable disposable = registration; registration = null; attachedType = null; patchOutcomesMethod = null; chestSettingsSummaryProperty = null; isIdleSettledProperty = null; idleSyncStatsProperty = null; if (disposable == null) { return; } try { disposable.Dispose(); } catch (Exception ex) { DiagLog.Warning("DiagLayer: could not detach CompatEvents registration: " + ex.Message); } } internal static string PatchOutcomes() { if (patchOutcomesMethod != null) { try { if (patchOutcomesMethod.Invoke(null, null) is string { Length: >0 } text) { return text; } } catch (Exception error) { ChestDiagnostics.Fault("CompatBridge.PatchOutcomes", error); } } return "DiagLayer " + typeof(Plugin).Assembly.GetName().Version.ToString(3); } internal static string? ChestSettingsSummary() { if (!(chestSettingsSummaryProperty?.GetValue(null) is Func<string> func)) { return null; } try { return func(); } catch (Exception error) { ChestDiagnostics.Fault("CompatBridge.ChestSettingsSummary", error); return null; } } internal static bool IsIdleSettled(ZSyncTransform sync) { if (!(isIdleSettledProperty?.GetValue(null) is Func<ZSyncTransform, bool> func)) { return false; } try { return func(sync); } catch (Exception error) { ChestDiagnostics.Fault("CompatBridge.IsIdleSettled", error); return false; } } internal static (bool Active, int Settled, long Skipped, long Checked)? IdleSyncStats() { if (!(idleSyncStatsProperty?.GetValue(null) is Func<(bool, int, long, long)> func)) { return null; } try { return func(); } catch (Exception error) { ChestDiagnostics.Fault("CompatBridge.IdleSyncStats", error); return null; } } private static void HandleEvent(string kind, Container? chest, string details, int severity, string extra) { try { ChestDiagnostics.Record(kind, chest, details, severity switch { 1 => Severity.Warning, 2 => Severity.Problem, _ => Severity.Info, }, extra); } catch (Exception error) { ChestDiagnostics.Fault("CompatBridge.Event", error); } } private static Action? HandleOperationScope(string operation) { string previous = ChestDiagnostics.Operation; ChestDiagnostics.Operation = operation; return delegate { ChestDiagnostics.Operation = previous; }; } private static Action<Exception?>? HandleCraft(Player player, string description, IReadOnlyList<Inventory> inventories, bool unmeasured) { if (!ChestDiagnostics.Enabled) { return null; } Dictionary<string, int> before; try { before = ChestDiagnostics.Counts(inventories); } catch (Exception error) { ChestDiagnostics.Fault("CompatBridge.BeginCraft", error); return null; } return delegate(Exception? exception) { try { Dictionary<string, int> delta = ChestDiagnostics.Delta(before, ChestDiagnostics.Counts(inventories)); CraftingStation currentCraftingStation = player.GetCurrentCraftingStation(); ClassifyCraft(delta, unmeasured, currentCraftingStation, exception, out string kind, out Severity severity); ChestDiagnostics.Record(kind, null, description + ";delta=" + ChestDiagnostics.Format(delta) + (unmeasured ? ";note=some sources have no inventory and are not counted" : ""), severity, (exception == null) ? "" : exception.ToString()); } catch (Exception error2) { ChestDiagnostics.Fault("CompatBridge.EndCraft", error2); } }; } private static void ClassifyCraft(Dictionary<string, int> delta, bool unmeasured, CraftingStation? station, Exception? exception, out string kind, out Severity severity) { bool flag = delta.Values.Any((int value) => value > 0); bool flag2 = delta.Values.Any((int value) => value < 0); kind = "craft-result"; severity = Severity.Info; if (exception != null) { kind = "craft-exception"; severity = Severity.Problem; } else if (flag && !flag2) { kind = "craft-output-without-consumption"; severity = (unmeasured ? Severity.Warning : Severity.Problem); } else if (flag2 && !flag) { kind = "craft-consumed-without-output"; severity = (((Object)(object)station != (Object)null && station.m_upgrader) ? Severity.Warning : Severity.Problem); } } private static (Action<IReadOnlyList<Container>, IReadOnlyList<(Container Chest, float Distance)>> TrackChests, Action<Exception?> End)? HandleOperation(string operation, Player player, float range) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) if (!ChestDiagnostics.Enabled) { return null; } string previous = ChestDiagnostics.Operation; ChestDiagnostics.Operation = operation; Dictionary<string, int> before = null; try { Vector3 position = ((Component)player).transform.position; before = ChestDiagnostics.Counts((IEnumerable<Inventory>)(object)new Inventory[1] { ((Humanoid)player).GetInventory() }); ChestDiagnostics.Record("operation-start", null, "range=" + range + ";position=" + WorldProbe.Text(position) + ";player_items=" + ChestDiagnostics.Items(((Humanoid)player).GetInventory())); } catch (Exception error) { ChestDiagnostics.Fault("CompatBridge.BeginOperation", error); } return (TrackChests, End); void End(Exception? exception) { try { if (before != null) { ChestDiagnostics.Record("operation-end", null, "player_delta=" + ChestDiagnostics.Format(ChestDiagnostics.Delta(before, ChestDiagnostics.Counts((IEnumerable<Inventory>)(object)new Inventory[1] { ((Humanoid)player).GetInventory() }))) + ((exception == null) ? "" : (";exception=" + exception)), (exception != null) ? Severity.Problem : Severity.Info); ItemLedger.EndOperation(player); } } catch (Exception error2) { ChestDiagnostics.Fault("CompatBridge.EndOperation", error2); } finally { ChestDiagnostics.Operation = previous; } } void TrackChests(IReadOnlyList<Container> refreshed, IReadOnlyList<(Container Chest, float Distance)> outside) { try { Container[] array = ItemLedger.BeginOperation(operation, player, refreshed, outside); foreach (Container chest in array) { ChestDiagnostics.Record("operation-chest", chest); } } catch (Exception error2) { ChestDiagnostics.Fault("ItemLedger.BeginOperation", error2); } } } } internal static class ContainerTracker { private static readonly FieldRef<Container, ZNetView> view = AccessTools.FieldRefAccess<Container, ZNetView>(AccessTools.Field(typeof(Container), "m_nview")); private static readonly FieldRef<Container, uint> lastRevision = AccessTools.FieldRefAccess<Container, uint>(AccessTools.Field(typeof(Container), "m_lastRevision")); private static readonly Dictionary<ZNetView, Container> views = new Dictionary<ZNetView, Container>(ReferenceComparer<ZNetView>.Instance); private static readonly Dictionary<Container, ZDOID> ids = new Dictionary<Container, ZDOID>(ReferenceComparer<Container>.Instance); private static readonly Dictionary<ZDOID, Container> containers = new Dictionary<ZDOID, Container>(); private static readonly Dictionary<Inventory, Container> inventories = new Dictionary<Inventory, Container>(); private static readonly Dictionary<ZDOID, (uint Revision, string Hash)> hashes = new Dictionary<ZDOID, (uint, string)>(); internal static int Count => containers.Count; internal static ZNetView? View(Container? chest) { ZNetView val = (((Object)(object)chest == (Object)null) ? null : view.Invoke(chest)); if (!((Object)(object)val == (Object)null)) { return val; } return null; } internal static ZDO? LiveZdo(Container? chest) { ZNetView val = View(chest); if (!((Object)(object)val != (Object)null)) { return null; } return val.GetZDO(); } internal static ZDOID? IdOf(Container? chest) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (chest == null || !ids.TryGetValue(chest, out var value)) { return LiveZdo(chest)?.m_uid; } return value; } internal static uint LoadedRevision(Container chest) { return lastRevision.Invoke(chest); } internal static Container? Find(ZDOID id) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (!containers.TryGetValue(id, out Container value) || LiveZdo(value) == null) { return null; } return value; } internal static Container? Find(Inventory inventory) { if (!inventories.TryGetValue(inventory, out Container value) || LiveZdo(value) == null) { return null; } return value; } internal static string PayloadHash(ZDO zdo) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) if (hashes.TryGetValue(zdo.m_uid, out (uint, string) value) && value.Item1 == zdo.DataRevision) { return value.Item2; } byte[] byteArray = zdo.GetByteArray(ZDOVars.s_items, (byte[])null); string text = ""; if (byteArray != null) { using SHA256 sHA = SHA256.Create(); text = BitConverter.ToString(sHA.ComputeHash(byteArray)).Replace("-", "").ToLowerInvariant(); } if (hashes.Count > 4096) { hashes.Clear(); } hashes[zdo.m_uid] = (zdo.DataRevision, text); return text; } internal static void Track(Container __instance) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) try { ZNetView val = View(__instance); if (!((Object)(object)val == (Object)null) && val.IsValid() && __instance.GetInventory() != null && !views.ContainsKey(val)) { ZDOID uid = val.GetZDO().m_uid; views[val] = __instance; ids[__instance] = uid; containers[uid] = __instance; inventories[__instance.GetInventory()] = __instance; ChestDiagnostics.Record("container-loaded", __instance); } } catch (Exception error) { ChestDiagnostics.Fault("ContainerTracker.Track", error); } } internal static void Forget(ZNetView __instance) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) try { if (views.TryGetValue(__instance, out Container value)) { ZDOID val = ids[value]; ChestDiagnostics.Record("container-unloaded", value); views.Remove(__instance); ids.Remove(value); inventories.Remove(value.GetInventory()); hashes.Remove(val); if (containers.TryGetValue(val, out Container value2) && value2 == value) { containers.Remove(val); } DiagnosticsPatch.Forget(val); } } catch (Exception error) { ChestDiagnostics.Fault("ContainerTracker.Forget", error); } } internal static void Reset() { views.Clear(); ids.Clear(); containers.Clear(); inventories.Clear(); hashes.Clear(); DiagnosticsPatch.ClearState(); } } internal static class DiagLog { internal static Action<string> Info = delegate { }; internal static Action<string> Warning = delegate { }; internal static Action<string> Error = delegate { }; private static readonly object hashGate = new object(); private static readonly Dictionary<string, (long Length, DateTime Written, string Hash)> hashes = new Dictionary<string, (long, DateTime, string)>(StringComparer.Ordinal); internal static bool IsServer() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 RuntimePlatform platform = Application.platform; if (platform - 43 <= 2) { return true; } return false; } internal static string Sha256(string path) { FileInfo fileInfo = new FileInfo(path); long length = fileInfo.Length; DateTime lastWriteTimeUtc = fileInfo.LastWriteTimeUtc; lock (hashGate) { if (hashes.TryGetValue(path, out (long, DateTime, string) value) && value.Item1 == length && value.Item2 == lastWriteTimeUtc) { return value.Item3; } } string text; using (SHA256 sHA = SHA256.Create()) { using FileStream inputStream = File.OpenRead(path); text = BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", ""); } lock (hashGate) { hashes[path] = (length, lastWriteTimeUtc, text); return text; } } } internal static class KnownMods { internal const string CrossModCompat = "CrossModCompat"; internal const string DeepNorthCompat = "DeepNorthCompat"; internal const string MultiUserChest = "com.maxsch.valheim.MultiUserChest"; internal const string QuickStack = "goldenrevolver.quick_stack_store"; internal const string CraftyBoxes = "Azumatt.AzuCraftyBoxes"; internal const string AaaCrafting = "Azumatt.AzuAntiArthriticCrafting"; internal const string ReforgedPotential = "akuichi.ReforgedPotential"; internal const string ImpactfulSkills = "MidnightsFX.ImpactfulSkills"; internal const string Vpo = "dev.ontrigger.vpo"; internal const string Vcp = "MidnightsFX.ValheimCommunityPatch"; internal const string ValheimTune = "akoozie.valheimtune"; internal const string BetterMap = "xtav1m.BetterMap"; internal const string Cartography = "advize.CartographySkill"; internal const string TeleportEverything = "odinplus.TeleportEverything"; internal const string SteadyFrame = "ru.ivest.steadyframe"; internal const string FarLands = "ru.ivest.farlands"; internal const string HeightmapUnlimited = "digitalroot.mods.heightmapunlimitedjvl"; internal const string WorkbenchTweaks = "Azumatt.AzuWorkbenchTweaks"; } internal sealed class ReferenceComparer<T> : IEqualityComparer<T> where T : class { internal static readonly ReferenceComparer<T> Instance = new ReferenceComparer<T>(); public bool Equals(T? x, T? y) { return x == y; } public int GetHashCode(T obj) { return RuntimeHelpers.GetHashCode(obj); } } internal static class DiagnosticReport { internal enum Access { Nobody, Admins, Everyone } private sealed class Error { internal string Source = ""; internal string Level = ""; internal string Text = ""; internal int Count; internal DateTime First; internal DateTime Last; internal string[] Context = Array.Empty<string>(); } private sealed class Budget { internal int Findings; internal int Context; internal int Errors; internal int ErrorText; internal int Recent; } private sealed class Listener : ILogListener, IDisposable { public void LogEvent(object sender, LogEventArgs eventArgs) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) ILogSource source = eventArgs.Source; Capture(((source != null) ? source.SourceName : null) ?? "", eventArgs.Level, eventArgs.Data?.ToString() ?? ""); } public void Dispose() { } } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static Func<string, bool> <>9__43_0; public static ConsoleEvent <>9__44_0; public static ConsoleEvent <>9__44_1; public static Func<bool, string> <>9__63_0; public static Func<FileInfo, bool> <>9__81_0; public static Func<FileInfo, DateTime> <>9__81_1; public static Func<Error, DateTime> <>9__89_0; public static Func<KeyValuePair<string, int>, string> <>9__92_0; public static Func<PluginInfo, string> <>9__92_1; public static Func<PluginInfo, string> <>9__92_2; public static Func<Error, int> <>9__94_0; public static Func<string, string> <>9__97_0; internal bool <CountError>b__43_0(string line) { return line.Trim().Length > 0; } internal void <RegisterCommands>b__44_0(ConsoleEventArgs args) { if (args.Args.Length > 1 && string.Equals(args.Args[1], "last", StringComparison.OrdinalIgnoreCase)) { SendPrevious(args.Context); } else { Collect(args.Context); } } internal void <RegisterCommands>b__44_1(ConsoleEventArgs args) { MarkCommand(args.Context, string.Join(" ", args.Args.Skip(1))); } internal string <MarkCommand>b__63_0(bool compact) { return Snapshot(compact, null); } internal bool <Save>b__81_0(FileInfo file) { return !IsPinned(file.Name); } internal DateTime <Save>b__81_1(FileInfo file) { return file.LastWriteTimeUtc; } internal DateTime <Errors>b__89_0(Error error) { return error.First; } internal string <Tail>b__92_0(KeyValuePair<string, int> entry) { return entry.Key + " " + entry.Value; } internal string <Tail>b__92_1(PluginInfo info) { return info.Metadata.GUID; } internal string <Tail>b__92_2(PluginInfo info) { return info.Metadata.GUID + " " + info.Metadata.Version; } internal int <ErrorSummary>b__94_0(Error error) { return error.Count; } internal string <RelevantMods>b__97_0(string guid) { if (!Chainloader.PluginInfos.TryGetValue(guid, out var value)) { return guid + " absent"; } return guid + " " + value.Metadata.Version?.ToString() + " sha256:" + Hash(value.Location); } } private const string HelloRpc = "DiagLayer.Hello.v1"; private const string RequestRpc = "DiagLayer.ReportRequest.v1"; private const string ReplyRpc = "DiagLayer.ReportReply.v1"; private const string ProbeRpc = "DiagLayer.ReportProbe.v1"; private const int ReplyLimit = 98304; private const float RequestInterval = 10f; private const int ReportsRetained = 30; private const int ErrorLimit = 40; private const int StartupLimit = 300; private const string LatestSuffix = "latest"; private const string PreviousSuffix = "previous"; private const string SentSuffix = "previous-sent"; private static readonly string[] Pinned = new string[3] { "latest", "previous", "previous-sent" }; private static readonly Budget Full = new Budget { Findings = 60, Context = 12, Errors = 30, ErrorText = 2500, Recent = 60 }; private static readonly Budget Compact = new Budget { Findings = 20, Context = 6, Errors = 12, ErrorText = 1200, Recent = 20 }; private static readonly string[] Relevant = new string[17] { "DiagLayer", "CrossModCompat", "DeepNorthCompat", "com.maxsch.valheim.MultiUserChest", "goldenrevolver.quick_stack_store", "Azumatt.AzuCraftyBoxes", "Azumatt.AzuAntiArthriticCrafting", "akuichi.ReforgedPotential", "MidnightsFX.ImpactfulSkills", "dev.ontrigger.vpo", "MidnightsFX.ValheimCommunityPatch", "akoozie.valheimtune", "xtav1m.BetterMap", "advize.CartographySkill", "odinplus.TeleportEverything", "ru.ivest.steadyframe", "ru.ivest.farlands" }; private static readonly object gate = new object(); private static readonly List<string> startup = new List<string>(); private static readonly Dictionary<string, Error> errors = new Dictionary<string, Error>(StringComparer.Ordinal); private static readonly Dictionary<long, string> hellos = new Dictionary<long, string>(); private static readonly Dictionary<long, (Vector3 Point, ZDOID Looked)> probes = new Dictionary<long, (Vector3, ZDOID)>(); private static readonly Dictionary<long, float> answered = new Dictionary<long, float>(); private static int droppedErrors; private static int writtenVersion = -1; private static string? serverHello; private static long request; private static string? serverReport; private static string serverStatus = ""; private static float nextAutoWrite; private static bool hinted; private static readonly Regex Footer = new Regex("<!-- DiagLayer session (\\w+) world (-?\\d+) clean (yes|no) -->\\s*$"); internal static Access ServerAccess = Access.Admins; private static Listener? listener; private static string PluginVersion => typeof(Plugin).Assembly.GetName().Version.ToString(3); private static string ReportDirectory => Path.Combine(ChestDiagnostics.Directory ?? ".", "reports"); private static string FooterLine(string session, long world, bool clean) { return "<!-- DiagLayer session " + session + " world " + world.ToString(CultureInfo.InvariantCulture) + " clean " + (clean ? "yes" : "no") + " -->"; } internal static void Listen() { lock (gate) { if (listener == null) { listener = new Listener(); Logger.Listeners.Add((ILogListener)(object)listener); } } } internal static void StopListening() { lock (gate) { if (listener != null) { Logger.Listeners.Remove((ILogListener)(object)listener); listener = null; } } } internal unsafe static void Capture(string source, LogLevel level, string text) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) if (ChestDiagnostics.Recording) { return; } bool flag; switch (source) { case "DiagLayer": case "CrossModCompat": case "DeepNorthCompat": flag = true; break; default: flag = false; break; } bool flag2 = flag; bool flag3 = IsError(level, text); if (!flag2 && !flag3) { return; } DateTime utcNow = DateTime.UtcNow; Error error = null; lock (gate) { if (flag2) { AddStartup(utcNow, level, text); } if (flag3) { error = CountError(source, level, text, utcNow); } } if (error != null) { string[] context = ChestDiagnostics.RecentLines(5); lock (gate) { error.Context = context; } ChestDiagnostics.RecordText("log-error", source + " " + ((object)(*(LogLevel*)(&level))/*cast due to .constrained prefix*/).ToString() + ": " + Clip(text.Split(new char[1] { '\n' })[0], 300)); } } private static bool IsError(LogLevel level, string text) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) if ((level & 3) == 0 && text.IndexOf("Exception", StringComparison.Ordinal) < 0) { return text.IndexOf("Failed to find rpc method", StringComparison.Ordinal) >= 0; } return true; } private unsafe static void AddStartup(DateTime now, LogLevel level, string text) { startup.Add(now.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + " " + ((object)(*(LogLevel*)(&level))/*cast due to .constrained prefix*/).ToString() + " " + Clip(text, 700)); if (startup.Count > 300) { startup.RemoveAt(100); } } private unsafe static Error? CountError(string source, LogLevel level, string text, DateTime now) { string[] array = text.Split(new char[1] { '\n' }); string key = source + "|" + array[0].Trim() + "|" + array.Skip(1).FirstOrDefault((string line) => line.Trim().Length > 0)?.Trim(); if (errors.TryGetValue(key, out Error value)) { value.Count++; value.Last = now; return null; } if (errors.Count >= 40) { droppedErrors++; return null; } Error error = new Error { Source = source, Level = ((object)(*(LogLevel*)(&level))/*cast due to .constrained prefix*/).ToString(), Text = text.TrimEnd(Array.Empty<char>()), Count = 1, First = now, Last = now }; errors[key] = error; return error; } internal static void RegisterCommands() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown object obj = <>c.<>9__44_0; if (obj == null) { ConsoleEvent val = delegate(ConsoleEventArgs args) { if (args.Args.Length > 1 && string.Equals(args.Args[1], "last", StringComparison.OrdinalIgnoreCase)) { SendPrevious(args.Context); } else { Collect(args.Context); } }; <>c.<>9__44_0 = val; obj = (object)val; } new ConsoleCommand("dl_report", "DiagLayer: save a diagnostic report, send it to the server operator, and copy it with the server's report to the clipboard. Both describe the terrain, base areas and creatures where you stand. `dl_report last` sends the report from your previous session instead.", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj2 = <>c.<>9__44_1; if (obj2 == null) { ConsoleEvent val2 = delegate(ConsoleEventArgs args) { MarkCommand(args.Context, string.Join(" ", args.Args.Skip(1))); }; <>c.<>9__44_1 = val2; obj2 = (object)val2; } new ConsoleCommand("dl_mark", "DiagLayer: mark a problem now and send it to the server operator, for example: dl_mark chest showed old items", (ConsoleEvent)obj2, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } internal static void GameStarted() { ZRoutedRpc.instance.Register<ZPackage>("DiagLayer.Hello.v1", (Action<long, ZPackage>)ReceiveHello); ZRoutedRpc.instance.Register<long>("DiagLayer.ReportRequest.v1", (Action<long, long>)ReceiveRequest); ZRoutedRpc.instance.Register<ZPackage>("DiagLayer.ReportReply.v1", (Action<long, ZPackage>)ReceiveReply); ZRoutedRpc.instance.Register<ZPackage>("DiagLayer.ReportProbe.v1", (Action<long, ZPackage>)ReceiveProbe); lock (gate) { hellos.Clear(); probes.Clear(); answered.Clear(); serverHello = null; } ReportUpload.WorldStarted(); ChestDiagnostics.Record("world-start", null, Environment(compact: true)); } internal static void LocalPlayerSpawned(Player player) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer() && ZRoutedRpc.instance != null) { ZPackage val = new ZPackage(); val.Write(player.GetPlayerName()); val.Write(player.GetPlayerID()); val.Write(CompatBridge.PatchOutcomes()); ZRoutedRpc.instance.InvokeRoutedRPC("DiagLayer.Hello.v1", new object[1] { val }); } } private static void ReceiveHello(long sender, ZPackage packet) { try { if (ZNet.instance.IsServer()) { AnswerHello(sender, packet); } else { ReadServerHello(sender, packet); } } catch (Exception error) { ChestDiagnostics.Fault("ReceiveHello", error); } } private static void AnswerHello(long sender, ZPackage packet) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown string text = packet.ReadString(); long num = packet.ReadLong(); string text2 = packet.ReadString(); string text3 = "player " + text + " (" + num + "); " + text2; lock (gate) { hellos[sender] = text3; } ChestDiagnostics.Record("peer-hello", null, "peer=" + sender + ";" + text3); ZPackage val = new ZPackage(); val.Write(CompatBridge.PatchOutcomes()); val.Write(ReportUpload.Accepting); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "DiagLayer.Hello.v1", new object[1] { val }); } private static void ReadServerHello(long sender, ZPackage packet) { string text = packet.ReadString(); bool flag = packet.ReadBool(); lock (gate) { serverHello = text; } ReportUpload.ServerAccepts = flag; ChestDiagnostics.Record("server-hello", null, "server=" + sender + ";accepts_reports=" + flag + ";" + text); if (flag) { HintPrevious(); } } internal static void PeerDisconnecting(ZNetPeer peer) { if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer()) { ChestDiagnostics.Record("peer-disconnected", null, "peer=" + peer.m_uid + ";player=" + peer.m_playerName); lock (gate) { hellos.Remove(peer.m_uid); probes.Remove(peer.m_uid); answered.Remove(peer.m_uid); } ReportUpload.PeerGone(peer.m_uid); } } internal static void WorldShutdown() { ChestDiagnostics.Record("world-shutdown", null); SaveLatest(clean: true); } private static void SaveLatest(bool clean) { Save(Build(Full, includeServer: false) + "\n" + FooterLine(ChestDiagnostics.Session, CurrentWorld(), clean) + "\n", "latest"); } private static long CurrentWorld() { if (!((Object)(object)ZNet.instance != (Object)null) || ZNet.World == null) { return 0L; } return ZNet.World.m_uid; } internal static void PreservePrevious() { if (ChestDiagnostics.Directory == null) { return; } string text = ReportPath("latest"); string text2 = ReportPath("previous"); string path = ReportPath("previous-sent"); try { if (File.Exists(text)) { if (File.Exists(text2)) { File.Delete(text2); } if (File.Exists(path)) { File.Delete(path); } File.Move(text, text2); } } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { DiagLog.Error("DiagLayer could not keep the previous session's report: " + ex); } } private static string ReportPath(string suffix) { return Path.Combine(ReportDirectory, ReportName(ChestDiagnostics.Role, suffix)); } private static string ReportName(string role, string suffix) { return "DiagLayer-report-" + role + "-" + suffix + ".md"; } internal static (string Path, string Text, long World, bool Clean, bool Sent)? Previous() { if (ChestDiagnostics.Directory == null) { return null; } (string, bool)[] array = new(string, bool)[2] { (ReportPath("previous"), false), (ReportPath("previous-sent"), true) }; for (int i = 0; i < array.Length; i++) { var (text, item) = array[i]; try { if (!File.Exists(text)) { continue; } string text2 = File.ReadAllText(text); Match match = Footer.Match(text2); return match.Success ? (text, text2, long.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), match.Groups[3].Value == "yes", item) : (text, text2, 0L, true, item); } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException || ex is OverflowException) ? 1 : 0) != 0) { return null; } } return null; } internal static void MarkPreviousSent(string path) { try { if (path == ReportPath("previous") && File.Exists(path)) { File.Move(path, ReportPath("previous-sent")); } } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { DiagLog.Error("DiagLayer could not mark the previous session's report as sent: " + ex); } } private static void HintPrevious() { if (hinted || !ReportUpload.Send) { return; } (string, string, long, bool, bool)? tuple = Previous(); if (tuple.HasValue && !tuple.Value.Item5 && !tuple.Value.Item4 && tuple.Value.Item3 != 0L && tuple.Value.Item3 == CurrentWorld()) { hinted = true; if ((Object)(object)Chat.instance != (Object)null) { ((Terminal)Chat.instance).AddString("DiagLayer: your last session in this world ended unexpectedly. Type /dl_report last to send its report to the server."); } } } private static void SendPrevious(Terminal context) { //IL_00f1: Unknown result type (might be due to invalid IL or missing references) if (!ChestDiagnostics.Enabled) { context.AddString("DiagLayer is disabled in its config."); return; } if (!ReportUpload.Send) { context.AddString("DiagLayer: sending reports is off in this client's config (Send reports to server)."); return; } if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || ZNet.instance.GetServerPeer() == null) { context.AddString("DiagLayer: join the server first, then type /dl_report last."); return; } (string, string, long, bool, bool)? tuple = Previous(); if (!tuple.HasValue) { context.AddString("DiagLayer: no report from a previous session was found."); return; } if (tuple.Value.Item5) { context.AddString("DiagLayer: the previous session's report was already sent to the server."); return; } if (tuple.Value.Item3 != 0L && tuple.Value.Item3 != CurrentWorld()) { context.AddString("DiagLayer: the previous session's report is from a different world. Join that world to send it."); return; } string text = tuple.Value.Item2; ReportUpload.Submit(context, "last", "", (bool _) => text, null, ZDOID.None, tuple.Value.Item1); } internal static void Prewarm() { if (!ChestDiagnostics.Enabled) { return; } try { Build(Full, includeServer: false); } catch (Exception error) { ChestDiagnostics.Fault("DiagnosticReport.Prewarm", error); } } internal static void Tick() { if (!ChestDiagnostics.Enabled) { return; } ReportUpload.Tick(); try { ItemLedger.Tick(); } catch (Exception error) { ChestDiagnostics.Fault("ItemLedger.Tick", error); } if (nextAutoWrite == 0f) { nextAutoWrite = Time.realtimeSinceStartup + 300f; } if (!(Time.realtimeSinceStartup < nextAutoWrite)) { nextAutoWrite = Time.realtimeSinceStartup + 300f; if (ChestDiagnostics.Version != writtenVersion) { writtenVersion = ChestDiagnostics.Version; SaveLatest((Object)(object)ZNet.instance == (Object)null); } } } private static void MarkCommand(Terminal context, string note) { //IL_0097: Unknown result type (might be due to invalid IL or missing references) if (!ChestDiagnostics.Enabled) { context.AddString("DiagLayer is disabled in its config."); return; } if (note.Trim().Length == 0) { note = "(no note)"; } ChestDiagnostics.Mark(((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerName() : "local", note); string note2 = ReportUpload.Redact(note); context.AddString("DiagLayer: marked \"" + note + "\". Reproduce if you can, then type /dl_report."); ReportUpload.Submit(context, "marker", note2, (bool compact) => Snapshot(compact, null), null, ZDOID.None); } private static void Collect(Terminal context) { //IL_006f: Unknown result type (might be due to invalid IL or missing references) if (!ChestDiagnostics.Enabled) { context.AddString("DiagLayer is disabled in its config."); return; } ZRoutedRpc val = (((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer() && ZNet.instance.GetServerPeer() != null) ? ZRoutedRpc.instance : null); Vector3? at; ZDOID target; string[] probe = Probe(val, out at, out target); ReportUpload.Submit(context, "report", "", (bool compact) => Snapshot(compact, probe), at, target); if (val != null) { RequestServer(context, val, probe); return; } lock (gate) { serverReport = null; serverStatus = (((Object)(object)ZNet.instance == (Object)null) ? "not in a world" : "this peer is the server"); } Deliver(context, probe); } private static string[]? Probe(ZRoutedRpc? server, out Vector3? at, out ZDOID target) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) at = null; target = ZDOID.None; Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)ZNet.instance == (Object)null) { return null; } Vector3 position = ((Component)localPlayer).transform.position; Character hoverCreature = localPlayer.GetHoverCreature(); target = (((Object)(object)hoverCreature == (Object)null) ? ZDOID.None : hoverCreature.GetZDOID()); at = position; string[] result = WorldProbe.Capture(position, target); if (server == null) { return result; } ZPackage val = new ZPackage(); val.Write(position); val.Write(target); server.InvokeRoutedRPC("DiagLayer.ReportProbe.v1", new object[1] { val }); return result; } private static void RequestServer(Terminal context, ZRoutedRpc server, string[]? probe) { lock (gate) { request = DateTime.UtcNow.Ticks; serverReport = null; serverStatus = "no reply within 10 seconds"; } server.InvokeRoutedRPC("DiagLayer.ReportRequest.v1", new object[1] { request }); context.AddString("DiagLayer: collecting the server's report..."); Plugin instance = Plugin.Instance; if ((Object)(object)instance != (Object)null) { ((MonoBehaviour)instance).StartCoroutine(Finish(context, request, probe)); return; } lock (gate) { serverStatus = "plugin instance unavailable"; } } private static void ReceiveProbe(long sender, ZPackage packet) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } try { Vector3 val = packet.ReadVector3(); ZDOID item = packet.ReadZDOID(); float f = val.x + val.y + val.z; if (float.IsNaN(f) || float.IsInfinity(f)) { return; } lock (gate) { probes[sender] = (val, item); } } catch (Exception error) { ChestDiagnostics.Fault("ReceiveProbe", error); } } private static IEnumerator Finish(Terminal context, long id, string[]? probe) { float until = Time.realtimeSinceStartup + 10f; while (Time.realtimeSinceStartup < until) { lock (gate) { if (request != id || serverReport != null) { break; } goto IL_005c; } IL_005c: yield return null; } Deliver(context, probe); } private static void Deliver(Terminal context, string[]? probe) { string text = Build(Full, includeServer: true, probe); string text2 = Save(text, "combined"); GUIUtility.systemCopyBuffer = text; context.AddString("DiagLayer: report copied to the clipboard (" + (text.Length / 1024 + 1) + " KB)." + ((text2 == null) ? "" : (" Saved to " + text2.Replace('\\', '/')))); } private static void ReceiveRequest(long sender, long id) { try { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) { AnswerRequest(sender, id); } } catch (Exception error) { ChestDiagnostics.Fault("ReceiveRequest", error); } } private static void AnswerRequest(long sender, long id) { //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) if (Throttled(sender)) { ChestDiagnostics.Record("report-request", null, "peer=" + sender + ";throttled=true"); Reply(sender, id, allowed: false, "the server built a report for you less than " + 10f + " seconds ago. Run the command again in a few seconds."); return; } ZNetPeer peer = ZNet.instance.GetPeer(sender); bool flag = ServerAccess == Access.Everyone || (ServerAccess == Access.Admins && peer != null && ZNet.instance.IsAdmin(peer.m_socket.GetHostName())); bool flag2; (Vector3, ZDOID) value; lock (gate) { flag2 = probes.TryGetValue(sender, out value); probes.Remove(sender); } string[] probe = ((flag2 && flag) ? WorldProbe.Capture(value.Item1, value.Item2) : null); string text = Build(Full, includeServer: false, probe); Save(text, "requested"); if (flag && Encoding.UTF8.GetByteCount(text) > 98304) { text = Build(Compact, includeServer: false, probe); } if (flag && Encoding.UTF8.GetByteCount(text) > 98304) { text = text.Substring(0, 49152) + "\n\n(truncated to fit the network limit)\n"; } ChestDiagnostics.Record("report-request", null, "peer=" + sender + ";player=" + peer?.m_playerName + ";allowed=" + flag + ";access=" + ServerAccess); string text2 = ((ServerAccess == Access.Admins) ? "admins (adminlist.txt)" : "nobody"); Reply(sender, id, flag, flag ? text : ("The server saved its report in " + ReportDirectory + ". It sends reports only to " + text2 + ". Change `Server report access` in the server's BepInEx/config/DiagLayer.cfg to allow this.")); } private static bool Throttled(long sender) { float realtimeSinceStartup = Time.realtimeSinceStartup; lock (gate) { if (answered.TryGetValue(sender, out var value) && realtimeSinceStartup - value < 10f) { probes.Remove(sender); return true; } answered[sender] = realtimeSinceStartup; } return false; } private static void Reply(long sender, long id, bool allowed, string text) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(id); val.Write(allowed); val.Write(text); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "DiagLayer.ReportReply.v1", new object[1] { val }); } private static void ReceiveReply(long sender, ZPackage packet) { try { long id = packet.ReadLong(); bool allowed = packet.ReadBool(); string text = packet.ReadString(); lock (gate) { StoreReply(id, allowed, text); } } catch (Exception error) { ChestDiagnostics.Fault("ReceiveReply", error); } } private static void StoreReply(long id, bool allowed, string text) { if (id == request) { if (allowed) { serverReport = text; serverStatus = "received"; } else { serverReport = ""; serverStatus = "refused: " + text; } } } private static bool IsPinned(string fileName) { return Array.Exists(Pinned, (string suffix) => fileName.EndsWith("-" + suffix + ".md", StringComparison.Ordinal)); } internal static string? Save(string text, string kind) { if (ChestDiagnostics.Directory == null) { return null; } try { Directory.CreateDirectory(ReportDirectory); string text2 = ReportPath((kind == "latest") ? "latest" : (DateTime.UtcNow.ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture) + "-" + kind)); File.WriteAllText(text2, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); foreach (FileInfo item in (from file in new DirectoryInfo(ReportDirectory).GetFiles("DiagLayer-report-*.md") where !IsPinned(file.Name) orderby file.LastWriteTimeUtc descending select file).Skip(30)) { item.Delete(); } return text2; } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { DiagLog.Error("DiagLayer could not save a report: " + ex); return null; } } internal static string Build(bool includeServer) { return Build(Full, includeServer); } internal static string Snapshot(bool compact, string[]? probe) { return Build(compact ? Compact : Full, includeServer: false, probe); } private static string Build(Budget budget, bool includeServer, string[]? probe = null) { ChestDiagnostics.SessionSnapshot snapshot = ChestDiagnostics.Snapshot(budget.Recent); StringBuilder stringBuilder = new StringBuilder(); string role = ChestDiagnostics.Role; DateTime utcNow = DateTime.UtcNow; stringBuilder.Append("# DiagLayer diagnostic report (").Append(role).AppendLine(")") .AppendLine(); stringBuilder.AppendLine("Times are UTC. Chest IDs match across peers; owner and peer values are network session IDs. Detailed event logs: `" + (ChestDiagnostics.Directory ?? "disabled") + "`.").AppendLine(); stringBuilder.AppendLine("Event lines read `time [severity] event [operation] chest=<id> owner=self|none|<peer> rev=<data revision>/<loaded revision> use=<local>/<replicated> payload=<item data hash> items=<name:quality:world level=count> | details`. A chest shows current contents when both revisions match. Finding blocks list that chest's earlier events, then the finding after `>`.").AppendLine(); Overview(stringBuilder, snapshot, role, utcNow); ProbeSection(stringBuilder, probe); Markers(stringBuilder, snapshot, budget); Findings(stringBuilder, snapshot, budget); Errors(stringBuilder, budget); if (role == "server" && (Object)(object)ZNet.instance != (Object)null) { Peers(stringBuilder); } Activity(stringBuilder, snapshot); Tail(stringBuilder, snapshot); ServerReport(stringBuilder, includeServer); return stringBuilder.ToString(); } private static void Overview(StringBuilder b, ChestDiagnostics.SessionSnapshot snapshot, string role, DateTime now) { b.AppendLine("## Overview").AppendLine(); string[] obj = new string[9] { "- Generated ", now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture), "; session ", ChestDiagnostics.Session, " started ", null, null, null, null }; DateTime started = ChestDiagnostics.Started; obj[5] = started.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); obj[6] = " ("; obj[7] = ((int)(now - ChestDiagnostics.Started).TotalMinutes).ToString(); obj[8] = " min ago)."; b.AppendLine(string.Concat(obj)); b.AppendLine("- " + Environment(compact: false)); lock (gate) { if (role == "client") { b.AppendLine("- Server: " + (serverHello ?? "no diagnostics reply this session (server diagnostics may be disabled).")); } } b.AppendLine("- Findings: " + ChestDiagnostics.Problems + " problems, " + ChestDiagnostics.Warnings + " warnings" + ((snapshot.Dropped > 0) ? (" (" + snapshot.Dropped + " middle findings omitted)") : "") + ". Errors: " + ErrorSummary() + ". Markers: " + snapshot.Markers.Length + "."); if (snapshot.Failures.Length != 0) { b.AppendLine("- Diagnostics faults: " + string.Join("; ", snapshot.Failures)); } b.AppendLine(); } private static void ProbeSection(StringBuilder b, string[]? probe) { if (probe != null) { b.AppendLine("## World probe").AppendLine(); b.AppendLine("What this peer holds at the position the report was requested from. The client and server reports each carry this block for the same point, so compare them line by line. `ground` is the terrain collider that creatures and spawn checks use. `generated` is the height before any edit, `stored` is the saved terrain edit and `applied` is how much of it this peer's terrain shows. `LIMITED` marks a peer that applies less than it stores, which happens when its terrain height limit is lower than the one used to make the edit. `owner` is `self`, `server`, `none` or a peer ID. A creature line ends with `BELOW GROUND` when the creature is more than 1 m under this peer's terrain. In the synced-object census, `settled` means the next vanilla sync would change nothing, and `skipped` counts sync calls the patch avoided.").AppendLine(); Block(b, probe); } } private static void Markers(StringBuilder b, ChestDiagnostics.SessionSnapshot snapshot, Budget budget) { if (snapshot.Markers.Length == 0) { return; } b.AppendLine("## Player markers").AppendLine(); ChestDiagnostics.Marker[] markers = snapshot.Markers; foreach (ChestDiagnostics.Marker marker in markers) { b.AppendLine("### " + marker.Utc.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + " " + marker.Who + ": " + marker.Note).AppendLine(); if (marker.Activity.Length != 0) { b.AppendLine("Item movements in the 20 minutes before:").AppendLine(); Block(b, marker.Activity.Skip(Math.Max(0, marker.Activity.Length - budget.Recent))); b.AppendLine("Events in the 90 seconds before:").AppendLine(); } Block(b, marker.Context.Skip(Math.Max(0, marker.Context.Length - budget.Recent))); } } private static void Findings(StringBuilder b, ChestDiagnostics.SessionSnapshot snapshot, Budget budget) { b.AppendLine("## Problems and warnings").AppendLine(); if (snapshot.Findings.Length == 0) { b.AppendLine("None recorded.").AppendLine(); } ChestDiagnostics.Finding[] array = snapshot.Findings.Skip(Math.Max(0, snapshot.Findings.Length - budget.Findings)).ToArray(); if (array.Length < snapshot.Findings.Length) { b.AppendLine("Showing the newest " + array.Length + " of " + snapshot.Findings.Length + ".").AppendLine(); } ChestDiagnostics.Finding[] array2 = array; foreach (ChestDiagnostics.Finding finding in array2) { b.AppendLine("### " + finding.Severity.ToString().ToUpperInvariant() + " " + finding.Kind + " at " + finding.Utc.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)).AppendLine(); Block(b, finding.Context.Skip(Math.Max(0, finding.Context.Length - budget.Context)).Concat(new string[1] { "> " + finding.Line }).Concat((finding.Extra.Length == 0) ? ((IEnumerable<string>)Array.Empty<string>()) : ((IEnumerable<string>)new string[1] { Clip(finding.Extra, budget.ErrorText) }))); } } private static void Errors(StringBuilder b, Budget budget) { b.AppendLine("## Errors and exceptions from all mods").AppendLine(); Error[] array; lock (gate) { array = errors.Values.OrderBy((Error error) => error.First).ToArray(); } if (array.Length == 0) { b.AppendLine("None recorded.").AppendLine(); } foreach (Error item in array.Skip(Math.Max(0, array.Length - budget.Errors))) { b.AppendLine("### " + item.Level + " from " + ((item.Source.Length == 0) ? "unknown" : item.Source) + ", " + item.Count + "x, first " + item.First.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + ", last " + item.Last.ToString("HH:mm:ss", CultureInfo.InvariantCulture)).AppendLine(); Block(b, new string[1] { Clip(item.Text, budget.ErrorText) }); if (item.Context.Length != 0) { b.AppendLine("Events before the first occurrence:").AppendLine(); Block(b, item.Context); } } } private static void Peers(StringBuilder b) { b.AppendLine("## Connected peers").AppendLine(); lock (gate) { foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { b.AppendLine("- " + peer.m_uid + " " + peer.m_playerName + ": " + (hellos.TryGetValue(peer.m_uid, out string value) ? value : "no diagnostics hello (peer diagnostics may be disabled).")); } } b.AppendLine(); } private static void Activity(StringBuilder b, ChestDiagnostics.SessionSnapshot snapshot) { if (snapshot.Activity.Length != 0) { b.AppendLine("## Item movements").AppendLine(); b.AppendLine("Quick Stack, restock and crafting results and other changes to the player's items, newest last. `operation-settled` nets a burst of presses after MultiUserChest returns what a chest could not hold; `unaccounted` must be `none`.").AppendLine(); Block(b, snapshot.Activity); } } private static void Tail(StringBuilder b, ChestDiagnostics.SessionSnapshot snapshot) { b.AppendLine("## Recent events").AppendLine(); Block(b, snapshot.Recent); b.AppendLine("## Event counts").AppendLine(); b.AppendLine(string.Join(", ", snapshot.Counts.Select((KeyValuePair<string, int> entry) => entry.Key + " " + entry.Value))).AppendLine(); b.AppendLine("## DiagLayer log").AppendLine(); lock (gate) { Block(b, startup.ToArray()); } b.AppendLine("## Settings and mods").AppendLine(); b.AppendLine("- " + Settings()); b.AppendLine("- Relevant mods: " + RelevantMods()); b.AppendLine("- All plugins: " + string.Join(", ", from info in Chainloader.PluginInfos.Values.OrderBy<PluginInfo, string>((PluginInfo info) => info.Metadata.GUID, StringComparer.OrdinalIgnoreCase) select info.Metadata.GUID + " " + info.Metadata.Version)); b.AppendLine(); } private static void ServerReport(StringBuilder b, bool includeServer) { if (includeServer) { string text; string value; lock (gate) { text = serverStatus; value = serverReport; } b.AppendLine("---").AppendLine(); if (!string.IsNullOrEmpty(value)) { b.Append(value); return; } b.AppendLine("# Server report unavailable").AppendLine().AppendLine("Status: " + text + ". The server writes `BepInEx/DiagLayer/reports/" + ReportName("server", "latest") + "` every five minutes and on shutdown; attach that file instead."); } } private static string ErrorSummary() { lock (gate) { return errors.Count + " unique, " + errors.Values.Sum((Error error) => error.Count) + " total" + ((droppedErrors > 0) ? (", " + droppedErrors + " more not kept") : ""); } } private static string Environment(bool compact) { string text = "DiagLayer " + PluginVersion + " " + ChestDiagnostics.Role + "; Valheim " + Version.GetVersionString(false) + "; peer " + ((ZDOMan.instance == null) ? "none" : ZDOMan.GetSessionID().ToString(CultureInfo.InvariantCulture)); if ((Object)(object)Player.m_localPlayer != (Object)null) { text = text + "; player " + Player.m_localPlayer.GetPlayerName() + " (" + Player.m_localPlayer.GetPlayerID() + ")"; } if (compact) { return text; } return text + "; game assembly " + Hash(typeof(ZNet).Assembly.Location) + "; " + SystemInfo.operatingSystem; } private static string Settings() { string text = CompatBridge.ChestSettingsSummary(); string text2 = "server report access " + ServerAccess.ToString() + "; tracked chests " + ContainerTracker.Count; if (!string.IsNullOrEmpty(text)) { return text + "; " + text2; } return text2; } private static string RelevantMods() { PluginInfo value; return string.Join(", ", Relevant.Select((string guid) => (!Chainloader.PluginInfos.TryGetValue(guid, out value)) ? (guid + " absent") : (guid + " " + value.Metadata.Version?.ToString() + " sha256:" + Hash(value.Location)))); } internal static string Hash(string path) { try { return DiagLog.Sha256(path).Substring(0, 16); } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException || ex is ArgumentException) ? 1 : 0) != 0) { return "unreadable"; } } private static void Block(StringBuilder b, IEnumerable<string> lines) { b.AppendLine("```text"); foreach (string line in lines) { b.AppendLine(line.Replace("```", "'''")); } b.AppendLine("```").AppendLine(); } private static string Clip(string value, int length) { if (value.Length > length) { return value.Substring(0, length) + "..."; } return value; } internal static void Clear() { lock (gate) { startup.Clear(); errors.Clear(); droppedErrors = 0; hellos.Clear(); probes.Clear(); answered.Clear(); serverHello = null; serverReport = null; serverStatus = ""; } hinted = false; ReportUpload.Clear(); } } internal static class DiagnosticsPatch { private readonly record struct SyncState(long Owner, uint Data, uint Loaded, bool Use, int Replicated); private const string Owner = "DiagLayer.Diagnostics"; private static readonly Harmony harmony = new Harmony("DiagLayer.Diagnostics"); private static readonly List<(MethodBase Target, MethodInfo Hook)> hooks = new List<(MethodBase, MethodInfo)>(); private static readonly HashSet<MethodBase> targets = new HashSet<MethodBase>(); private static readonly HashSet<MethodBase> built = new HashSet<MethodBase>(); private static readonly MethodInfo builtMarker = AccessTools.DeclaredMethod(typeof(DiagnosticsPatch), "Built", (Type[])null, (Type[])null); private static readonly Dictionary<ZDOID, SyncState> states = new Dictionary<ZDOID, SyncState>(); private static readonly Dictionary<ZDOID, string> contents = new Dictionary<ZDOID, string>(); [ThreadStatic] private static Container? loading; private static bool installed; private static bool verified; internal static bool Enabled { get; private set; } internal static void Install() { if (installed || !ChestDiagnostics.Enabled) { return; } try { Postfix(Method(typeof(Container), "Awake", typeof(void)), "TrackContainer", 0); Prefix(Method(typeof(ZNetView), "OnDestroy", typeof(void)), "ForgetView"); Postfix(Method(typeof(ZNet), "Shutdown", typeof(void), typeof(bool)), "ResetContainers"); Prefix(Method(typeof(Container), "SetInUse", typeof(void), typeof(bool)), "Use", 0); Prefix(Method(typeof(Container), "CheckForChanges", typeof(void)), "Check"); MethodInfo target = Method(typeof(Container), "Load", typeof(bool)); Prefix(target, "Loading"); Postfix(target, "Loaded"); Finalizer(target, "LoadEnded"); MethodInfo target2 = Method(typeof(Container), "Save", typeof(void)); Prefix(target2, "Saving"); Postfix(target2, "Saved"); Postfix(Method(typeof(Inventory), "Changed", typeof(void), typeof(bool), typeof(bool)), "InventoryChanged"); Prefix(Method(typeof(ZDO), "SetOwner", typeof(void), typeof(long)), "OwnerChanging"); Prefix(Method(typeof(ZDOMan), "RPC_ZDOData", typeof(void), typeof(ZRpc), typeof(ZPackage)), "Received"); Postfix(Method(typeof(Game), "Start", typeof(void)), "GameStarted"); Postfix(Method(typeof(Player), "OnSpawned", typeof(void), typeof(bool)), "Spawned"); Prefix(Method(typeof(ZNet), "Disconnect", typeof(void), typeof(ZNetPeer)), "Disconnecting"); Prefix(Method(typeof(ZNet), "Shutdown", typeof(void), typeof(bool)), "ShuttingDown"); Postfix(Method(typeof(ZRoutedRpc), "AddPeer", typeof(void), typeof(ZNetPeer)), "PeerAdded"); installed = true; } catch (Exception ex) { Rollback("install failed: " + ex); } } internal static void Verify() { if (verified || !installed) { return; } foreach (var hook2 in hooks) { MethodBase item = hook2.Target; MethodInfo hook = hook2.Hook; Patches patchInfo = Harmony.GetPatchInfo(item); if ((patchInfo?.Prefixes.Concat(patchInfo.Postfixes).Concat(patchInfo.Finalizers).Concat(patchInfo.ILManipulators) .Count((Patch patch) => patch.owner == "DiagLayer.Diagnostics" && patch.PatchMethod == hook) ?? 0) != 1) { Rollback("expected one DiagLayer.Diagnostics hook " + hook.Name + " on " + item.DeclaringType?.Name + "." + item.Name + "."); return; } } foreach (MethodBase target in targets) { if (!built.Contains(target)) { Rollback("target " + target.DeclaringType?.Name + "." + target.Name + " was not rebuilt after patching."); return; } } verified = true; Enabled = true; DiagLog.Info("DiagLayer: APPLIED; chest, crafting, network and error events are recorded, and /dl_mark and /dl_report can send reports to a server that collects them."); } private static void Rollback(string reason) { harmony.UnpatchSelf(); hooks.Clear(); targets.Clear(); built.Clear(); installed = false; verified = false; Enabled = false; DiagLog.Error("DiagLayer: NOT APPLIED; " + reason); } private static MethodInfo Method(Type type, string name, Type returnType, params Type[] parameters) { MethodInfo method = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null); if (method == null || method.ReturnType != returnType || !(from p in method.GetParameters() select p.ParameterType).SequenceEqual(parameters)) { throw new MissingMethodException(type.FullName, name); } return method; } private static void Built(MethodBase original) { built.Add(original); } private static HarmonyMethod? TrackTarget(MethodInfo target) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown built.Remove(target); if (!targets.Add(target)) { return null; } hooks.Add((target, builtMarker)); return new HarmonyMethod(builtMarker); } private static void Prefix(MethodInfo target, string hookName, int priority = 400) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(DiagnosticsPatch), hookName, (Type[])null, (Type[])null); HarmonyMethod val = TrackTarget(target); hooks.Add((target, methodInfo)); harmony.Patch((MethodBase)target, new HarmonyMethod(methodInfo) { priority = priority }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, val); } private static void Postfix(MethodInfo target, string hookName, int priority = 400) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(DiagnosticsPatch), hookName, (Type[])null, (Type[])null); HarmonyMethod val = TrackTarget(target); hooks.Add((target, methodInfo)); harmony.Patch((MethodBase)target, (HarmonyMethod)null, new HarmonyMethod(methodInfo) { priority = priority }, (HarmonyMethod)null, (HarmonyMethod)null, val); } private static void Finalizer(MethodInfo target, string hookName) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(DiagnosticsPatch), hookName, (Type[])null, (Type[])null); HarmonyMethod val = TrackTarget(target); hooks.Add((target, methodInfo)); harmony.Patch((MethodBase)target, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo), val); } private static void TrackContainer(Container __instance) { ContainerTracker.Track(__instance); } private static void ForgetView(ZNetView __instance) { ContainerTracker.Forget(__instance); } private static void ResetContainers() { ContainerTracker.Reset(); } private static void Use(Container __instance, bool __0) { try { if ((!__0 || !__instance.IsInUse()) && ContainerTracker.LiveZdo(__instance) != null) { ChestDiagnostics.Record(__0 ? "open-use" : "close-use", __instance); } } catch (Exception error) { ChestDiagnostics.Fault("SetInUse", error); } } private static void Check(Container __instance) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) try { ZDO val = ContainerTracker.LiveZdo(__instance); if (val == null) { return; } SyncState syncState = new SyncState(val.GetOwner(), val.DataRevision, ContainerTracker.LoadedRevision(__instance), __instance.IsInUse(), val.GetInt(ZDOVars.s_inUse, 0)); if (!states.TryGetValue(val.m_uid, out var value) || !(value == syncState)) { bool num = !states.ContainsKey(val.m_uid); states[val.m_uid] = syncState; if (!num) { ChestDiagnostics.Record("state-change", __instance, Describe(value, syncState)); } } } catch (Exception error) { ChestDiagnostics.Fault("Check", error); } } private static string Describe(SyncState before, SyncState after) { List<string> list = new List<string>(); if (before.Owner != after.Owner) { list.Add("owner " + before.Owner + "->" + after.Owner); } if (before.Data != after.Data) { list.Add("data_revision " + before.Data + "->" + after.Data); } if (before.Loaded != after.Loaded) { list.Add("loaded_revision " + before.Loaded + "->" + after.Loaded); } if (before.Use != after.Use) { list.Add("local_use " + before.Use + "->" + after.Use); } if (before.Replicated != after.Replicated) { list.Add("replicated_use " + before.Replicated + "->" + after.Replicated); } return string.Join(";", list); } private static void Contents(Container chest, string kind) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) ZDOID? val = ContainerTracker.IdOf(chest); if (val.HasValue && ContainerTracker.LiveZdo(chest) != null) { string text = ChestDiagnostics.Items(chest.GetInventory()); if (!contents.TryGetValue(val.Value, out string value) || !(value == text)) { contents[val.Value] = text; ChestDiagnostics.RecordContents(kind, chest, text); } } } private static void Loading(Container __instance, out Container? __state) { __state = loading; loading = __instance; } private static Exception? LoadEnded(Exception? __exception, Container? __state) { loading = __state; return __exception; } private static void Loaded(Container __instance, bool __result) { if (!__result) { return; } try { Contents(__instance, "inventory-refreshed"); } catch (Exception error) { ChestDiagnostics.Fault("Load", error); } } private static void Saving(Container __instance) { try { ZNetView val = ContainerTracker.View(__instance); if (!((Object)(object)val == (Object)null) && val.IsValid() && !val.IsOwner()) { ChestDiagnostics.Record("NON_OWNER_WRITE", __instance, "a peer saved a chest it does not own", Severity.Problem, "stack: " + ChestDiagnostics.Stack(1, 14)); } } catch (Exception error) { ChestDiagnostics.Fault("Saving", error); } } private static void Saved(Container __instance) { try { Contents(__instance, "inventory-saved"); } catch (Exception error) { ChestDiagnostics.Fault("Save", error); } } private static void InventoryChanged(Inventory __instance) { try { ItemLedger.InventoryChanged(__instance); Container val = ContainerTracker.Find(__instance); if (val != null && val != loading) { Contents(val, "inventory-changed"); } } catch (Exception error) { ChestDiagnostics.Fault("Inventory.Changed", error); } } private static void OwnerChanging(ZDO __instance, long __0) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) try { Container val = ContainerTracker.Find(__instance.m_uid); if (val != null && __instance.GetOwner() != __0) { ChestDiagnostics.Record("owner-assignment", val, "from=" + __instance.GetOwner() + ";to=" + __0, Severity.Info, "stack: " + ChestDiagnostics.Stack(1, 10)); } } catch (Exception error) { ChestDiagnostics.Fault("SetOwner", error); } } private static void Received(ZRpc __0, ZPackage __1) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) if (ContainerTracker.Count == 0) { return; } int pos = __1.GetPos(); try { int num = __1.ReadInt(); for (int i = 0; i < num; i++) { __1.ReadZDOID(); } while (true) { ZDOID id = __1.ReadZDOID(); if (!((ZDOID)(ref id)).IsNone()) { ushort num2