Decompiled source of CatLibTests v0.7.5
plugins/CatLib.Tests.dll
Decompiled 2 weeks 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.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Http; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Configuration; using BetterRepair; using BetterRepair.Logic; using BetterRepair.Settings; using BoatTweaks; using BoatTweaks.Logic; using BoatTweaks.Settings; using CatLib.Assets; using CatLib.Config; using CatLib.Core; using CatLib.CrashWatcher.Stacks; using CatLib.CrashWatcher.Symbols; using CatLib.DevTools; using CatLib.Diagnostics; using CatLib.Events; using CatLib.Game; using CatLib.Game.Bridge; using CatLib.Game.Events; using CatLib.Il2Cpp; using CatLib.Localization; using CatLib.Logging; using CatLib.Net; using CatLib.Patching; using CatLib.Saves; using CatLib.Tests.Diagnostics; using CatLib.Tests.Diagnostics.Inspection; using CatLib.Tests.Framework; using CatLib.Tests.Suites.Localization; using CatLib.Tests.Suites.Network; using CatLib.Tests.Suites.Presentation; using CatLib.Tests.Suites.Saves; using CatLib.Tests.Suites.Settings; using CatLib.Tests.Timeline; using CatLib.Threading; using CatLib.UI; using CatLib.Voice; using CustomStamps.Packs; using HarmonyLib; using I2.Loc; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using Il2CppSystem.Reflection; using Microsoft.CodeAnalysis; using ParcelBoard; using ParcelBoard.Logic; using ParcelBoard.Scene; using ParcelBoard.Settings; using Purr; using Purr.Logic; using Purr.Settings; using SemanticVersioning; using ShelfLabels; using ShelfLabels.Data; using ShelfLabels.Logic; using ShelfLabels.Settings; using ShelfLabels.Sync; using StackIt; using StackIt.Logic; using StackIt.Patches; using StackIt.Scene; using StackIt.Settings; using Steamworks; using TMPro; using TooLate; using TooLate.Logic; using TooLate.Patches; using TooLate.Scene; using TooLate.Settings; using UnityEngine; using UnityEngine.Diagnostics; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("CatLib contributors")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.7.5.0")] [assembly: AssemblyInformationalVersion("0.7.5+5afca9e7564e9569248ff23a4a6de0000d21c4e4")] [assembly: AssemblyProduct("CatLib")] [assembly: AssemblyTitle("CatLib.Tests")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.7.5.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [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 CatLib.CrashWatcher { internal sealed class WatcherLog { public const long MaxBytes = 262144L; private static readonly object Gate = new object(); private readonly string _path; public WatcherLog(string path) { _path = path; } public void Write(string message) { try { lock (Gate) { if (File.Exists(_path) && new FileInfo(_path).Length > 262144) { File.Delete(_path); } File.AppendAllText(_path, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + " " + message + Environment.NewLine, Encoding.UTF8); } } catch (IOException) { } catch (UnauthorizedAccessException) { } } } } namespace CatLib.CrashWatcher.Stacks { internal interface IProcessMemory { bool TryRead(ulong address, byte[] buffer, int count); bool IsExecutable(ulong address); } internal static class CrashMemory { public const int StackBytes = 131072; public const int PageSize = 4096; public const int MaxStrings = 8; public const int MaxStringLength = 300; public const int MinStringLength = 3; public const int MaxDeclaredLength = 1048576; public const int DotnetLengthOffset = 8; public const int DotnetCharsOffset = 12; public const int Il2CppLengthOffset = 16; public const int Il2CppCharsOffset = 20; public const string DotnetMark = ".NET"; public const string Il2CppMark = "IL2CPP"; public static List<string> LogLines(IProcessMemory memory, ulong address, int size) { List<string> result = new List<string>(); if (memory == null || address == 0L || size <= 0 || size > 4194304) { return result; } byte[] array = new byte[24]; long num = default(long); int num2 = default(int); if (!memory.TryRead(address, array, array.Length) || !CrashLogRing.TryReadHeader(array, ref num, ref num2) || num2 != size) { return result; } byte[] array2 = new byte[num2]; if (!memory.TryRead(address + 24, array2, num2)) { return result; } return CrashLogRing.Lines(array2, num); } public static List<string> StackStrings(IProcessMemory memory, IList<ulong> registers, ulong stackPointer, ulong dotnetType, ulong il2cppType) { List<string> list = new List<string>(); if (memory == null || (dotnetType == 0L && il2cppType == 0L)) { return list; } HashSet<ulong> seen = new HashSet<ulong>(); HashSet<string> texts = new HashSet<string>(StringComparer.Ordinal); foreach (ulong item in registers ?? new ulong[0]) { Consider(memory, item, dotnetType, il2cppType, seen, texts, list); } byte[] array = new byte[4096]; ulong num = stackPointer & 0xFFFFFFFFFFFFFFF8uL; int num3; for (ulong num2 = num + 131072; num < num2; num += (ulong)num3) { if (list.Count >= 8) { break; } num3 = (int)Math.Min(4096 - (num & 0xFFF), num2 - num); if (!memory.TryRead(num, array, num3)) { break; } for (int i = 0; i + 8 <= num3; i += 8) { if (list.Count >= 8) { break; } Consider(memory, BitConverter.ToUInt64(array, i), dotnetType, il2cppType, seen, texts, list); } } return list; } public static bool IsReadable(string text) { if (string.IsNullOrEmpty(text) || text.Length < 3) { return false; } int num = 0; int num2 = 0; foreach (char c in text) { if (char.IsLetterOrDigit(c)) { num++; } else if (char.IsControl(c) && c != '\n' && c != '\r' && c != '\t') { num2++; } else if (char.IsSurrogate(c) || c == '\ufffd') { num2++; } } if (num2 == 0) { return num * 2 >= text.Length; } return false; } public static string Quote(string mark, string text) { string text2 = (text ?? string.Empty).Replace("\r", "\\r").Replace("\n", "\\n").Replace("\t", " "); return mark + ": \"" + text2 + "\""; } private static void Consider(IProcessMemory memory, ulong value, ulong dotnetType, ulong il2cppType, HashSet<ulong> seen, HashSet<string> texts, List<string> found) { if (found.Count >= 8 || value < 65536 || (value & 1) != 0L || value > 140737488355327L) { return; } if (dotnetType != 0L) { Try(memory, value, dotnetType, 8, 12, ".NET", seen, texts, found); if (value > 12) { Try(memory, value - 12, dotnetType, 8, 12, ".NET", seen, texts, found); } } if (il2cppType != 0L) { Try(memory, value, il2cppType, 16, 20, "IL2CPP", seen, texts, found); if (value > 20) { Try(memory, value - 20, il2cppType, 16, 20, "IL2CPP", seen, texts, found); } } } private static void Try(IProcessMemory memory, ulong objectAddress, ulong type, int lengthOffset, int charsOffset, string mark, HashSet<ulong> seen, HashSet<string> texts, List<string> found) { if (found.Count >= 8 || (objectAddress & 7) != 0L || !seen.Add(objectAddress ^ type)) { return; } byte[] array = new byte[charsOffset]; if (!memory.TryRead(objectAddress, array, array.Length) || BitConverter.ToUInt64(array, 0) != type) { return; } int num = BitConverter.ToInt32(array, lengthOffset); if (num < 3 || num > 1048576) { return; } int num2 = Math.Min(num, 300); byte[] array2 = new byte[num2 * 2]; if (memory.TryRead(objectAddress + (ulong)charsOffset, array2, array2.Length)) { string text = Encoding.Unicode.GetString(array2); if (IsReadable(text) && texts.Add(text)) { found.Add(Quote(mark, (num > num2) ? (text + "...") : text)); } } } } internal sealed class ModuleSet { private readonly List<CrashModule> _modules; public int Count => _modules.Count; public ModuleSet(IEnumerable<CrashModule> modules) { _modules = new List<CrashModule>(modules ?? new List<CrashModule>()); _modules.Sort((CrashModule left, CrashModule right) => left.Start.CompareTo(right.Start)); } public CrashModule Find(ulong address) { int num = 0; int num2 = _modules.Count - 1; while (num <= num2) { int num3 = (num + num2) / 2; CrashModule val = _modules[num3]; if (address < val.Start) { num2 = num3 - 1; continue; } if (address - val.Start >= val.Size) { num = num3 + 1; continue; } return val; } return null; } public CrashModule Named(string fileName) { foreach (CrashModule module in _modules) { if (string.Equals(Path.GetFileName(module.Path), fileName, StringComparison.OrdinalIgnoreCase)) { return module; } } return null; } } internal sealed class RegisterSet { public const int StackPointer = 4; public const int FramePointer = 5; public const int Count = 16; public const int AllStale = 65519; public ulong[] Integer { get; } = new ulong[16]; public ulong Rip { get; set; } public int Stale { get; set; } public ulong Rsp { get { return Integer[4]; } set { Integer[4] = value; } } public bool IsStale(int register) { return (Stale & (1 << register)) != 0; } public void Restore(int register, ulong value) { Integer[register] = value; Stale &= ~(1 << register); } public RegisterSet Copy() { RegisterSet registerSet = new RegisterSet { Rip = Rip, Stale = Stale }; Array.Copy(Integer, registerSet.Integer, 16); return registerSet; } } internal sealed class StackUnwinder { private enum StepResult { Unwound, MachineFrame, NoUnwindData, Failed } public const int MaxFrames = 64; public const int ScanBytes = 32768; public const int ScanPage = 4096; public const int MaxScans = 6; public const int MaxChain = 32; public const uint PastProlog = uint.MaxValue; public const string EndOfStack = "end of the stack"; private const int PushNonvolatile = 0; private const int AllocLarge = 1; private const int AllocSmall = 2; private const int SetFramePointer = 3; private const int SaveNonvolatile = 4; private const int SaveNonvolatileFar = 5; private const int PushMachineFrame = 10; private const int SetFramePointerLarge = 11; private const int LastKnownOperation = 11; private static readonly int[] ExtraSlots = new int[12] { 0, 1, 0, 0, 1, 2, 1, 2, 1, 2, 0, 2 }; private readonly IProcessMemory _memory; private readonly ModuleSet _modules; private readonly CodeNames _names; private readonly byte[] _word = new byte[8]; private bool _doubtful; public string LastStop { get; private set; } = string.Empty; public StackUnwinder(IProcessMemory memory, ModuleSet modules, CodeNames names) { _memory = memory; _modules = modules; _names = names; } public List<UnwoundFrame> Walk(RegisterSet start, int maxFrames = 64) { LastStop = "frame limit"; List<UnwoundFrame> list = new List<UnwoundFrame>(); RegisterSet registers = start.Copy(); RegisterSet beforeScan = null; int scans = 0; bool flag = false; bool flag2 = false; bool flag3 = true; while (list.Count < maxFrames) { if (registers.Rip == 0L && list.Count > 0) { if (!Retry(list, ref registers, beforeScan, ref scans)) { LastStop = "end of the stack"; break; } flag = true; flag3 = false; continue; } bool flag4 = list.Count == 0 && !IsCode(registers.Rip); list.Add(new UnwoundFrame(registers.Rip, registers.Rsp, flag || flag2, flag3, flag4)); bool top = flag3; flag = false; flag2 = false; if (flag4) { if (!Pop(registers)) { LastStop = "unwinding failed"; break; } flag3 = false; continue; } ulong rsp = registers.Rsp; _doubtful = false; StepResult stepResult = Step(registers, top); flag2 = _doubtful; flag3 = stepResult == StepResult.MachineFrame; if (stepResult == StepResult.NoUnwindData) { beforeScan = registers.Copy(); if (scans >= 6 || !Scan(registers, registers.Rsp)) { LastStop = ((scans >= 6) ? "too many searches of the stack" : "no return address found on the stack"); break; } scans++; flag = true; continue; } bool flag5 = registers.Rip != 0L && !IsCode(registers.Rip); if (stepResult == StepResult.Failed || flag5 || (stepResult == StepResult.Unwound && registers.Rsp <= rsp)) { if (!Retry(list, ref registers, beforeScan, ref scans)) { LastStop = ((stepResult == StepResult.Failed) ? "unwinding failed" : (flag5 ? "the next address is not code" : "the stack pointer went back")); break; } flag = true; flag3 = false; } } return list; } public static bool FollowsCall(byte[] b) { if (b[2] != 232 && (b[1] != byte.MaxValue || b[2] != 21) && (b[5] != byte.MaxValue || (b[6] & 0xF8) != 208) && (b[5] != byte.MaxValue || (b[6] & 0xF8) != 16 || (b[6] & 7) == 4 || (b[6] & 7) == 5) && (b[4] != byte.MaxValue || b[5] != 20) && (b[4] != byte.MaxValue || (b[5] & 0xF8) != 80 || (b[5] & 7) == 4) && (b[3] != byte.MaxValue || b[4] != 84) && (b[1] != byte.MaxValue || (b[2] & 0xF8) != 144 || (b[2] & 7) == 4)) { if (b[0] == byte.MaxValue) { return b[1] == 148; } return false; } return true; } private bool Retry(List<UnwoundFrame> frames, ref RegisterSet registers, RegisterSet beforeScan, ref int scans) { if (frames.Count == 0 || !frames[frames.Count - 1].Scanned || beforeScan == null || scans >= 6) { return false; } UnwoundFrame unwoundFrame = frames[frames.Count - 1]; RegisterSet registerSet = beforeScan.Copy(); scans++; if (!Scan(registerSet, unwoundFrame.StackPointer)) { return false; } frames.RemoveAt(frames.Count - 1); registers = registerSet; return true; } private bool IsCode(ulong address) { CrashModule val = _modules.Find(address); if (val == null) { return _memory.IsExecutable(address); } return _names.Image(val.Path)?.IsExecutable((uint)(address - val.Start)) ?? true; } private StepResult Step(RegisterSet registers, bool top) { CrashModule val = _modules.Find(registers.Rip); PeImage peImage = ((val == null) ? null : _names.Image(val.Path)); if (peImage == null || !peImage.IsAmd64) { return StepResult.NoUnwindData; } uint num = (uint)(registers.Rip - val.Start); if (!peImage.TryFindFunction(top ? num : (num - 1), out var function)) { if (!Pop(registers)) { return StepResult.Failed; } return StepResult.Unwound; } return Unwind(peImage, num, function, registers, top); } private StepResult Unwind(PeImage image, uint rva, RuntimeFunction function, RegisterSet registers, bool top) { UnwindInfo unwindInfo = UnwindInfo.Read(image, function.UnwindInfo); if (unwindInfo == null) { return StepResult.Failed; } uint num = ((rva >= function.Begin && rva - function.Begin < unwindInfo.PrologSize) ? (rva - function.Begin) : uint.MaxValue); if (top && num == uint.MaxValue && TryEpilog(image, rva, function, unwindInfo.FrameRegister, registers)) { return StepResult.Unwound; } ulong num2 = EstablisherFrame(unwindInfo, num, registers); bool flag = false; UnwindInfo unwindInfo2 = unwindInfo; bool flag2 = true; for (int i = 0; i < 32; i++) { byte[] codes = unwindInfo2.Codes; int num3 = 0; while (num3 < unwindInfo2.CodeCount) { byte b = codes[num3 * 2]; int num4 = codes[num3 * 2 + 1] & 0xF; int num5 = codes[num3 * 2 + 1] >> 4; if (num4 > 11) { return StepResult.Failed; } int num6 = Slots(num4, num5); if (num3 + num6 > unwindInfo2.CodeCount) { return StepResult.Failed; } if (flag2 && num != uint.MaxValue && b > num) { num3 += num6; continue; } switch (num4) { case 0: { if (!ReadWord(registers.Rsp, out var value4)) { return StepResult.Failed; } registers.Restore(num5, value4); registers.Rsp += 8uL; break; } case 1: registers.Rsp += ((num5 == 0) ? (Slot16(codes, num3 + 1) * 8) : Slot32(codes, num3 + 1)); break; case 2: registers.Rsp += (ulong)((long)(num5 + 1) * 8L); break; case 3: case 11: { if (registers.IsStale(unwindInfo2.FrameRegister)) { _doubtful = true; } ulong num7 = ((num4 == 3) ? ((ulong)unwindInfo2.FrameOffset) : Slot32(codes, num3 + 1)); registers.Rsp = registers.Integer[unwindInfo2.FrameRegister] - num7 * 16; break; } case 4: case 5: { ulong address = num2 + ((num4 == 4) ? (Slot16(codes, num3 + 1) * 8) : Slot32(codes, num3 + 1)); if (!ReadWord(address, out var value3)) { return StepResult.Failed; } registers.Restore(num5, value3); break; } case 10: { if (num5 != 0) { registers.Rsp += 8uL; } if (!ReadWord(registers.Rsp, out var value) || !ReadWord(registers.Rsp + 24, out var value2)) { return StepResult.Failed; } registers.Rip = value; registers.Rsp = value2; flag = true; break; } } num3 += num6; } if (!unwindInfo2.Chained) { break; } RuntimeFunction runtimeFunction = image.ReadChained(unwindInfo2.Address, unwindInfo2.CodeCount); unwindInfo2 = ((runtimeFunction.UnwindInfo == 0) ? null : UnwindInfo.Read(image, runtimeFunction.UnwindInfo)); if (unwindInfo2 == null) { return StepResult.Failed; } flag2 = false; } if (flag) { return StepResult.MachineFrame; } if (!Pop(registers)) { return StepResult.Failed; } return StepResult.Unwound; } private ulong EstablisherFrame(UnwindInfo info, uint prologOffset, RegisterSet registers) { if (info.FrameRegister == 0) { return registers.Rsp; } bool flag = prologOffset == uint.MaxValue || info.Chained; if (!flag) { int num; for (int i = 0; i < info.CodeCount; i += Slots(num, info.Codes[i * 2 + 1] >> 4)) { num = info.Codes[i * 2 + 1] & 0xF; if (num == 3) { flag = prologOffset >= info.Codes[i * 2]; break; } if (num > 11) { break; } } } if (!flag) { return registers.Rsp; } if (registers.IsStale(info.FrameRegister)) { _doubtful = true; } return registers.Integer[info.FrameRegister] - (ulong)((long)info.FrameOffset * 16L); } private bool TryEpilog(PeImage image, uint rva, RuntimeFunction function, int frameRegister, RegisterSet registers) { byte[] array = image.Read(rva, 32); if (array == null) { return false; } int i = 0; long num = 0L; int num2 = -1; if (array[0] == 72 && array[1] == 131 && array[2] == 196) { num = (sbyte)array[3]; i = 4; } else if (array[0] == 72 && array[1] == 129 && array[2] == 196) { num = BitConverter.ToInt32(array, 3); i = 7; } else if ((array[0] & 0xFE) == 72 && array[1] == 141 && (array[2] & 0x38) == 32 && (array[2] & 0xC0) != 192) { int num3 = array[2] >> 6; int num4 = (array[2] & 7) + (((array[0] & 1) != 0) ? 8 : 0); if ((array[2] & 7) == 4 || num3 == 0 || frameRegister == 0 || num4 != frameRegister) { return false; } num = ((num3 == 1) ? ((sbyte)array[3]) : BitConverter.ToInt32(array, 3)); num2 = num4; i = ((num3 == 1) ? 4 : 7); } List<int> list = new List<int>(); for (; i < array.Length - 7; i++) { int num5 = 0; if ((array[i] & 0xF0) == 64) { num5 = array[i]; i++; } byte b = array[i]; if ((num5 & 8) == 0 && b >= 88 && b <= 95) { list.Add(b - 88 + (((num5 & 1) != 0) ? 8 : 0)); continue; } if (b == 242 && num5 == 0) { i++; b = array[i]; } bool flag; switch (b) { case 194: case 195: flag = true; break; case 243: flag = array[i + 1] == 195; break; case 233: flag = LeavesFunction(rva + i + 5 + BitConverter.ToInt32(array, i + 1), function); break; case 235: flag = LeavesFunction(rva + i + 2 + (sbyte)array[i + 1], function); break; case byte.MaxValue: flag = (num5 == 0 && array[i + 1] == 37) || ((num5 & 8) != 0 && ((array[i + 1] >> 3) & 7) == 4); break; default: flag = false; break; } if (!flag) { return false; } ulong num6 = ((num2 >= 0) ? (registers.Integer[num2] + (ulong)num) : (registers.Rsp + (ulong)num)); ulong[] array2 = new ulong[list.Count]; for (int j = 0; j < list.Count; j++) { if (!ReadWord(num6, out array2[j])) { return false; } num6 += 8; } if (!ReadWord(num6, out var value)) { return false; } for (int k = 0; k < list.Count; k++) { registers.Restore(list[k], array2[k]); } registers.Rip = value; registers.Rsp = num6 + 8; return true; } return false; } private static bool LeavesFunction(long target, RuntimeFunction function) { if (target >= function.Begin && target < function.End) { return target == function.Begin; } return true; } private bool Scan(RegisterSet registers, ulong from) { byte[] array = new byte[4096]; ulong num = from & 0xFFFFFFFFFFFFFFF8uL; int num3; for (ulong num2 = num + 32768; num < num2; num += (ulong)num3) { num3 = ReadSome(num, array); if (num3 == 0) { return false; } for (int i = 0; i + 8 <= num3; i += 8) { ulong num4 = BitConverter.ToUInt64(array, i); if (LooksLikeReturnAddress(num4)) { registers.Rip = num4; registers.Rsp = (ulong)((long)num + (long)i + 8); registers.Stale = 65519; return true; } } } return false; } private int ReadSome(ulong address, byte[] buffer) { for (int num = 4096 - (int)(address & 0xFFF); num >= 8; num /= 2) { if (_memory.TryRead(address, buffer, num & -8)) { return num & -8; } } return 0; } private bool LooksLikeReturnAddress(ulong value) { CrashModule val = _modules.Find(value); if (val == null || value - val.Start < 8) { return false; } PeImage peImage = _names.Image(val.Path); uint num = (uint)(value - val.Start); if (peImage == null || !peImage.IsExecutable(num - 1)) { return false; } byte[] array = peImage.Read(num - 7, 7); if (array != null) { return FollowsCall(array); } return false; } private bool Pop(RegisterSet registers) { if (!ReadWord(registers.Rsp, out var value)) { return false; } registers.Rip = value; registers.Rsp += 8uL; return true; } private bool ReadWord(ulong address, out ulong value) { value = 0uL; if (!_memory.TryRead(address, _word, 8)) { return false; } value = BitConverter.ToUInt64(_word, 0); return true; } private static int Slots(int operation, int operationInfo) { int num = ExtraSlots[Math.Min(operation, 11)] + 1; if (operation == 1 && operationInfo != 0) { num++; } return num; } private static ulong Slot16(byte[] codes, int index) { return BitConverter.ToUInt16(codes, index * 2); } private static ulong Slot32(byte[] codes, int index) { return BitConverter.ToUInt32(codes, index * 2); } } internal sealed class UnwindInfo { public const byte ChainFlag = 4; public uint Address { get; private set; } public int Version { get; private set; } public bool Chained { get; private set; } public int PrologSize { get; private set; } public int CodeCount { get; private set; } public int FrameRegister { get; private set; } public int FrameOffset { get; private set; } public byte[] Codes { get; private set; } private UnwindInfo() { } public static UnwindInfo Read(PeImage image, uint rva) { byte[] array = image.Read(rva, 4); if (array == null) { return null; } int num = array[0] & 7; if (num != 1 && num != 2) { return null; } byte b = array[2]; byte[] array2 = ((b == 0) ? new byte[0] : image.Read(rva + 4, b * 2)); if (array2 == null) { return null; } return new UnwindInfo { Address = rva, Version = num, Chained = (((array[0] >> 3) & 4) != 0), PrologSize = array[1], CodeCount = b, FrameRegister = (array[3] & 0xF), FrameOffset = array[3] >> 4, Codes = array2 }; } } internal sealed class UnwoundFrame { public ulong Address { get; } public ulong StackPointer { get; } public bool Scanned { get; } public bool Interrupted { get; } public bool NotCode { get; } public UnwoundFrame(ulong address, ulong stackPointer, bool scanned, bool interrupted, bool notCode = false) { NotCode = notCode; Address = address; StackPointer = stackPointer; Scanned = scanned; Interrupted = interrupted; } } } namespace CatLib.CrashWatcher.Symbols { internal sealed class CodeNames : IDisposable { public const string GameAssemblyName = "GameAssembly.dll"; public const string RuntimeName = "IL2CPP runtime"; public const string GeneratedName = "IL2CPP code that is not a game method"; public const uint MaxLeafSize = 1024u; public const int CheckedSamples = 256; public const double RequiredMatch = 0.95; public const double RequiredStarts = 0.5; public const double RequiredAgreement = 0.8; public const string InteropPlaceholderPrefix = "Method_"; private readonly object _gate = new object(); private readonly Dictionary<string, PeImage> _images = new Dictionary<string, PeImage>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, PdbPublics> _pdbs = new Dictionary<string, PdbPublics>(StringComparer.OrdinalIgnoreCase); private readonly string _interopDirectory; private readonly SymbolStore _symbols; private readonly WatcherLog _log; private GameMethodMap _map; private bool _mapTried; private Il2CppCodeNames _il2cpp; private bool _il2cppTried; public Func<string, string> Undecorate { get; set; } = Readable; public bool HasGameMethods { get { if (_map == null) { return _il2cpp != null; } return true; } } public CodeNames(string interopDirectory, WatcherLog log, SymbolStore symbols = null) { _interopDirectory = interopDirectory; _symbols = symbols; _log = log; } public static string Offset(ulong value) { return "0x" + value.ToString("x", CultureInfo.InvariantCulture); } public PeImage Image(string path) { if (string.IsNullOrEmpty(path)) { return null; } lock (_gate) { if (!_images.TryGetValue(path, out var value)) { try { value = PeImage.Open(path); } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { _log?.Write("Could not read " + path + " for method names: " + ex.Message); value = null; } _images[path] = value; } return value; } } public void WaitForSymbols(TimeSpan timeout) { _symbols?.WaitIdle(timeout); } public string Name(string modulePath, ulong offset, bool returnAddress = false) { bool gameMethod; return Name(modulePath, offset, returnAddress, out gameMethod); } public string Name(string modulePath, ulong offset, bool returnAddress, out bool gameMethod) { gameMethod = false; if (offset > uint.MaxValue) { return null; } PeImage peImage = Image(modulePath); if (peImage == null) { return null; } try { lock (_gate) { return IsGameAssembly(modulePath) ? NameInGameAssembly(peImage, (uint)offset, returnAddress, out gameMethod) : ModuleName(peImage, (uint)offset, returnAddress); } } catch (Exception ex) { _log?.Write($"Could not name {Path.GetFileName(modulePath)} + {Offset(offset)}: {ex.Message}"); return null; } } public void Dispose() { lock (_gate) { foreach (PeImage value in _images.Values) { value?.Dispose(); } _images.Clear(); } } public static string Readable(string export) { if (string.IsNullOrEmpty(export) || export[0] != '?' || export.Length < 2 || export[1] == '?' || export[1] == '$') { return export; } int num = export.IndexOf("@@", StringComparison.Ordinal); if (num < 0) { return export; } string[] array = export.Substring(1, num - 1).Split('@'); Array.Reverse(array); return string.Join("::", array); } public static bool IsGameAssembly(string modulePath) { return string.Equals(Path.GetFileName(modulePath ?? string.Empty), "GameAssembly.dll", StringComparison.OrdinalIgnoreCase); } private string NameInGameAssembly(PeImage image, uint rva, bool returnAddress, out bool gameMethod) { gameMethod = true; uint num = ((returnAddress && rva != 0) ? (rva - 1) : rva); RuntimeFunction function; bool flag = image.TryFindFunction(num, out function); uint num2 = (flag ? image.PrimaryStart(function) : 0u); GameMethodMap gameMethodMap = Map(image); Il2CppCodeNames il2CppCodeNames = Il2Cpp(image); if (flag) { int sharedWith = 0; string name = gameMethodMap?.NameAt(num2, out sharedWith); if (name == null && il2CppCodeNames != null) { name = il2CppCodeNames.GenericNameAt(num2, out sharedWith); } if (name == null && gameMethodMap == null && il2CppCodeNames != null) { name = il2CppCodeNames.MethodNameAt(num2); } if (name != null) { string text = InteropAlias(ref name, il2CppCodeNames, num2); return Format(name, rva - num2, sharedWith) + text; } } else { if (gameMethodMap != null && gameMethodMap.TryFloor(num, out var start) && IsLeaf(image, start, num)) { int sharedWith2; string name2 = gameMethodMap.NameAt(start, out sharedWith2); if (name2 != null) { string text2 = InteropAlias(ref name2, il2CppCodeNames, start); return Format(name2, rva - start, sharedWith2) + text2; } } if (il2CppCodeNames != null && il2CppCodeNames.TryFloorGeneric(num, out start) && IsLeaf(image, start, num)) { int sharedWith3; string text3 = il2CppCodeNames.GenericNameAt(start, out sharedWith3); if (text3 != null) { return Format(text3, rva - start, sharedWith3); } } if (gameMethodMap == null && il2CppCodeNames != null && il2CppCodeNames.TryFloorMethod(num, out start) && IsLeaf(image, start, num)) { string text4 = il2CppCodeNames.MethodNameAt(start); if (text4 != null) { return Format(text4, rva - start, 0); } } } gameMethod = false; string text5 = ExportName(image, rva, num, flag, num2); if (text5 != null) { return text5; } string text6 = (flag ? (", in the function at " + Offset(num2)) : string.Empty); string text7 = image.SectionName(num); if (!(text7 == ".text")) { if (text7 == "il2cpp") { return "IL2CPP code that is not a game method, such as a generic method" + text6; } return null; } return "IL2CPP runtime" + text6; } private string ModuleName(PeImage image, uint rva, bool returnAddress) { uint num = ((returnAddress && rva != 0) ? (rva - 1) : rva); RuntimeFunction function; bool flag = image.TryFindFunction(num, out function); uint num2 = (flag ? image.PrimaryStart(function) : 0u); PdbPublics pdbPublics = Pdb(image); if (pdbPublics != null) { uint start; string name; if (flag) { string text = pdbPublics.NameAt(num2); if (text != null) { return Undecorate(text) + " + " + Offset(rva - num2); } } else if (pdbPublics.TryFloor(num, out start, out name) && IsLeaf(image, start, num)) { return Undecorate(name) + " + " + Offset(rva - start); } } return ExportName(image, rva, num, flag, num2); } private static bool IsLeaf(PeImage image, uint start, uint lookup) { if (lookup - start < 1024) { return !image.HasFunctionStartBetween(start, lookup); } return false; } private string ExportName(PeImage image, uint rva, uint lookup, bool inFunction, uint start) { if (!image.TryFindExport(lookup, out var name, out var start2)) { return null; } if (inFunction && start2 == start) { return Undecorate(name) + " + " + Offset(rva - start); } if (!inFunction && IsLeaf(image, start2, lookup)) { return Undecorate(name) + " + " + Offset(rva - start2); } return null; } private static string Format(string name, uint offset, int shared) { return name + " + " + Offset(offset) + ((shared <= 0) ? string.Empty : ((shared == 1) ? ", 1 more method has the same code" : $", {shared} more methods have the same code")); } private PdbPublics Pdb(PeImage image) { if (_pdbs.TryGetValue(image.Path, out var value)) { return value; } PdbPublics pdbPublics = null; if (image.TryGetCodeView(out var pdbName, out var key)) { foreach (string item in PdbCandidates(image.Path, pdbName, key)) { pdbPublics = PdbPublics.Read(item, image, key, out var problem); if (pdbPublics != null) { _log?.Write($"Names of {Path.GetFileName(image.Path)} come from {item}, {pdbPublics.Count} public symbols"); break; } _log?.Write("Symbols " + item + " are not used: " + problem); } } _pdbs[image.Path] = pdbPublics; return pdbPublics; } private IEnumerable<string> PdbCandidates(string modulePath, string pdbName, string key) { string path = Path.GetDirectoryName(modulePath) ?? string.Empty; string beside = Path.Combine(path, pdbName); if (File.Exists(beside)) { yield return beside; } string text = Path.ChangeExtension(modulePath, ".pdb"); if (!string.Equals(text, beside, StringComparison.OrdinalIgnoreCase) && File.Exists(text)) { yield return text; } string text2 = _symbols?.CachedPath(pdbName, key); if (text2 != null) { yield return text2; } } private Il2CppCodeNames Il2Cpp(PeImage gameAssembly) { if (_il2cppTried) { return _il2cpp; } _il2cppTried = true; string metadataPath = Il2CppCodeNames.FindMetadata(gameAssembly.Path); Stopwatch stopwatch = Stopwatch.StartNew(); string problem; Il2CppCodeNames il2CppCodeNames = Il2CppCodeNames.Open(gameAssembly, metadataPath, out problem); if (il2CppCodeNames == null) { _log?.Write("Generic method names are not available: " + (problem ?? "global-metadata.dat was not found")); return null; } GameMethodMap gameMethodMap = Map(gameAssembly); if (gameMethodMap != null) { int num = 0; int num2 = 0; int num3 = Math.Max(1, gameMethodMap.Count / 256); for (int i = 0; i < gameMethodMap.Count; i += num3) { uint rva = gameMethodMap.Sample(i); int sharedWith; string text = gameMethodMap.NameAt(rva, out sharedWith); string text2 = il2CppCodeNames.MethodNameAt(rva); if (text != null && text2 != null && sharedWith <= 0) { num++; num2 += (SameMethod(text, text2) ? 1 : 0); } } if (num == 0 || (double)num2 < (double)num * 0.8) { _log?.Write($"Generic method names are not used: the IL2CPP metadata agrees with the BepInEx method map for {num2} of {num} methods"); return null; } _log?.Write($"IL2CPP metadata version {il2CppCodeNames.Version} read in {stopwatch.ElapsedMilliseconds} ms: {il2CppCodeNames.GenericMethodCount} generic method addresses, {il2CppCodeNames.MethodCount} methods, {num2} of {num} checked methods agree with the BepInEx method map"); } else { _log?.Write($"IL2CPP metadata version {il2CppCodeNames.Version} read in {stopwatch.ElapsedMilliseconds} ms: {il2CppCodeNames.GenericMethodCount} generic method addresses, {il2CppCodeNames.MethodCount} methods"); } _il2cpp = il2CppCodeNames; return il2CppCodeNames; } public static bool SameMethod(string known, string read) { string text = Signature(known); string text2 = Signature(read); if (text.Length == 0 || text2.Length == 0) { return false; } if (string.Equals(Letters(text), Letters(text2), StringComparison.Ordinal)) { return true; } if (IsInteropPlaceholder(known)) { return string.Equals(Letters(DeclaringType(text)), Letters(DeclaringType(text2)), StringComparison.Ordinal); } return false; } public static bool IsInteropPlaceholder(string name) { string text = Signature(name); string text2 = text.Substring(text.LastIndexOf('.') + 1); int num = text2.LastIndexOf('_'); if (!text2.StartsWith("Method_", StringComparison.Ordinal) || num < 0 || num == text2.Length - 1) { return false; } for (int i = num + 1; i < text2.Length; i++) { if (!char.IsDigit(text2[i])) { return false; } } return true; } private static string InteropAlias(ref string name, Il2CppCodeNames il2cpp, uint start) { if (il2cpp == null || !IsInteropPlaceholder(name)) { return string.Empty; } string text = il2cpp.MethodNameAt(start); if (text == null || !SameMethod(name, text)) { return string.Empty; } string text2 = Signature(name); string text3 = text2.Substring(text2.LastIndexOf('.') + 1); name = text; return ", " + text3 + " in the interop assemblies"; } private static string Signature(string name) { int num = name?.IndexOf('(') ?? (-1); string text; if (num <= 0) { text = name; if (text == null) { return string.Empty; } } else { text = name.Substring(0, num); } return text; } private static string DeclaringType(string signature) { int num = signature.LastIndexOf('.'); if (num <= 0) { return string.Empty; } return signature.Substring(0, num); } private static string Letters(string text) { StringBuilder stringBuilder = new StringBuilder(text.Length); foreach (char c in text) { if (char.IsLetterOrDigit(c)) { stringBuilder.Append(c); } } return stringBuilder.ToString(); } private GameMethodMap Map(PeImage gameAssembly) { if (_mapTried) { return _map; } _mapTried = true; string problem; GameMethodMap gameMethodMap = GameMethodMap.Open(_interopDirectory, out problem); if (gameMethodMap == null) { _log?.Write("Game method names are not available: " + problem); return null; } int num = 0; int num2 = 0; int num3 = 0; int num4 = Math.Max(1, gameMethodMap.Count / 256); for (int i = 0; i < gameMethodMap.Count; i += num4) { uint num5 = gameMethodMap.Sample(i); num++; if (gameAssembly.TryFindFunction(num5, out var function)) { num2 += ((function.Begin == num5) ? 1 : 0); } else if (gameAssembly.IsExecutable(num5)) { num3++; } } int num6 = num2 + num3; if (num == 0 || (double)num6 < (double)num * 0.95 || (double)num2 < (double)num * 0.5) { _log?.Write($"Game method names are not used: only {num6} of {num} checked addresses of the BepInEx method map start a function in {gameAssembly.Path}, the map is for another game build"); return null; } _log?.Write($"Game method names come from {Path.Combine(_interopDirectory, "MethodAddressToToken.db")}, {gameMethodMap.Count} methods"); _map = gameMethodMap; return gameMethodMap; } } internal sealed class GameMethodMap { public const string FileName = "MethodAddressToToken.db"; public const uint Magic = 1297370453u; public const int SupportedVersion = 1; private readonly string _directory; private readonly Dictionary<int, ManagedMetadata> _metadata = new Dictionary<int, ManagedMetadata>(); private long[] _rvas; private int[] _tokens; private int[] _assemblyIndexes; private string[] _assemblies; public int Count => _rvas.Length; private GameMethodMap(string directory) { _directory = directory; } public static GameMethodMap Open(string interopDirectory, out string problem) { problem = null; string text = Path.Combine(interopDirectory ?? string.Empty, "MethodAddressToToken.db"); if (!File.Exists(text)) { problem = text + " is missing"; return null; } try { GameMethodMap gameMethodMap = new GameMethodMap(interopDirectory); problem = gameMethodMap.Load(File.ReadAllBytes(text)); return (problem == null) ? gameMethodMap : null; } catch (Exception ex) { problem = text + " could not be read: " + ex.Message; return null; } } public bool TryFloor(uint rva, out uint start) { start = 0u; int num = Floor(rva); if (num < 0) { return false; } start = (uint)_rvas[num]; return true; } public bool Contains(uint rva) { int num = Floor(rva); if (num >= 0) { return _rvas[num] == rva; } return false; } public uint Sample(int index) { return (uint)_rvas[index]; } public string NameAt(uint rva, out int sharedWith) { sharedWith = 0; int num = Floor(rva); if (num < 0 || _rvas[num] != rva) { return null; } int num2 = num; while (num2 > 0 && _rvas[num2 - 1] == rva) { num2--; } for (int i = num2; i <= num; i++) { string text = Resolve(_tokens[i], _assemblyIndexes[i]); if (!string.IsNullOrEmpty(text)) { sharedWith = num - num2; return text; } } return null; } private int Floor(uint rva) { int i = Array.BinarySearch(_rvas, rva); if (i >= 0) { for (; i + 1 < _rvas.Length && _rvas[i + 1] == rva; i++) { } return i; } return ~i - 1; } private string Load(byte[] bytes) { using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes), Encoding.UTF8)) { if (binaryReader.ReadUInt32() != 1297370453) { return "the method map has an unknown format"; } int num = binaryReader.ReadInt32(); if (num != 1) { return $"the method map has version {num}, this crash watcher reads version {1}"; } int num2 = binaryReader.ReadInt32(); int num3 = binaryReader.ReadInt32(); int num4 = binaryReader.ReadInt32(); if (num2 < 0 || num2 > bytes.Length || num3 < 0 || num4 < 0 || num4 + (long)num3 * 16L > bytes.Length) { return "the method map is damaged"; } _assemblies = new string[num2]; for (int i = 0; i < num2; i++) { _assemblies[i] = binaryReader.ReadString(); } binaryReader.BaseStream.Position = num4; _rvas = new long[num3]; for (int j = 0; j < num3; j++) { _rvas[j] = binaryReader.ReadInt64(); } _tokens = new int[num3]; _assemblyIndexes = new int[num3]; for (int k = 0; k < num3; k++) { _tokens[k] = binaryReader.ReadInt32(); _assemblyIndexes[k] = binaryReader.ReadInt32(); } } for (int l = 1; l < _rvas.Length; l++) { if (_rvas[l] < _rvas[l - 1]) { int[] array = new int[_rvas.Length]; for (int m = 0; m < array.Length; m++) { array[m] = m; } Array.Sort((long[])_rvas.Clone(), array); long[] array2 = new long[array.Length]; int[] array3 = new int[array.Length]; int[] array4 = new int[array.Length]; for (int n = 0; n < array.Length; n++) { array2[n] = _rvas[array[n]]; array3[n] = _tokens[array[n]]; array4[n] = _assemblyIndexes[array[n]]; } _rvas = array2; _tokens = array3; _assemblyIndexes = array4; break; } } return null; } private string Resolve(int token, int assembly) { if (assembly < 0 || assembly >= _assemblies.Length) { return null; } if (!_metadata.TryGetValue(assembly, out var value)) { value = LoadAssembly(_assemblies[assembly]); _metadata[assembly] = value; } return value?.MethodName(token); } private ManagedMetadata LoadAssembly(string fullName) { try { return ReadAssembly(fullName); } catch (Exception) { return null; } } private ManagedMetadata ReadAssembly(string fullName) { string text = fullName.Split(',')[0].Trim(); string path = Path.Combine(_directory, text + ".dll"); if (!File.Exists(path)) { path = null; string[] files = Directory.GetFiles(_directory, "*.dll"); foreach (string text2 in files) { if (Path.GetFileNameWithoutExtension(text2).EndsWith(text, StringComparison.OrdinalIgnoreCase)) { path = text2; break; } } } using PeImage peImage = PeImage.Open(path); return (peImage == null) ? null : ManagedMetadata.Read(peImage.ReadClrMetadata()); } } internal sealed class Il2CppCodeNames { private sealed class GenericContext { public List<ulong> ClassArguments { get; } public List<ulong> MethodArguments { get; } public GenericContext(List<ulong> classArguments, List<ulong> methodArguments) { ClassArguments = classArguments; MethodArguments = methodArguments; } } public const string AnchorModule = "mscorlib.dll"; public const int CodeRegistrationSize = 136; public const int MetadataRegistrationTypeSizesOffset = 96; public const int MaxBacktrack = 400; public const ulong CountLimit = 786432uL; public const int MaxDepth = 12; public const string FullySharedPrefix = "__Il2CppFullySharedGeneric"; private const int Void = 1; private const int Pointer = 15; private const int ValueType = 17; private const int Class = 18; private const int Var = 19; private const int Array = 20; private const int GenericInstance = 21; private const int SingleArray = 29; private const int MethodVar = 30; private static readonly Dictionary<int, string> Primitives = new Dictionary<int, string> { [1] = "void", [2] = "bool", [3] = "char", [4] = "sbyte", [5] = "byte", [6] = "short", [7] = "ushort", [8] = "int", [9] = "uint", [10] = "long", [11] = "ulong", [12] = "float", [13] = "double", [14] = "string", [22] = "TypedReference", [24] = "IntPtr", [25] = "UIntPtr", [27] = "fnptr", [28] = "object" }; private readonly PeImage _image; private readonly Il2CppMetadataFile _metadata; private readonly List<KeyValuePair<uint, byte[]>> _data = new List<KeyValuePair<uint, byte[]>>(); private readonly Dictionary<uint, int> _genericByRva = new Dictionary<uint, int>(); private readonly Dictionary<uint, int> _genericShared = new Dictionary<uint, int>(); private readonly Dictionary<uint, int> _methodByRva = new Dictionary<uint, int>(); private uint[] _genericStarts = new uint[0]; private uint[] _methodStarts = new uint[0]; private ulong[] _types; private ulong[] _genericInsts; private byte[] _methodSpecs; private readonly Dictionary<int, string> _typeNames = new Dictionary<int, string>(); private readonly Dictionary<int, bool> _fullyShared = new Dictionary<int, bool>(); public ulong CodeRegistration { get; private set; } public ulong MetadataRegistration { get; private set; } public int Version => _metadata.Version; public int GenericMethodCount => _genericByRva.Count; public int MethodCount => _methodByRva.Count; private Il2CppCodeNames(PeImage image, Il2CppMetadataFile metadata) { _image = image; _metadata = metadata; } public static string FindMetadata(string gameAssemblyPath) { string directoryName = Path.GetDirectoryName(gameAssemblyPath ?? string.Empty); if (string.IsNullOrEmpty(directoryName) || !Directory.Exists(directoryName)) { return null; } string[] directories = Directory.GetDirectories(directoryName, "*_Data"); for (int i = 0; i < directories.Length; i++) { string text = Path.Combine(directories[i], "il2cpp_data", "Metadata", "global-metadata.dat"); if (File.Exists(text)) { return text; } } return null; } public static Il2CppCodeNames Open(PeImage gameAssembly, string metadataPath, out string problem) { Il2CppMetadataFile il2CppMetadataFile = Il2CppMetadataFile.Open(metadataPath, out problem); if (il2CppMetadataFile == null) { return null; } if (!gameAssembly.IsAmd64) { problem = "GameAssembly.dll is not a 64-bit image"; return null; } Il2CppCodeNames il2CppCodeNames = new Il2CppCodeNames(gameAssembly, il2CppMetadataFile); problem = il2CppCodeNames.Load(); if (problem != null) { return null; } return il2CppCodeNames; } public string GenericNameAt(uint rva, out int sharedWith) { sharedWith = 0; if (!_genericByRva.TryGetValue(rva, out var value)) { return null; } _genericShared.TryGetValue(rva, out sharedWith); return MethodSpecName(value); } public string MethodNameAt(uint rva) { if (!_methodByRva.TryGetValue(rva, out var value)) { return null; } return MethodName(value, null, null); } public bool TryFloorGeneric(uint rva, out uint start) { return Floor(_genericStarts, rva, out start); } public bool TryFloorMethod(uint rva, out uint start) { return Floor(_methodStarts, rva, out start); } private static bool Floor(uint[] starts, uint rva, out uint start) { start = 0u; int num = System.Array.BinarySearch(starts, rva); if (num < 0) { num = ~num - 1; } if (num < 0) { return false; } start = starts[num]; return true; } private string Load() { foreach (PeSection section in _image.Sections) { if (!section.IsExecutable && section.RawSize != 0) { byte[] array = _image.Read(section.VirtualAddress, (int)Math.Min(section.RawSize, (section.VirtualSize == 0) ? section.RawSize : section.VirtualSize)); if (array != null) { _data.Add(new KeyValuePair<uint, byte[]>(section.VirtualAddress, array)); } } } CodeRegistration = FindCodeRegistration(); if (CodeRegistration == 0L) { return "the code registration of IL2CPP was not found in GameAssembly.dll"; } MetadataRegistration = FindMetadataRegistration(); if (MetadataRegistration == 0L) { return "the metadata registration of IL2CPP was not found in GameAssembly.dll"; } ulong[] array2 = ReadWords(MetadataRegistration + 48, 2); ulong[] array3 = ReadWords(MetadataRegistration + 16, 2); ulong[] array4 = ReadWords(MetadataRegistration + 64, 2); ulong[] array5 = ReadWords(MetadataRegistration + 32, 2); ulong[] array6 = ReadWords(CodeRegistration + 16, 2); if (array2 == null || array3 == null || array4 == null || array5 == null || array6 == null) { return "the IL2CPP registrations could not be read"; } _types = ReadWords(array2[1], (int)Math.Min(array2[0], 3145728uL)); _genericInsts = ReadWords(array3[1], (int)Math.Min(array3[0], 3145728uL)); _methodSpecs = _image.ReadVirtual(array4[1], (int)Math.Min(array4[0], 3145728uL) * 12); byte[] array7 = _image.ReadVirtual(array5[1], (int)Math.Min(array5[0], 3145728uL) * 16); ulong[] array8 = ReadWords(array6[1], (int)Math.Min(array6[0], 3145728uL)); if (_types == null || _genericInsts == null || _methodSpecs == null || array7 == null || array8 == null) { return "the IL2CPP generic method tables could not be read"; } for (int i = 0; i + 16 <= array7.Length; i += 16) { int value = BitConverter.ToInt32(array7, i); int num = BitConverter.ToInt32(array7, i + 4); if (num >= 0 && num < array8.Length && array8[num] >= _image.ImageBase) { uint key = (uint)(array8[num] - _image.ImageBase); if (_genericByRva.ContainsKey(key)) { _genericShared.TryGetValue(key, out var value2); _genericShared[key] = value2 + 1; } else { _genericByRva[key] = value; } } } LoadModules(); _genericStarts = new List<uint>(_genericByRva.Keys).ToArray(); System.Array.Sort(_genericStarts); _methodStarts = new List<uint>(_methodByRva.Keys).ToArray(); System.Array.Sort(_methodStarts); return null; } private void LoadModules() { ulong[] array = ReadWords(CodeRegistration + 120, 2); if (array == null || array[0] > 400) { return; } ulong[] array2 = ReadWords(array[1], (int)array[0]); if (array2 == null) { return; } Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < _metadata.ImageCount; i++) { Il2CppMetadataFile.ImageRecord imageRecord = _metadata.Image(i); dictionary[_metadata.String(imageRecord.NameIndex)] = i; } ulong[] array3 = array2; foreach (ulong address in array3) { ulong[] array4 = ReadWords(address, 3); if (array4 == null || array4[1] > 3145728) { continue; } string text = ReadString(array4[0]); if (text == null || !dictionary.TryGetValue(text, out var value)) { continue; } ulong[] array5 = ReadWords(array4[2], (int)array4[1]); if (array5 == null) { continue; } Il2CppMetadataFile.ImageRecord imageRecord2 = _metadata.Image(value); for (int k = imageRecord2.FirstType; k < imageRecord2.FirstType + imageRecord2.TypeCount; k++) { Il2CppMetadataFile.TypeDefinitionRecord typeDefinitionRecord = _metadata.TypeDefinition(k); if (typeDefinitionRecord == null || typeDefinitionRecord.FirstMethodIndex < 0) { continue; } for (int l = typeDefinitionRecord.FirstMethodIndex; l < typeDefinitionRecord.FirstMethodIndex + typeDefinitionRecord.MethodCount; l++) { Il2CppMetadataFile.MethodRecord methodRecord = _metadata.Method(l); int num = ((methodRecord == null) ? (-1) : ((int)((methodRecord.Token & 0xFFFFFF) - 1))); if (num >= 0 && num < array5.Length && array5[num] >= _image.ImageBase) { uint key = (uint)(array5[num] - _image.ImageBase); if (!_methodByRva.ContainsKey(key)) { _methodByRva[key] = l; } } } } } } private ulong FindCodeRegistration() { int imageCount = _metadata.ImageCount; Dictionary<ulong, List<ulong>> dictionary = FindWords(new HashSet<ulong>(FindStrings("mscorlib.dll"))); HashSet<ulong> hashSet = new HashSet<ulong>(); foreach (List<ulong> value2 in dictionary.Values) { hashSet.UnionWith(value2); } HashSet<ulong> hashSet2 = new HashSet<ulong>(); foreach (List<ulong> value3 in FindWords(hashSet).Values) { hashSet2.UnionWith(value3); } HashSet<ulong> hashSet3 = new HashSet<ulong>(); int num = Math.Min(400, imageCount); foreach (ulong item2 in hashSet2) { for (int i = 0; i <= num; i++) { hashSet3.Add(item2 - (ulong)((long)i * 8L)); } } Dictionary<ulong, List<ulong>> dictionary2 = FindWords(hashSet3); List<ulong> list = new List<ulong>(); foreach (ulong item3 in hashSet2) { for (int j = 0; j <= num; j++) { if (!dictionary2.TryGetValue(item3 - (ulong)((long)j * 8L), out var value) || value.Count != 1) { continue; } ulong[] array = ReadWords(value[0] - 8, 1); if (array != null && array[0] != 0L && array[0] <= (ulong)imageCount && (ulong)j < array[0]) { ulong item = value[0] - 128; if (!list.Contains(item)) { list.Add(item); } break; } } } if (list.Count != 1) { return 0uL; } return list[0]; } private ulong FindMetadataRegistration() { List<ulong> value; foreach (ulong item in FindWords(new HashSet<ulong> { (ulong)_metadata.TypeDefinitionCount }).TryGetValue((ulong)_metadata.TypeDefinitionCount, out value) ? value : new List<ulong>()) { ulong num = item - 96; ulong[] array = ReadWords(num, 16); if (array != null) { bool flag = true; for (int i = 0; i < 16 && flag; i++) { flag = ((i % 2 != 0) ? ((array[i] != 0L) ? (_image.ReadVirtual(array[i], 1) != null) : (i >= 14 || i == 1)) : (array[i] < 786432)); } if (flag) { return num; } } } return 0uL; } private List<ulong> FindStrings(string text) { List<ulong> list = new List<ulong>(); byte[] bytes = Encoding.ASCII.GetBytes(text + "\0"); foreach (KeyValuePair<uint, byte[]> datum in _data) { byte[] value = datum.Value; for (int i = 0; i + bytes.Length <= value.Length; i++) { if (value[i] == bytes[0]) { bool flag = true; for (int j = 1; j < bytes.Length && flag; j++) { flag = value[i + j] == bytes[j]; } if (flag && (i == 0 || value[i - 1] == 0)) { list.Add(_image.ImageBase + datum.Key + (uint)i); } } } } return list; } private Dictionary<ulong, List<ulong>> FindWords(HashSet<ulong> values) { Dictionary<ulong, List<ulong>> dictionary = new Dictionary<ulong, List<ulong>>(); if (values.Count == 0) { return dictionary; } foreach (KeyValuePair<uint, byte[]> datum in _data) { byte[] value = datum.Value; for (int i = 0; i + 8 <= value.Length; i += 8) { ulong num = BitConverter.ToUInt64(value, i); if (values.Contains(num)) { if (!dictionary.TryGetValue(num, out var value2)) { value2 = (dictionary[num] = new List<ulong>()); } value2.Add(_image.ImageBase + datum.Key + (uint)i); } } } return dictionary; } private ulong[] ReadWords(ulong address, int count) { if (count < 0) { return null; } byte[] array = _image.ReadVirtual(address, count * 8); if (array == null) { return null; } ulong[] array2 = new ulong[count]; for (int i = 0; i < count; i++) { array2[i] = BitConverter.ToUInt64(array, i * 8); } return array2; } private string ReadString(ulong address) { byte[] array = _image.ReadVirtual(address, 256); if (array == null) { return null; } int num = System.Array.IndexOf(array, (byte)0); if (num > 0) { return Encoding.UTF8.GetString(array, 0, num); } return null; } private string MethodSpecName(int spec) { if (spec < 0 || (spec + 1) * 12 > _methodSpecs.Length) { return null; } int methodIndex = BitConverter.ToInt32(_methodSpecs, spec * 12); int index = BitConverter.ToInt32(_methodSpecs, spec * 12 + 4); int index2 = BitConverter.ToInt32(_methodSpecs, spec * 12 + 8); return MethodName(methodIndex, InstArguments(index), InstArguments(index2)); } private List<ulong> InstArguments(int index) { if (index < 0 || index >= _genericInsts.Length) { return null; } return InstArgumentsAt(_genericInsts[index]); } private List<ulong> InstArgumentsAt(ulong address) { ulong[] array = ReadWords(address, 2); if (array == null || array[0] > 64) { return null; } ulong[] array2 = ReadWords(array[1], (int)array[0]); if (array2 != null) { return new List<ulong>(array2); } return null; } private string MethodName(int methodIndex, List<ulong> classArguments, List<ulong> methodArguments) { Il2CppMetadataFile.MethodRecord methodRecord = _metadata.Method(methodIndex); if (methodRecord == null) { return null; } GenericContext context = new GenericContext(classArguments, methodArguments); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(TypeDefinitionFullName(methodRecord.DeclaringType, classArguments, 0)); stringBuilder.Append('.').Append(_metadata.String(methodRecord.NameIndex)); List<string> list = ((methodRecord.GenericContainerIndex >= 0) ? _metadata.GenericParameterNames(methodRecord.GenericContainerIndex) : null); if (methodArguments != null && methodArguments.Count > 0) { stringBuilder.Append('<').Append(string.Join(", ", ArgumentNames(methodArguments, list, null, 0))).Append('>'); } else if (list != null && list.Count > 0) { stringBuilder.Append('<').Append(string.Join(", ", list)).Append('>'); } List<string> list2 = new List<string>(); for (int i = 0; i < methodRecord.ParameterCount && i < 64; i++) { int num = _metadata.ParameterType(methodRecord.ParameterStart + i); list2.Add((num < 0 || num >= _types.Length) ? "?" : TypeName(_types[num], context, 0)); } stringBuilder.Append('(').Append(string.Join(", ", list2)).Append(')'); return stringBuilder.ToString(); } private List<string> ArgumentNames(List<ulong> arguments, List<string> parameterNames, GenericContext context, int depth) { List<string> list = new List<string>(); for (int i = 0; i < arguments.Count; i++) { list.Add((IsFullyShared(arguments[i]) && parameterNames != null && i < parameterNames.Count) ? parameterNames[i] : TypeName(arguments[i], context, depth)); } return list; } private List<string> ParameterNamesOf(int definition) { Il2CppMetadataFile.TypeDefinitionRecord typeDefinitionRecord = _metadata.TypeDefinition(definition); if (typeDefinitionRecord != null && typeDefinitionRecord.GenericContainerIndex >= 0) { return _metadata.GenericParameterNames(typeDefinitionRecord.GenericContainerIndex); } return null; } private bool IsFullyShared(ulong typeAddress) { int num = DefinitionOf(typeAddress); if (num < 0) { return false; } if (!_fullyShared.TryGetValue(num, out var value)) { Il2CppMetadataFile.TypeDefinitionRecord typeDefinitionRecord = _metadata.TypeDefinition(num); value = typeDefinitionRecord != null && _metadata.String(typeDefinitionRecord.NameIndex).StartsWith("__Il2CppFullySharedGeneric", StringComparison.Ordinal); _fullyShared[num] = value; } return value; } private string TypeDefinitionFullName(int definition, List<ulong> arguments, int depth) { return GenericTypeName(definition, arguments, null, depth, full: true); } private string GenericTypeName(int definition, List<ulong> arguments, GenericContext context, int depth, bool full) { Il2CppMetadataFile.TypeDefinitionRecord typeDefinitionRecord = _metadata.TypeDefinition(definition); if (typeDefinitionRecord == null) { return "?"; } arguments = arguments ?? new List<ulong>(); List<string> list = ParameterNamesOf(definition) ?? new List<string>(); int num = ((depth < 12 && typeDefinitionRecord.DeclaringTypeIndex >= 0 && typeDefinitionRecord.DeclaringTypeIndex < _types.Length) ? DefinitionOf(_types[typeDefinitionRecord.DeclaringTypeIndex]) : (-1)); int num2 = ((num >= 0) ? (ParameterNamesOf(num)?.Count ?? 0) : 0); int num3 = ((arguments.Count > 0) ? Math.Min(arguments.Count, num2) : 0); string text = _metadata.String(typeDefinitionRecord.NameIndex); string text2 = (full ? WithoutArity(text) : ShortDefinitionName(definition)); if (arguments.Count > num3) { List<ulong> range = arguments.GetRange(num3, arguments.Count - num3); List<string> parameterNames = ((list.Count > num3) ? list.GetRange(num3, list.Count - num3) : null); text2 = text2 + "<" + string.Join(", ", ArgumentNames(range, parameterNames, context, depth + 1)) + ">"; } else if (arguments.Count == 0 && full && text.IndexOf('`') >= 0 && list.Count > num2) { text2 = text2 + "<" + string.Join(", ", list.GetRange(num2, list.Count - num2)) + ">"; } if (num >= 0 && (full || num3 > 0)) { return GenericTypeName(num, (num3 > 0) ? arguments.GetRange(0, num3) : null, context, depth + 1, full) + "." + text2; } if (!full) { return text2; } string text3 = _metadata.String(typeDefinitionRecord.NamespaceIndex); if (text3.Length != 0) { return text3 + "." + text2; } return text2; } private string ShortDefinitionName(int definition) { if (_typeNames.TryGetValue(definition, out var value)) { return value; } Il2CppMetadataFile.TypeDefinitionRecord typeDefinitionRecord = _metadata.TypeDefinition(definition); string text = ((typeDefinitionRecord == null) ? "?" : WithoutArity(_metadata.String(typeDefinitionRecord.NameIndex))); if (typeDefinitionRecord != null && _metadata.String(typeDefinitionRecord.NamespaceIndex) == "System") { if (!(text == "Object")) { if (text == "String") { text = "string"; } } else { text = "object"; } } _typeNames[definition] = text; return text; } private int DefinitionOf(ulong typeAddress) { byte[] array = _image.ReadVirtual(typeAddress, 12); if (array == null) { return -1; } ulong num = BitConverter.ToUInt64(array, 0); switch ((int)((BitConverter.ToUInt32(array, 8) >> 16) & 0xFF)) { case 17: case 18: return (int)num; case 21: { ulong[] array2 = ReadWords(num, 1); if (array2 != null) { return DefinitionOf(array2[0]); } return -1; } default: return -1; } } private string TypeName(ulong typeAddress, GenericContext context, int depth) { if (depth > 12) { return "?"; } byte[] array = _image.ReadVirtual(typeAddress, 12); if (array == null) { return "?"; } ulong data = BitConverter.ToUInt64(array, 0); uint num = BitConverter.ToUInt32(array, 8); int num2 = (int)((num >> 16) & 0xFF); bool num3 = ((num >> 29) & 1) != 0 && num2 != 1; string text = KindName(num2, data, context, depth); if (!num3) { return text; } return "ref " + text; } private string KindName(int kind, ulong data, GenericContext context, int depth) { if (Primitives.TryGetValue(kind, out var value)) { return value; } switch (kind) { case 17: case 18: return ShortDefinitionName((int)data); case 21: { ulong[] array2 = ReadWords(data, 2); if (array2 == null) { return "?"; } int num = DefinitionOf(array2[0]); List<ulong> list = InstArgumentsAt(array2[1]) ?? new List<ulong>(); if (num < 0) { return "?"; } if (ShortDefinitionName(num) == "Nullable" && list.Count == 1) { return TypeName(list[0], context, depth + 1) + "?"; } return GenericTypeName(num, list, context, depth + 1, full: false); } case 19: case 30: { Il2CppMetadataFile.GenericParameterRecord genericParameterRecord = _metadata.GenericParameter((int)data); List<ulong> list2 = ((kind != 19) ? context?.MethodArguments : context?.ClassArguments); if (genericParameterRecord != null && list2 != null && genericParameterRecord.Number < list2.Count && !IsFullyShared(list2[genericParameterRecord.Number])) { return TypeName(list2[genericParameterRecord.Number], null, depth + 1); } if (genericParameterRecord != null) { return _metadata.String(genericParameterRecord.NameIndex); } return "?"; } case 29: return TypeName(data, context, depth + 1) + "[]"; case 15: return TypeName(data, context, depth + 1) + "*"; case 20: { byte[] array = _image.ReadVirtual(data, 9); if (array == null) { return "?[]"; } return TypeName(BitConverter.ToUInt64(array, 0), context, depth + 1) + "[" + new string(',', Math.Max(0, array[8] - 1)) + "]"; } default: return "?"; } } private static string WithoutArity(string name) { int num = name.IndexOf('`'); if (num >= 0) { return name.Substring(0, num); } return name; } } internal sealed class Il2CppMetadataFile { internal sealed class TypeDefinitionRecord { public int NameIndex { get; set; } public int NamespaceIndex { get; set; } public int ByvalTypeIndex { get; set; } public int DeclaringTypeIndex { get; set; } public int ParentIndex { get; set; } public int GenericContainerIndex { get; set; } public uint Flags { get; set; } public int FirstMethodIndex { get; set; } public int MethodCount { get; set; } } internal sealed class MethodRecord { public int NameIndex { get; set; } public int DeclaringType { get; set; } public int ReturnType { get; set; } public int ParameterStart { get; set; } public int GenericContainerIndex { get; set; } public uint Token { get; set; } public int ParameterCount { get; set; } } internal sealed class GenericParameterRecord { public int Owner { get; set; } public int NameIndex { get; set; } public int Number { get; set; } } internal sealed class ImageRecord { public int NameIndex { get; set; } public int FirstType { get; set; } public int TypeCount { get; set; } } private struct RecordReader { private readonly Il2CppMetadataFile _owner; private int _at; public RecordReader(Il2CppMetadataFile owner, int at) { _owner = owner; _at = at; } public int Int32() { int result = BitConverter.ToInt32(_owner._data, _at); _at += 4; return result; } public uint UInt32() { uint result = BitConverter.ToUInt32(_owner._data, _at); _at += 4; return result; } public int UInt16() { ushort result = BitConverter.ToUInt16(_owner._data, _at); _at += 2; return result; } public int Int16() { short result = BitConverter.ToInt16(_owner._data, _at); _at += 2; return result; } public int Byte() { return _owner._data[_at++]; } public int Index(int width) { switch (width) { case 1: { byte b = _owner._data[_at++]; if (b != byte.MaxValue) { return b; } return -1; } case 2: { ushort num = BitConverter.ToUInt16(_owner._data, _at); _at += 2; if (num != ushort.MaxValue) { return num; } return -1; } default: return Int32(); } } } public const uint Magic = 4205910959u; public const int OldestVersion = 29; public const int NewestVersion = 106; public const string FileName = "global-metadata.dat"; private const int Strings = 2; private const int Methods = 5; private const int Parameters = 10; private const int Fields = 11; private const int GenericParameters = 12; private const int GenericContainers = 14; private const int NestedTypes = 15; private const int InterfaceOffsets = 18; private const int TypeDefinitions = 19; private const int Images = 21; private const int Events = 3; private const int Properties = 4; private const int DefaultValueData = 8; private static readonly int[] SectionsBeforeImages = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; private readonly byte[] _data; private readonly int[] _offset = new int[32]; private readonly int[] _size = new int[32]; private readonly int[] _count = new int[32]; private int _typeWidth; private int _typeDefinitionWidth; private int _genericContainerWidth; private int _parameterWidth; private int _interfaceOffsetWidth; private int _eventWidth; private int _propertyWidth; private int _nestedTypeWidth; private int _methodWidth; private int _genericParameterWidth; private int _fieldWidth; public int Version { get; private set; } public int TypeDefinitionCount { get; private set; } public int MethodCount { get; private set; } public int ImageCount { get; private set; } public int TypeDefinitionSize { get; private set; } public int MethodSize { get; private set; } public int ParameterSize { get; private set; } public int GenericContainerSize { get; private set; } public int GenericParameterSize { get; private set; } public int ImageSize { get; private set; } private Il2CppMetadataFile(byte[] data) { _data = data; } public static Il2CppMetadataFile Open(string path, out string problem) { problem = null; if (string.IsNullOrEmpty(path) || !File.Exists(path)) { problem = path + " is missing"; return null; } try { Il2CppMetadataFile il2CppMetadataFile = new Il2CppMetadataFile(File.ReadAllBytes(path)); problem = il2CppMetadataFile.ReadHeader(); return (problem == null) ? il2CppMetadataFile : null; } catch (Exception ex) { problem = path + " could not be read: " + ex.Message; return null; } } public string String(int index) { if (index < 0 || index >= _size[2]) { return string.Empty; } int num = _offset[2] + index; int i = num; for (int num2 = _offset[2] + _size[2]; i < num2 && _data[i] != 0; i++) { } return Encoding.UTF8.GetString(_data, num, i - num); } public TypeDefinitionRecord TypeDefinition(int index) { if (index < 0 || index >= TypeDefinitionCount) { return null; } RecordReader recordReader = new RecordReader(this, _offset[19] + index * TypeDefinitionSize); TypeDefinitionRecord obj = new TypeDefinitionRecord { NameIndex = recordReader.Int32(), NamespaceIndex = recordReader.Int32(), ByvalTypeIndex = recordReader.Index(_typeWidth), DeclaringTypeIndex = recordReader.Index(_typeWidth), ParentIndex = recordReader.Index(_typeWidth) }; if (Version < 35) { recordReader.Int32(); } obj.GenericContainerIndex = recordReader.Index(_genericContainerWidth); obj.Flags = recordReader.UInt32(); recordReader.Index(_fieldWidth); obj.FirstMethodIndex = recordReader.Index(_methodWidth); recordReader.Index(_eventWidth); recordReader.Index(_propertyWidth); recordReader.Index(_nestedTypeWidth); recordReader.Index(_interfaceOffsetWidth); recordReader.Int32(); recordReader.Index(_interfaceOffsetWidth); obj.MethodCount = recordReader.UInt16(); return obj; } public MethodRecord Method(int index) { if (index < 0 || index >= MethodCount) { return null; } RecordReader recordReader = new RecordReader(this, _offset[5] + index * MethodSize); MethodRecord obj = new MethodRecord { NameIndex = recordReader.Int32(), DeclaringType = recordReader.Index(_typeDefinitionWidth), ReturnType = recordReader.Index(_typeWidth) }; if (Version >= 31) { recordReader.UInt32(); } obj.ParameterStart = recordReader.Index(_parameterWidth); obj.GenericContainerIndex = recordReader.Index(_genericContainerWidth); obj.Token = recordReader.UInt32(); recordReader.UInt16(); recordReader.UInt16(); recordReader.UInt16(); obj.ParameterCount = recordReader.UInt16(); return obj; } public int ParameterType(int index) { if (index < 0 || index >= _size[10] / ParameterSize) { return -1; } RecordReader recordReader = new RecordReader(this, _offset[10] + index * ParameterSize); recordReader.Int32(); recordReader.UInt32(); return recordReader.Index(_typeWidth); } public List<string> GenericParameterNames(int containerIndex) { List<string> list = new List<string>(); if (containerIndex < 0 || containerIndex >= _size[14] / GenericContainerSize) { return list; } RecordReader recordReader = new RecordReader(this, _offset[14] + containerIndex * GenericContainerSize); recordReader.Int32(); int num; if (Version >= 106) { num = recordReader.UInt16(); recordReader.Byte(); } else { num = recordReader.Int32(); recordReader.Int32(); } int num2 = recordReader.Index(_genericParameterWidth); for (int i = 0; i < num && i < 64; i++) { list.Add(GenericParameterName(num2 + i)); } return list; } public string GenericParameterName(int index) { GenericParameterRecord genericParameterRecord = GenericParameter(index); if (genericParameterRecord != null) { return String(genericParameterRecord.NameIndex); } return "T" + index; } public GenericParameterRecord GenericParameter(int index) { if (index < 0 || index >= _size[12] / GenericParameterSize) { return null; } RecordReader recordReader = new RecordReader(this, _offset[12] + index * GenericParameterSize); GenericParameterRecord obj = new GenericParameterRecord { Owner = recordReader.Index(_genericContainerWidth), NameIndex = recordReader.Int32() }; recordReader.Int16(); recordReader.Int16(); obj.Number = recordReader.UInt16(); return obj; } public ImageRecord Image(int index) { if (index < 0 || index >= ImageCount) { return null; } RecordReader recordReader = new RecordReader(this, _offset[21] + index * ImageSize); ImageRecord obj = new ImageRecord { NameIndex = recordReader.Int32() }; recordReader.Int32(); obj.FirstType = recordReader.Index(_typeDefinitionWidth); obj.TypeCount = (int)recordReader.UInt32(); return obj; } private static int Width(int count) { if (count > 255) { if (count > 65535) { return 4; } return 2; } return 1; } private string ReadHeader() { if (_data.Length < 16 || BitConverter.ToUInt32(_data, 0) != 4205910959u) { return "global-metadata.dat has an unknown format"; } Version = BitConverter.ToInt32(_data, 4); if (Version < 29 || Version > 106) { return $"global-metadata.dat has version {Version}, the crash watcher reads versions {29} to {106}"; } bool flag = Version >= 38; int num = (flag ? 12 : 8); int num2 = 8; List<int> list = new List<int>(SectionsBeforeImages); if (Version >= 104) { list.Add(-1); } list.Add(21); list.Add(22); foreach (int item in list) { if (num2 + num > _data.Length) { return "global-metadata.dat is cut short"; } if (item >= 0) { _offset[item] = BitConverter.ToInt32(_data, num2); _size[item] = BitConverter.ToInt32(_data, num2 + 4); _count[item] = (flag ? BitConverter.ToInt32(_data, num2 + 8) : 0); if (_offset[item] < 0 || _size[item] < 0 || (long)_offset[item] + (long)_size[item] > _data.Length) { return $"global-metadata.dat has a section outside the file at header offset {num2}"; } } num2 += num; } bool flag2 = Version < 38; _typeWidth = (flag2 ? 4 : (_size[18] / Math.Max(1, _count[18]) - 4)); _typeDefinitionWidth = (flag2 ? 4 : Width(_count[19])); _genericContainerWidth = (flag2 ? 4 : Width(_count[14])); _parameterWidth = ((Version >= 39) ? Width(_count[10]) : 4); _interfaceOffsetWidth = ((Version >= 104) ? Width(_count[18]) : 4); _eventWidth = ((Version >= 104) ? Width(_count[3]) : 4); _propertyWidth = ((Version >= 104) ? Width(_count[4]) : 4); _nestedTypeWidth = ((Version >= 104) ? Width(_count[15]) : 4); _methodWidth = ((Version >= 105) ? Width(_count[5]) : 4); _genericParameterWidth = ((Version >= 106) ? Width(_count[12]) : 4); _fieldWidth = ((Version >= 106) ? Width(_count[11]) : 4); if (_typeWidth != 1 && _typeWidth != 2 && _typeWidth != 4) { return $"global-metadata.dat gives a type index width of {_typeWidth}"; } TypeDefinitionSize = 8 + _typeWidth * 3 + ((Version < 35) ? 4 : 0) + _genericContainerWidth + 4 + _fieldWidth + _methodWidth + _eventWidth + _propertyWidth + _nestedTypeWidth + _interfaceOffsetWidth + 4 + _interfaceOffsetWidth + 16 + 4 + 4; MethodSize = 4 + _typeDefinitionWidth + _typeWidth + ((Version >= 31) ? 4 : 0) + _parameterWidth + _genericContainerWidth + 4 + 8; ParameterSize = 8 + _typeWidth; GenericContainerSize = 4 + ((Version >= 106) ? 3 : 8) + _genericParameterWidth; GenericParameterSize = _genericContainerWidth + 4 + 2 + 2 + 2 + 2; ImageSize = 8 + _typeDefinitionWidth + 4 + _typeDefinitionWidth + 4 + _methodWidth + 4 + 4 + 4; TypeDefinitionCount = _size[19] / TypeDefinitionSize; MethodCount = _size[5] / MethodSize; ImageCount = _size[21] / ImageSize; if (flag && (TypeDefinitionCount != _count[19] || MethodCount != _count[5] || ImageCount != _count[21])) { return $"global-metadata.dat version {Version} does not match the record sizes the crash watcher expects (type definitions {TypeDefinitionCount} of {_count[19]}, methods {MethodCount} of {_count[5]}, images {ImageCount} of {_count[21]})"; } if (!flag && (_size[19] % TypeDefinitionSize != 0 || _size[5] % MethodSize != 0 || _size[21] % ImageSize != 0)) { return $"global-metadata.dat version {Version} does not match the record sizes the crash watcher expects"; } return null; } } internal sealed class ManagedMetadata { private sealed class SignatureReader { private readonly ManagedMetadata _owner; private readonly int _type; private readonly int _method; private readonly int _end; private int _at; private int _depth; public SignatureReader(ManagedMetadata owner, int blobIndex, int type, int method) { _owner = owner; _type = type; _method = method; _at = owner._blob + blobIndex; int num = Compressed(); _end = Math.Min(_at + num, owner._blob + owner._blobSize); } public byte Byte() { if (_at >= _end) { throw new IndexOutOfRangeException(); } return _owner._data[_at++]; } public int Compressed() { return _owner.ReadCompressed(ref _at); } public string Type() { if (++_depth > 64) { throw new ArgumentException("Signature too deep"); } try { byte b = Byte(); if (b >= 1 && b <= 14) { return Primitives[b]; } switch (b) { case 15: return Type() + "*"; case 16: return "ref " + Type(); case 17: case 18: return Named(Compressed(), null); case 19: return Generic(0, _type, Compressed()); case 20: return ArrayType(); case 21: { Byte(); int coded = Compressed(); int num = Compressed(); List<string> list = new List<string>(); for (int i = 0; i < num && i < 32; i++) { list.Add(Type()); } return Named(coded, list); } case 22: return "TypedReference"; case 24: return "IntPtr"; case 25: return "UIntPtr"; case 27: SkipMethodSignature(); return "fnptr"; case 28: return "object"; case 29: return Type() + "[]"; case 30: return Generic(1, _method, Compressed()); case 31: case 32: Compressed(); return Type(); case 65: case 69: return Type(); default: throw new ArgumentException("Unknown element type"); } } finally { _depth--; } } private string Generic(int tag, int owner, int number) { List<string> list = _owner.GenericNames(tag, owner); if (number >= list.Count) { return ((tag == 0) ? "!" : "!!") + number; } return list[number]; } private string ArrayType() { string text = Type(); int num = Compressed(); int num2 = Compressed(); for (int i = 0; i < num2; i++) { Compressed(); } int num3 = Compressed(); for (int j = 0; j < num3; j++) { Compressed(); } return text + "[" + new string(',', Math.Max(0, num - 1)) + "]"; } private void SkipMethodSignature() { if ((Byte() & 0x10) != 0) { Compressed(); } int num = Compressed(); Type(); for (int i = 0; i < num; i++) { Type(); } } private string Named(int coded, List<string> arguments) { if ((coded & 3) == 2) { return "?"; } string text = _owner.ShortTypeName(coded); string text2 = WithoutArity(text); if (arguments == null || arguments.Count == 0) { if (!(text == "Il2CppStringArray")) { return text2; } return "string[]"; } switch (text2) { case "Il2CppStructArray": case "Il2CppReferenceArray": case "Il2CppArrayBase": return arguments[0] + "[]"; case "Nullable": return arguments[0] + "?"; default: return text2 + "<" + string.Join(", ", arguments) + ">"; } } } public const uint Signature = 1112167234u; public const int MethodDefTable = 6; public const int TypeRefTable = 1; public const int TypeDefTable = 2; public const int TypeSpecTable = 27; public const int NestedClassTable = 41; public const int GenericParamTable = 42; public const int MemberRefTable = 10; public const int CustomAttributeTable = 12; public const string OriginalNameAttribute = "ObfuscatedNameAttribute"; public const int MaxDepth = 16; private const int U16 = -1; private const int U32 = -2; private const int Str = -3; private const int Guid = -4; private const int Blob = -5; private const int Coded = 100; private static readonly int[][] CodedTables = new int[13][] { new int[3] { 2, 1, 27 }, new int[3] { 4, 8, 23 }, new int[22] { 6, 4, 1, 2, 8, 9, 10, 0, 14, 23, 20, 17, 26, 27, 32, 35, 38, 39, 40, 42, 44, 43 }, new int[2] { 4, 8 }, new int[3] { 2, 6, 32 }, new int[5] { 2, 1, 26, 6, 27 }, new int[2] { 20, 23 }, new int[2] { 6, 10 }, new int[2] { 4, 6 }, new int[3] { 38, 35, 39 }, new int[5] { -1, -1, 6, 10, -1 }, new int[4] { 0, 26, 35, 1 }, new int[2] { 2, 6 } }; private static readonly int[][] Schema = new int[45][] { new int[5] { -1, -3, -4, -4, -4 }, new int[3] { 111, -3, -3 }, new int[6] { -2, -3, -3, 100, 4, 6 }, new int[1] { 4 }, new int[3] { -1, -3, -5 }, new int[1] { 6 }, new int[6] { -2, -1, -1, -3, -5, 8 }, new int[1] { 8 }, new int[3] { -1, -1, -3 }, new int[2] { 2, 100 }, new int[3] { 105, -3, -5 }, new int[3] { -1, 101, -5 }, new int[3] { 102, 110, -5 }, new int[2] { 103, -5 }, new int[3] { -1, 104, -5 }, new int[3] { -1, -2, 2 }, new int[2] { -2, 4 }, new int[1] { -5 }, new int[2] { 2, 20 }, new int[1] { 20 }, new int[3] { -1, -3, 100 }, new int[2] { 2, 23 }, new int[1] { 23 }, new int[3] { -1, -3, -5 }, new int[3] { -1, 6, 106 }, new int[3] { 2, 107, 107 }, new int[1] { -3 }, new int[1] { -5 }, new int[4] { -1, 108, -3, 26 }, new int[2] { -2, 4 }, new int[2] { -2, -2 }, new int[1] { -2 }, new int[9] { -2, -1, -1, -1, -1, -2, -5, -3, -3 }, new int[1] { -2 }, new int[3] { -2, -2, -2 }, new int[9] { -1, -1, -1, -1, -2, -5, -3, -3, -5 }, new int[2] { -2, 35 }, new int[4] { -2, -2, -2, 35 }, new int[3] { -2, -3, -5 }, new int[5] { -2, -2, -3, -3, 109 }, new int[4] { -2, -2, -3, 109 }, new int[2] { 2, 2 }, new int[4] { -1, -1, 112, -3 }, new int[2] { 107, -5 }, new int[2] { 42, 100 } }; private static readonly Dictionary<string, string> Aliases = new Dictionary<string, string>(StringComparer.Ordinal) { ["System.Void"] = "void", ["System.Boolean"] = "bool", ["System.Char"] = "char", ["System.SByte"] = "sbyte", ["System.Byte"] = "byte", ["System.Int16"] = "short", ["System.UInt16"] = "ushort", ["System.Int32"] = "int", ["System.UInt32"] = "uint", ["System.Int64"] = "long", ["System.UInt64"] = "ulong", ["System.Single"] = "float", ["System.Double"] = "double", ["System.String"] = "string", ["System.Object"] = "object", ["System.IntPtr"] = "IntPtr", ["System.UIntPtr"] = "UIntPtr" }; private static readonly string[] Primitives = new string[15] { null, "void", "bool", "char", "sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "float", "double", "string" }; private readonly byte[] _data; private readonly int[] _rows = new int[64]; private readonly int[] _tableStart = new int[64]; private readonly int[] _rowSize = new int[64]; private readonly int[][] _columnOffset = new int[64][]; private readonly int[][] _columnSize = new int[64][]; private int _strings; private int _stringsSize; private int _blob; private int _blobSize; private int _stringIndexSize; private int _guidIndexSize; private int _blobIndexSize; private Dictionary<int, int> _enclosing; private Dictionary<long, List<string>> _genericNames; private Dictionary<long, string> _originalNames; public int MethodCount => _rows[6]; private ManagedMetadata(byte[] data) { _data = data; } public static ManagedMetadata Read(byte[] metadata) { if (metadata == null || metadata.Length < 32 || BitConverter.ToUInt32(metadata, 0) != 1112167234) { return null; } ManagedMetadata managedMetadata = new ManagedMetadata(metadata); if (!managedMetadata.ReadStreams()) { return null; } return managedMetadata; } public string MethodName(int token) { if (token >> 24 != 6) { return null; } int num = token & 0xFFFFFF; if (num < 1 || num > _rows[6]) { return null; } int num2 = DeclaringType(num); string value = OriginalName(0, num) ?? String(Value(6, num, 3)); StringBuilder stringBuilder = new StringBuilder(); if (num2 > 0) { stringBuilder.Append(TypeDefFullName(num2, 0)).Append('.'); } stringBuilder.Append(value); List<string> list = GenericNames(1, num); if (list.Count > 0) { stringBuilder.Append('<').Append(string.Join(", ", list)).Append('>'); } stringBuilder.Append('(').Append(Parameters(Value(6, num, 4), num2, num)).Append(')'); return stringBuilder.ToString(); } private bool ReadStreams() { int num = BitConverter.ToInt32(_data, 12); int num2 = 16 + ((num + 3) & -4); if (num2 + 4 > _data.Length) { return false; } ushort num3 = BitConverter.ToUInt16(_data, num2 + 2); num2 += 4; int num4 = -1; for (int i = 0; i < num3; i++) { if (num2 + 8 >= _data.Length) { break; } int num5 = BitConverter.ToInt32(_data, num2); int num6 = BitConverter.ToInt32(_data, num2 + 4); num2 += 8; int num7 = num2; for (; num2 < _data.Length && _data[num2] != 0; num2++) { } string text = Encoding.ASCII.GetString(_data, num7, num2 - num7); num2 = num7 + ((num2 - num7 + 4) & -4); switch (text) { case "#~": num4 = num5; break; case "#Strings": _strings = num5; _stringsSize = num6; break; case "#Blob": _blob = num5; _blobSize = num6; break; } } if (num4 >= 0) { return ReadTables(num4); } return false; } private bool ReadTables(int at) { byte b = _data[at + 6]; ulong num = BitConverter.ToUInt64(_data, at + 8); _stringIndexSize = (((b & 1) != 0) ? 4 : 2); _guidIndexSize = (((b & 2) != 0) ? 4 : 2); _blobIndexSize = (((b & 4) != 0) ? 4 : 2); int num2 = at + 24; for (int i = 0; i < 64; i++) { if (((num >> i) & 1) != 0L) { if (i >= Schema.Length) { return false; } _rows[i] = BitConverter.ToInt32(_data, num2); num2 += 4; } } if ((b & 0x40) != 0) { num2 += 4; } for (int j = 0; j < Schema.Length; j++) { int[] array = Schema[j]; _columnOffset[j] = new int[array.Length]; _columnSize[j] = new int[array.Length]; int num3 = 0; for (int k = 0; k < array.Length; k++) { _columnOffset[j][k] = num3; _columnSize[j][k] = ColumnSize(array[k]); num3 += _columnSize[j][k]; } _rowSize[j] = num3; _tableStart[j] = num2; num2 += num3 * _rows[j]; } return num2 <= _data.Length; } private int ColumnSize(int kind) { switch (kind) { case -1: return 2; case -2: return 4; case -3: return _stringIndexSize; case -4: return _guidIndexSize; case -5: return _blobIndexSize; default: if (kind >= 100) { int[] array = CodedTables[kind - 100]; int i; for (i = 0; 1 << i < array.Length; i++) { } int num = 0; int[] array2 = array; foreach (int num2 in array2) { if (num2 >= 0) { num = Math.Max(num, _rows[num2]); } } if (num >= 1 << 16 - i) { return 4; } return 2; } if (_rows[kind] >= 65536) { return 4; } return 2; } } private int Value(int table, int row, int column) { int startIndex = _tableStart[table] + (row - 1) * _rowSize[table] + _columnOffset[table][column]; if (_columnSize[table][column] != 2) { return BitConverter.ToInt32(_data, startIndex); } return BitConverter.ToUInt16(_data, startIndex); } private string String(int index) { if (index <= 0 || index >= _stringsSize) { return string.Empty; } int num = _strings + index; int i; for (i = num; i < _strings + _stringsSize && _data[i] != 0; i++) { } return Encoding.UTF8.GetString(_data, num, i - num); } private int DeclaringType(int method) { int num = 1; int num2 = _rows[2]; int result = 0; while (num <= num2) { int num3 = (num + num2) / 2; if (Value(2, num3, 5) <= method) { result = num3; num = num3 + 1; } else { num2 = num3 - 1; } } return result; } private string TypeDefFullName(int type, int depth) { string text = OriginalName(3, type); if (text != null) { return text.Replace('+', '.'); } string text2 = GenericDisplayName(String(Value(2, type, 1)), GenericNames(0, type)); if (depth < 16 && Enclosing().TryGetValue(type, out var value)) { return TypeDefFullName(value, depth + 1) + "." + text2; } string text3 = OriginalNamespace(String(Value(2, type, 2))); if (text3.Length != 0) { return text3 + "." + text2; } return text2; } private Dictionary<int, int> Enclosing() { if (_enclosing == null) { _enclosing = new Dictionary<int, int>(); for (int i = 1; i <= _rows[41]; i++) { _enclosing[Value(41, i, 0)] = Value(41, i, 1); } } return _enclosing; } private List<string> GenericNames(int ownerTag, int owner) { if (_genericNames == null) { _genericNames = new Dictionary<long, List<string>>(); Dictionary<long, SortedDictionary<int, string>> dictionary = new Dictionary<long, SortedDictionary<int, string>>(); for (int i = 1; i <= _rows[42]; i++) { int num = Value(42, i, 2); long key = Key(num & 1, num >> 1); if (!dictionary.TryGetValue(key, out var value)) { value = (dictionary[key] = new SortedDictionary<int, string>()); } value[Value(42, i, 0)] = String(Value(42, i, 3)); } foreach (KeyValuePair<long, SortedDictionary<int, string>> item in dictionary) { _genericNames[item.Key] = new List<string>(item.Value.Values); } } if (!_genericNames.TryGetValue(Key(ownerTag, owner), out var value2)) { return new List<string>(); } return value2; } private string OriginalName(int parentTag, int row) { if (_originalNames == null) { _originalNames = new Dictionary<long, string>(); HashSet<int> hashSet = new HashSet<int>(); for (int i = 1; i <= _rows[1]; i++) { if (String(Value(1, i, 1)) != "ObfuscatedNameAttribute") { continue; } for (int j = 1; j <= _rows[10]; j++) { if (Value(10, j, 0) == ((i << 3) | 1)) { hashSet.Add((j << 3) | 3); } } } int num = 1; while (hashSet.Count > 0 && num <= _rows[12]) { if (hashSet.Contains(Value(12, num, 1))) { int num2 = Value(12, num, 0); string value = AttributeString(Value(12, num, 2)); if (!string.IsNullOrEmpty(value)) { _originalNames[Key(num2 & 0x1F, num2 >> 5)] = value; } } num++; } } if (!_originalNames.TryGetValue(Key(parentTag, row), out var value2)) { return null; } return value2; } private string AttributeString(int blobIndex) { try { int at = _blob + blobIndex; if (ReadCompressed(ref at) < 3 || _data[at] != 1 || _data[at + 1] != 0 || _data[at + 2] == byte.MaxValue) { return null; } at += 2; int num = ReadCompressed(ref at); return (at + num <= _data.Length) ? Encoding.UTF8.GetString(_data, at, num) : null; } catch (IndexOutOfRangeException) { return null; } } private int ReadCompressed(ref int at) { byte b = _data[at++]; if ((b & 0x80) == 0) { return b; } if ((b & 0xC0) == 128) { return ((b & 0x3F) << 8) | _data[at++]; } int result = ((b & 0x1F) << 24) | (_data[at] << 16) | (_data[at + 1] << 8) | _data[at + 2]; at += 3; return result; } private static long Key(int tag, int row) { return ((long)tag << 32) | (uint)row; } private string Parameters(int signature, int type, int method) { SignatureReader signatureReader = new SignatureReader(this, signature, type, method); try { if ((signatureReader.Byte() & 0x10) != 0) { signatureReader.Compressed(); } int num = signatureReader.Compressed(); signatureReader.Type(); List<string> list = new List<string>(); for (int i = 0; i < num && i < 64; i++) { list.Add(signatureReader.Type()); } return string.Join(", ", list); } catch (IndexOutOfRangeException) { return "?"; } catch (ArgumentException) { return "?"; } } private static string OriginalNamespace(string space) { string[] array = new string[3] { "Il2CppSystem", "Il2CppMono", "Il2CppMicrosoft" }; foreach (string text in array) { if (space == text || space.StartsWith(text + ".", StringComparison.Ordinal)) { return space.Substring("Il2Cpp".Length); } } return space; } private static string WithoutArity(string name) { int num = name.IndexOf('`'); if (num >= 0) { return name.Substring(0, num); } return name; } private static string GenericDisplayName(string name, List<string> parameters) { string text = WithoutArity(name); if (parameters.Count != 0 && !(text == name)) { return text + "<" + string.Join(", ", parameters) + ">"; } return text; } private string ShortTypeName(int coded) { int num = coded & 3; int num2 = coded >> 2; string space; string text; if (num == 0 && num2 >= 1 && num2 <= _rows[2]) { space = (Enclosing().ContainsKey(num2) ? string.Empty : String(Value(2, num2, 2))); text = String(Value(2, num2, 1)); } else { if (num != 1 || num2 < 1 || num2 > _rows[1]) { return "?"; } space = (((Value(1, num2, 0) & 3) == 3) ? string.Empty : String(Value(1, num2, 2))); text = String(Value(1, num2, 1)); } string key = OriginalNamespace(space) + "." + text; if (!Aliases.TryGetValue(key, out var value)) { return text; } return value; } } internal sealed class PdbPublics { private sealed class MsfReader { private readonly FileStream _file; private int _blockSize; private uint[] _streamSizes; private uint[][] _streamBlocks; public MsfReader(FileStream file) { _file = file; } public string Open() { byte[] array = ReadAt(0L, 56); if (array == null || Encoding.ASCII.GetString(array, 0, 32) != "Microsoft C/C++ MSF 7.00\r\n\u001aDS\0\0\0") { return "the PDB is not an MSF 7.00 file"; } _blockSize = BitConverter.ToInt32(array, 32); int num = BitConverter.ToInt32(array, 44); uint num2 = BitConverter.ToUInt32(array, 52); if (_blockSize < 512 || _blockSize > 65536 || num <= 0 || num > 67108864) { return "the PDB has an unexpected layout"; } int num3 = (