Decompiled source of Runtime Unity Editor v6.3.0
UMM/Mods/Runtime Unity Editor/mcs.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Threading; using System.Xml; using Microsoft.CodeAnalysis; using Mono.CSharp.Linq; using Mono.CSharp.Nullable; using Mono.CSharp.yyParser; using Mono.CSharp.yydebug; using Mono.CompilerServices.SymbolWriter; using Mono.Security.Cryptography; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Mono C# Compiler")] [assembly: AssemblyProduct("Mono C# Compiler")] [assembly: AssemblyCopyright("2001 - 2009 Novell, Inc.")] [assembly: AssemblyCompany("Novell, Inc.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyFileVersion("4.0.30319.17020")] [assembly: AssemblyDescription("Mono C# Compiler")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.13.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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; } } } internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.0.30319.17020"; public const string EnvironmentVersion = "4.0.30319.17020"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } namespace System { internal interface ITupleInternal : ITuple { string ToString(StringBuilder sb); int GetHashCode(IEqualityComparer comparer); } public static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3>(item1, item2, item3); } public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) { return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4); } public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5); } public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6); } public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7); } public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new Tuple<T8>(item8)); } internal static int CombineHashCodes(int h1, int h2) { return ((h1 << 5) + h1) ^ h2; } internal static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); } } [Serializable] public class Tuple<T1> : IComparable, System.ITupleInternal, ITuple { private readonly T1 m_Item1; public T1 Item1 => m_Item1; int ITuple.Length => 1; object? ITuple.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override bool Equals(object? obj) { return Equals(obj, EqualityComparer<object>.Default); } private bool Equals(object? other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple<T1> tuple)) { return false; } return comparer.Equals(m_Item1, tuple.m_Item1); } int IComparable.CompareTo(object? obj) { return CompareTo(obj, Comparer<object>.Default); } private int CompareTo(object? other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple<T1> tuple)) { throw new ArgumentException($"Tuple of incorrect type (expected {GetType()})", "other"); } return comparer.Compare(m_Item1, tuple.m_Item1); } public override int GetHashCode() { return GetHashCode(EqualityComparer<object>.Default); } int System.ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(m_Item1); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string System.ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(')'); return sb.ToString(); } } [Serializable] public class Tuple<T1, T2> : IComparable, System.ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; int ITuple.Length => 2; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override bool Equals(object? obj) { return Equals(obj, EqualityComparer<object>.Default); } private bool Equals(object? other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple<T1, T2> tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1)) { return comparer.Equals(m_Item2, tuple.m_Item2); } return false; } int IComparable.CompareTo(object? obj) { return CompareTo(obj, Comparer<object>.Default); } private int CompareTo(object? other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple<T1, T2> tuple)) { throw new ArgumentException($"Tuple of incorrect type (expected {GetType()})", "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } return comparer.Compare(m_Item2, tuple.m_Item2); } public override int GetHashCode() { return GetHashCode(EqualityComparer<object>.Default); } int System.ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string System.ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(')'); return sb.ToString(); } } [Serializable] public class Tuple<T1, T2, T3> : IComparable, System.ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; int ITuple.Length => 3; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; } public override bool Equals(object? obj) { return Equals(obj, EqualityComparer<object>.Default); } private bool Equals(object? other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple<T1, T2, T3> tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2)) { return comparer.Equals(m_Item3, tuple.m_Item3); } return false; } int IComparable.CompareTo(object? obj) { return CompareTo(obj, Comparer<object>.Default); } private int CompareTo(object? other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple<T1, T2, T3> tuple)) { throw new ArgumentException($"Tuple of incorrect type (expected {GetType()})", "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } return comparer.Compare(m_Item3, tuple.m_Item3); } public override int GetHashCode() { return GetHashCode(EqualityComparer<object>.Default); } int System.ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string System.ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(')'); return sb.ToString(); } } [Serializable] public class Tuple<T1, T2, T3, T4> : IComparable, System.ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; int ITuple.Length => 4; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; } public override bool Equals(object? obj) { return Equals(obj, EqualityComparer<object>.Default); } private bool Equals(object? other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple<T1, T2, T3, T4> tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3)) { return comparer.Equals(m_Item4, tuple.m_Item4); } return false; } int IComparable.CompareTo(object? obj) { return CompareTo(obj, Comparer<object>.Default); } private int CompareTo(object? other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple<T1, T2, T3, T4> tuple)) { throw new ArgumentException($"Tuple of incorrect type (expected {GetType()})", "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } return comparer.Compare(m_Item4, tuple.m_Item4); } public override int GetHashCode() { return GetHashCode(EqualityComparer<object>.Default); } int System.ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string System.ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(')'); return sb.ToString(); } } [Serializable] public class Tuple<T1, T2, T3, T4, T5> : IComparable, System.ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; private readonly T5 m_Item5; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; int ITuple.Length => 5; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; } public override bool Equals(object? obj) { return Equals(obj, EqualityComparer<object>.Default); } private bool Equals(object? other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple<T1, T2, T3, T4, T5> tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3) && comparer.Equals(m_Item4, tuple.m_Item4)) { return comparer.Equals(m_Item5, tuple.m_Item5); } return false; } int IComparable.CompareTo(object? obj) { return CompareTo(obj, Comparer<object>.Default); } private int CompareTo(object? other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple<T1, T2, T3, T4, T5> tuple)) { throw new ArgumentException($"Tuple of incorrect type (expected {GetType()})", "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } num = comparer.Compare(m_Item4, tuple.m_Item4); if (num != 0) { return num; } return comparer.Compare(m_Item5, tuple.m_Item5); } public override int GetHashCode() { return GetHashCode(EqualityComparer<object>.Default); } int System.ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string System.ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(')'); return sb.ToString(); } } [Serializable] public class Tuple<T1, T2, T3, T4, T5, T6> : IComparable, System.ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; private readonly T5 m_Item5; private readonly T6 m_Item6; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public T6 Item6 => m_Item6; int ITuple.Length => 6; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; } public override bool Equals(object? obj) { return Equals(obj, EqualityComparer<object>.Default); } private bool Equals(object? other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple<T1, T2, T3, T4, T5, T6> tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3) && comparer.Equals(m_Item4, tuple.m_Item4) && comparer.Equals(m_Item5, tuple.m_Item5)) { return comparer.Equals(m_Item6, tuple.m_Item6); } return false; } int IComparable.CompareTo(object? obj) { return CompareTo(obj, Comparer<object>.Default); } private int CompareTo(object? other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple<T1, T2, T3, T4, T5, T6> tuple)) { throw new ArgumentException($"Tuple of incorrect type (expected {GetType()})", "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } num = comparer.Compare(m_Item4, tuple.m_Item4); if (num != 0) { return num; } num = comparer.Compare(m_Item5, tuple.m_Item5); if (num != 0) { return num; } return comparer.Compare(m_Item6, tuple.m_Item6); } public override int GetHashCode() { return GetHashCode(EqualityComparer<object>.Default); } int System.ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string System.ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(')'); return sb.ToString(); } } [Serializable] public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IComparable, System.ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; private readonly T5 m_Item5; private readonly T6 m_Item6; private readonly T7 m_Item7; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public T6 Item6 => m_Item6; public T7 Item7 => m_Item7; int ITuple.Length => 7; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, 6 => Item7, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; } public override bool Equals(object? obj) { return Equals(obj, EqualityComparer<object>.Default); } private bool Equals(object? other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7> tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3) && comparer.Equals(m_Item4, tuple.m_Item4) && comparer.Equals(m_Item5, tuple.m_Item5) && comparer.Equals(m_Item6, tuple.m_Item6)) { return comparer.Equals(m_Item7, tuple.m_Item7); } return false; } private int CompareTo(object? other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7> tuple)) { throw new ArgumentException($"Tuple of incorrect type (expected {GetType()})", "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } num = comparer.Compare(m_Item4, tuple.m_Item4); if (num != 0) { return num; } num = comparer.Compare(m_Item5, tuple.m_Item5); if (num != 0) { return num; } num = comparer.Compare(m_Item6, tuple.m_Item6); if (num != 0) { return num; } return comparer.Compare(m_Item7, tuple.m_Item7); } public override int GetHashCode() { return GetHashCode(EqualityComparer<object>.Default); } int IComparable.CompareTo(object? obj) { return CompareTo(obj, Comparer<object>.Default); } int System.ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string System.ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(')'); return sb.ToString(); } } [Serializable] public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IComparable, System.ITupleInternal, ITuple where TRest : notnull { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; private readonly T5 m_Item5; private readonly T6 m_Item6; private readonly T7 m_Item7; private readonly TRest m_Rest; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public T6 Item6 => m_Item6; public T7 Item7 => m_Item7; public TRest Rest => m_Rest; int ITuple.Length => 7 + ((System.ITupleInternal)(object)Rest).Length; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, 6 => Item7, _ => ((System.ITupleInternal)(object)Rest)[index - 7], }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { if (!(rest is System.ITupleInternal)) { throw new ArgumentException("Last argument is not a tuple"); } m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; m_Rest = rest; } public override bool Equals(object? obj) { return Equals(obj, EqualityComparer<object>.Default); } private bool Equals(object? other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3) && comparer.Equals(m_Item4, tuple.m_Item4) && comparer.Equals(m_Item5, tuple.m_Item5) && comparer.Equals(m_Item6, tuple.m_Item6) && comparer.Equals(m_Item7, tuple.m_Item7)) { return comparer.Equals(m_Rest, tuple.m_Rest); } return false; } int IComparable.CompareTo(object? obj) { return CompareTo(obj, Comparer<object>.Default); } private int CompareTo(object? other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> tuple)) { throw new ArgumentException($"Tuple of incorrect type (expected {GetType()})", "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } num = comparer.Compare(m_Item4, tuple.m_Item4); if (num != 0) { return num; } num = comparer.Compare(m_Item5, tuple.m_Item5); if (num != 0) { return num; } num = comparer.Compare(m_Item6, tuple.m_Item6); if (num != 0) { return num; } num = comparer.Compare(m_Item7, tuple.m_Item7); if (num != 0) { return num; } return comparer.Compare(m_Rest, tuple.m_Rest); } public override int GetHashCode() { return GetHashCode(EqualityComparer<object>.Default); } private int GetHashCode(IEqualityComparer comparer) { System.ITupleInternal tupleInternal = (System.ITupleInternal)(object)m_Rest; if (tupleInternal.Length >= 8) { return tupleInternal.GetHashCode(comparer); } return (8 - tupleInternal.Length) switch { 1 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 2 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 3 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 4 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 5 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 6 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 7 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), _ => -1, }; } int System.ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string System.ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(", "); return ((System.ITupleInternal)(object)m_Rest).ToString(sb); } } } namespace System.Runtime.CompilerServices { internal interface ITuple { int Length { get; } object? this[int index] { get; } } } namespace Mono.CompilerServices.SymbolWriter { public class MonoSymbolFileException : Exception { public MonoSymbolFileException() { } public MonoSymbolFileException(string message, params object[] args) : base(string.Format(message, args)) { } public MonoSymbolFileException(string message, Exception innerException) : base(message, innerException) { } } internal sealed class MyBinaryWriter : BinaryWriter { public MyBinaryWriter(Stream stream) : base(stream) { } public void WriteLeb128(int value) { Write7BitEncodedInt(value); } } internal class MyBinaryReader : BinaryReader { public MyBinaryReader(Stream stream) : base(stream) { } public int ReadLeb128() { return Read7BitEncodedInt(); } public string ReadString(int offset) { long position = BaseStream.Position; BaseStream.Position = offset; string result = ReadString(); BaseStream.Position = position; return result; } } public interface ISourceFile { SourceFileEntry Entry { get; } } public interface ICompileUnit { CompileUnitEntry Entry { get; } } public interface IMethodDef { string Name { get; } int Token { get; } } public class MonoSymbolFile : IDisposable { private List<MethodEntry> methods = new List<MethodEntry>(); private List<SourceFileEntry> sources = new List<SourceFileEntry>(); private List<CompileUnitEntry> comp_units = new List<CompileUnitEntry>(); private Dictionary<int, AnonymousScopeEntry> anonymous_scopes; private OffsetTable ot; private int last_type_index; private int last_method_index; private int last_namespace_index; public readonly int MajorVersion = 50; public readonly int MinorVersion; public int NumLineNumbers; private MyBinaryReader reader; private Dictionary<int, SourceFileEntry> source_file_hash; private Dictionary<int, CompileUnitEntry> compile_unit_hash; private List<MethodEntry> method_list; private Dictionary<int, MethodEntry> method_token_hash; private Dictionary<string, int> source_name_hash; private Guid guid; internal int LineNumberCount; internal int LocalCount; internal int StringSize; internal int LineNumberSize; internal int ExtendedLineNumberSize; public int CompileUnitCount => ot.CompileUnitCount; public int SourceCount => ot.SourceCount; public int MethodCount => ot.MethodCount; public int TypeCount => ot.TypeCount; public int AnonymousScopeCount => ot.AnonymousScopeCount; public int NamespaceCount => last_namespace_index; public Guid Guid => guid; public OffsetTable OffsetTable => ot; public SourceFileEntry[] Sources { get { if (reader == null) { throw new InvalidOperationException(); } SourceFileEntry[] array = new SourceFileEntry[SourceCount]; for (int i = 0; i < SourceCount; i++) { array[i] = GetSourceFile(i + 1); } return array; } } public CompileUnitEntry[] CompileUnits { get { if (reader == null) { throw new InvalidOperationException(); } CompileUnitEntry[] array = new CompileUnitEntry[CompileUnitCount]; for (int i = 0; i < CompileUnitCount; i++) { array[i] = GetCompileUnit(i + 1); } return array; } } public MethodEntry[] Methods { get { if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); MethodEntry[] array = new MethodEntry[MethodCount]; method_list.CopyTo(array, 0); return array; } } } internal MyBinaryReader BinaryReader { get { if (reader == null) { throw new InvalidOperationException(); } return reader; } } public MonoSymbolFile() { ot = new OffsetTable(); } public int AddSource(SourceFileEntry source) { sources.Add(source); return sources.Count; } public int AddCompileUnit(CompileUnitEntry entry) { comp_units.Add(entry); return comp_units.Count; } public void AddMethod(MethodEntry entry) { methods.Add(entry); } public MethodEntry DefineMethod(CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id) { if (reader != null) { throw new InvalidOperationException(); } MethodEntry methodEntry = new MethodEntry(this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id); AddMethod(methodEntry); return methodEntry; } internal void DefineAnonymousScope(int id) { if (reader != null) { throw new InvalidOperationException(); } if (anonymous_scopes == null) { anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>(); } anonymous_scopes.Add(id, new AnonymousScopeEntry(id)); } internal void DefineCapturedVariable(int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind) { if (reader != null) { throw new InvalidOperationException(); } anonymous_scopes[scope_id].AddCapturedVariable(name, captured_name, kind); } internal void DefineCapturedScope(int scope_id, int id, string captured_name) { if (reader != null) { throw new InvalidOperationException(); } anonymous_scopes[scope_id].AddCapturedScope(id, captured_name); } internal int GetNextTypeIndex() { return ++last_type_index; } internal int GetNextMethodIndex() { return ++last_method_index; } internal int GetNextNamespaceIndex() { return ++last_namespace_index; } private void Write(MyBinaryWriter bw, Guid guid) { bw.Write(5037318119232611860L); bw.Write(MajorVersion); bw.Write(MinorVersion); bw.Write(guid.ToByteArray()); long position = bw.BaseStream.Position; ot.Write(bw, MajorVersion, MinorVersion); methods.Sort(); for (int i = 0; i < methods.Count; i++) { methods[i].Index = i + 1; } ot.DataSectionOffset = (int)bw.BaseStream.Position; foreach (SourceFileEntry source in sources) { source.WriteData(bw); } foreach (CompileUnitEntry comp_unit in comp_units) { comp_unit.WriteData(bw); } foreach (MethodEntry method in methods) { method.WriteData(this, bw); } ot.DataSectionSize = (int)bw.BaseStream.Position - ot.DataSectionOffset; ot.MethodTableOffset = (int)bw.BaseStream.Position; for (int j = 0; j < methods.Count; j++) { methods[j].Write(bw); } ot.MethodTableSize = (int)bw.BaseStream.Position - ot.MethodTableOffset; ot.SourceTableOffset = (int)bw.BaseStream.Position; for (int k = 0; k < sources.Count; k++) { sources[k].Write(bw); } ot.SourceTableSize = (int)bw.BaseStream.Position - ot.SourceTableOffset; ot.CompileUnitTableOffset = (int)bw.BaseStream.Position; for (int l = 0; l < comp_units.Count; l++) { comp_units[l].Write(bw); } ot.CompileUnitTableSize = (int)bw.BaseStream.Position - ot.CompileUnitTableOffset; ot.AnonymousScopeCount = ((anonymous_scopes != null) ? anonymous_scopes.Count : 0); ot.AnonymousScopeTableOffset = (int)bw.BaseStream.Position; if (anonymous_scopes != null) { foreach (AnonymousScopeEntry value in anonymous_scopes.Values) { value.Write(bw); } } ot.AnonymousScopeTableSize = (int)bw.BaseStream.Position - ot.AnonymousScopeTableOffset; ot.TypeCount = last_type_index; ot.MethodCount = methods.Count; ot.SourceCount = sources.Count; ot.CompileUnitCount = comp_units.Count; ot.TotalFileSize = (int)bw.BaseStream.Position; bw.Seek((int)position, SeekOrigin.Begin); ot.Write(bw, MajorVersion, MinorVersion); bw.Seek(0, SeekOrigin.End); } public void CreateSymbolFile(Guid guid, FileStream fs) { if (reader != null) { throw new InvalidOperationException(); } Write(new MyBinaryWriter(fs), guid); } private MonoSymbolFile(Stream stream) { reader = new MyBinaryReader(stream); try { long num = reader.ReadInt64(); int num2 = reader.ReadInt32(); int num3 = reader.ReadInt32(); if (num != 5037318119232611860L) { throw new MonoSymbolFileException("Symbol file is not a valid"); } if (num2 != 50) { throw new MonoSymbolFileException("Symbol file has version {0} but expected {1}", num2, 50); } if (num3 != 0) { throw new MonoSymbolFileException("Symbol file has version {0}.{1} but expected {2}.{3}", num2, num3, 50, 0); } MajorVersion = num2; MinorVersion = num3; guid = new Guid(reader.ReadBytes(16)); ot = new OffsetTable(reader, num2, num3); } catch (Exception innerException) { throw new MonoSymbolFileException("Cannot read symbol file", innerException); } source_file_hash = new Dictionary<int, SourceFileEntry>(); compile_unit_hash = new Dictionary<int, CompileUnitEntry>(); } public static MonoSymbolFile ReadSymbolFile(Assembly assembly) { string mdbFilename = assembly.Location + ".mdb"; Guid moduleVersionId = assembly.GetModules()[0].ModuleVersionId; return ReadSymbolFile(mdbFilename, moduleVersionId); } public static MonoSymbolFile ReadSymbolFile(string mdbFilename) { return ReadSymbolFile(new FileStream(mdbFilename, FileMode.Open, FileAccess.Read)); } public static MonoSymbolFile ReadSymbolFile(string mdbFilename, Guid assemblyGuid) { MonoSymbolFile monoSymbolFile = ReadSymbolFile(mdbFilename); if (assemblyGuid != monoSymbolFile.guid) { throw new MonoSymbolFileException("Symbol file `{0}' does not match assembly", mdbFilename); } return monoSymbolFile; } public static MonoSymbolFile ReadSymbolFile(Stream stream) { return new MonoSymbolFile(stream); } public SourceFileEntry GetSourceFile(int index) { if (index < 1 || index > ot.SourceCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (source_file_hash.TryGetValue(index, out var value)) { return value; } long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1); value = new SourceFileEntry(this, reader); source_file_hash.Add(index, value); reader.BaseStream.Position = position; return value; } } public CompileUnitEntry GetCompileUnit(int index) { if (index < 1 || index > ot.CompileUnitCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (compile_unit_hash.TryGetValue(index, out var value)) { return value; } long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1); value = new CompileUnitEntry(this, reader); compile_unit_hash.Add(index, value); reader.BaseStream.Position = position; return value; } } private void read_methods() { lock (this) { if (method_token_hash == null) { method_token_hash = new Dictionary<int, MethodEntry>(); method_list = new List<MethodEntry>(); long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.MethodTableOffset; for (int i = 0; i < MethodCount; i++) { MethodEntry methodEntry = new MethodEntry(this, reader, i + 1); method_token_hash.Add(methodEntry.Token, methodEntry); method_list.Add(methodEntry); } reader.BaseStream.Position = position; } } } public MethodEntry GetMethodByToken(int token) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); method_token_hash.TryGetValue(token, out var value); return value; } } public MethodEntry GetMethod(int index) { if (index < 1 || index > ot.MethodCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); return method_list[index - 1]; } } public int FindSource(string file_name) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (source_name_hash == null) { source_name_hash = new Dictionary<string, int>(); for (int i = 0; i < ot.SourceCount; i++) { SourceFileEntry sourceFile = GetSourceFile(i + 1); source_name_hash.Add(sourceFile.FileName, i); } } if (!source_name_hash.TryGetValue(file_name, out var value)) { return -1; } return value; } } public AnonymousScopeEntry GetAnonymousScope(int id) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (anonymous_scopes != null) { anonymous_scopes.TryGetValue(id, out var value); return value; } anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>(); reader.BaseStream.Position = ot.AnonymousScopeTableOffset; for (int i = 0; i < ot.AnonymousScopeCount; i++) { AnonymousScopeEntry value = new AnonymousScopeEntry(reader); anonymous_scopes.Add(value.ID, value); } return anonymous_scopes[id]; } } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { if (disposing && reader != null) { reader.Close(); reader = null; } } } public class OffsetTable { [Flags] public enum Flags { IsAspxSource = 1, WindowsFileNames = 2 } public const int MajorVersion = 50; public const int MinorVersion = 0; public const long Magic = 5037318119232611860L; public int TotalFileSize; public int DataSectionOffset; public int DataSectionSize; public int CompileUnitCount; public int CompileUnitTableOffset; public int CompileUnitTableSize; public int SourceCount; public int SourceTableOffset; public int SourceTableSize; public int MethodCount; public int MethodTableOffset; public int MethodTableSize; public int TypeCount; public int AnonymousScopeCount; public int AnonymousScopeTableOffset; public int AnonymousScopeTableSize; public Flags FileFlags; public int LineNumberTable_LineBase = -1; public int LineNumberTable_LineRange = 8; public int LineNumberTable_OpcodeBase = 9; internal OffsetTable() { int platform = (int)Environment.OSVersion.Platform; if (platform != 4 && platform != 128) { FileFlags |= Flags.WindowsFileNames; } } internal OffsetTable(BinaryReader reader, int major_version, int minor_version) { TotalFileSize = reader.ReadInt32(); DataSectionOffset = reader.ReadInt32(); DataSectionSize = reader.ReadInt32(); CompileUnitCount = reader.ReadInt32(); CompileUnitTableOffset = reader.ReadInt32(); CompileUnitTableSize = reader.ReadInt32(); SourceCount = reader.ReadInt32(); SourceTableOffset = reader.ReadInt32(); SourceTableSize = reader.ReadInt32(); MethodCount = reader.ReadInt32(); MethodTableOffset = reader.ReadInt32(); MethodTableSize = reader.ReadInt32(); TypeCount = reader.ReadInt32(); AnonymousScopeCount = reader.ReadInt32(); AnonymousScopeTableOffset = reader.ReadInt32(); AnonymousScopeTableSize = reader.ReadInt32(); LineNumberTable_LineBase = reader.ReadInt32(); LineNumberTable_LineRange = reader.ReadInt32(); LineNumberTable_OpcodeBase = reader.ReadInt32(); FileFlags = (Flags)reader.ReadInt32(); } internal void Write(BinaryWriter bw, int major_version, int minor_version) { bw.Write(TotalFileSize); bw.Write(DataSectionOffset); bw.Write(DataSectionSize); bw.Write(CompileUnitCount); bw.Write(CompileUnitTableOffset); bw.Write(CompileUnitTableSize); bw.Write(SourceCount); bw.Write(SourceTableOffset); bw.Write(SourceTableSize); bw.Write(MethodCount); bw.Write(MethodTableOffset); bw.Write(MethodTableSize); bw.Write(TypeCount); bw.Write(AnonymousScopeCount); bw.Write(AnonymousScopeTableOffset); bw.Write(AnonymousScopeTableSize); bw.Write(LineNumberTable_LineBase); bw.Write(LineNumberTable_LineRange); bw.Write(LineNumberTable_OpcodeBase); bw.Write((int)FileFlags); } public override string ToString() { return $"OffsetTable [{TotalFileSize} - {DataSectionOffset}:{DataSectionSize} - {SourceCount}:{SourceTableOffset}:{SourceTableSize} - {MethodCount}:{MethodTableOffset}:{MethodTableSize} - {TypeCount}]"; } } public class LineNumberEntry { public sealed class LocationComparer : IComparer<LineNumberEntry> { public static readonly LocationComparer Default = new LocationComparer(); public int Compare(LineNumberEntry l1, LineNumberEntry l2) { if (l1.Row != l2.Row) { int row = l1.Row; return row.CompareTo(l2.Row); } return l1.Column.CompareTo(l2.Column); } } public readonly int Row; public int Column; public int EndRow; public int EndColumn; public readonly int File; public readonly int Offset; public readonly bool IsHidden; public static readonly LineNumberEntry Null = new LineNumberEntry(0, 0, 0, 0); public LineNumberEntry(int file, int row, int column, int offset) : this(file, row, column, offset, is_hidden: false) { } public LineNumberEntry(int file, int row, int offset) : this(file, row, -1, offset, is_hidden: false) { } public LineNumberEntry(int file, int row, int column, int offset, bool is_hidden) : this(file, row, column, -1, -1, offset, is_hidden) { } public LineNumberEntry(int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden) { File = file; Row = row; Column = column; EndRow = end_row; EndColumn = end_column; Offset = offset; IsHidden = is_hidden; } public override string ToString() { return string.Format("[Line {0}:{1,2}-{3,4}:{5}]", File, Row, Column, EndRow, EndColumn, Offset); } } public class CodeBlockEntry { public enum Type { Lexical = 1, CompilerGenerated, IteratorBody, IteratorDispatcher } public int Index; public int Parent; public Type BlockType; public int StartOffset; public int EndOffset; public CodeBlockEntry(int index, int parent, Type type, int start_offset) { Index = index; Parent = parent; BlockType = type; StartOffset = start_offset; } internal CodeBlockEntry(int index, MyBinaryReader reader) { Index = index; int num = reader.ReadLeb128(); BlockType = (Type)(num & 0x3F); Parent = reader.ReadLeb128(); StartOffset = reader.ReadLeb128(); EndOffset = reader.ReadLeb128(); if (((uint)num & 0x40u) != 0) { int num2 = reader.ReadInt16(); reader.BaseStream.Position += num2; } } public void Close(int end_offset) { EndOffset = end_offset; } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128((int)BlockType); bw.WriteLeb128(Parent); bw.WriteLeb128(StartOffset); bw.WriteLeb128(EndOffset); } public override string ToString() { return $"[CodeBlock {Index}:{Parent}:{BlockType}:{StartOffset}:{EndOffset}]"; } } public struct LocalVariableEntry { public readonly int Index; public readonly string Name; public readonly int BlockIndex; public LocalVariableEntry(int index, string name, int block) { Index = index; Name = name; BlockIndex = block; } internal LocalVariableEntry(MonoSymbolFile file, MyBinaryReader reader) { Index = reader.ReadLeb128(); Name = reader.ReadString(); BlockIndex = reader.ReadLeb128(); } internal void Write(MonoSymbolFile file, MyBinaryWriter bw) { bw.WriteLeb128(Index); bw.Write(Name); bw.WriteLeb128(BlockIndex); } public override string ToString() { return $"[LocalVariable {Name}:{Index}:{BlockIndex - 1}]"; } } public struct CapturedVariable { public enum CapturedKind : byte { Local, Parameter, This } public readonly string Name; public readonly string CapturedName; public readonly CapturedKind Kind; public CapturedVariable(string name, string captured_name, CapturedKind kind) { Name = name; CapturedName = captured_name; Kind = kind; } internal CapturedVariable(MyBinaryReader reader) { Name = reader.ReadString(); CapturedName = reader.ReadString(); Kind = (CapturedKind)reader.ReadByte(); } internal void Write(MyBinaryWriter bw) { bw.Write(Name); bw.Write(CapturedName); bw.Write((byte)Kind); } public override string ToString() { return $"[CapturedVariable {Name}:{CapturedName}:{Kind}]"; } } public struct CapturedScope { public readonly int Scope; public readonly string CapturedName; public CapturedScope(int scope, string captured_name) { Scope = scope; CapturedName = captured_name; } internal CapturedScope(MyBinaryReader reader) { Scope = reader.ReadLeb128(); CapturedName = reader.ReadString(); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(Scope); bw.Write(CapturedName); } public override string ToString() { return $"[CapturedScope {Scope}:{CapturedName}]"; } } public struct ScopeVariable { public readonly int Scope; public readonly int Index; public ScopeVariable(int scope, int index) { Scope = scope; Index = index; } internal ScopeVariable(MyBinaryReader reader) { Scope = reader.ReadLeb128(); Index = reader.ReadLeb128(); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(Scope); bw.WriteLeb128(Index); } public override string ToString() { return $"[ScopeVariable {Scope}:{Index}]"; } } public class AnonymousScopeEntry { public readonly int ID; private List<CapturedVariable> captured_vars = new List<CapturedVariable>(); private List<CapturedScope> captured_scopes = new List<CapturedScope>(); public CapturedVariable[] CapturedVariables { get { CapturedVariable[] array = new CapturedVariable[captured_vars.Count]; captured_vars.CopyTo(array, 0); return array; } } public CapturedScope[] CapturedScopes { get { CapturedScope[] array = new CapturedScope[captured_scopes.Count]; captured_scopes.CopyTo(array, 0); return array; } } public AnonymousScopeEntry(int id) { ID = id; } internal AnonymousScopeEntry(MyBinaryReader reader) { ID = reader.ReadLeb128(); int num = reader.ReadLeb128(); for (int i = 0; i < num; i++) { captured_vars.Add(new CapturedVariable(reader)); } int num2 = reader.ReadLeb128(); for (int j = 0; j < num2; j++) { captured_scopes.Add(new CapturedScope(reader)); } } internal void AddCapturedVariable(string name, string captured_name, CapturedVariable.CapturedKind kind) { captured_vars.Add(new CapturedVariable(name, captured_name, kind)); } internal void AddCapturedScope(int scope, string captured_name) { captured_scopes.Add(new CapturedScope(scope, captured_name)); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(ID); bw.WriteLeb128(captured_vars.Count); foreach (CapturedVariable captured_var in captured_vars) { captured_var.Write(bw); } bw.WriteLeb128(captured_scopes.Count); foreach (CapturedScope captured_scope in captured_scopes) { captured_scope.Write(bw); } } public override string ToString() { return $"[AnonymousScope {ID}]"; } } public class CompileUnitEntry : ICompileUnit { public readonly int Index; private int DataOffset; private MonoSymbolFile file; private SourceFileEntry source; private List<SourceFileEntry> include_files; private List<NamespaceEntry> namespaces; private bool creating; public static int Size => 8; CompileUnitEntry ICompileUnit.Entry => this; public SourceFileEntry SourceFile { get { if (creating) { return source; } ReadData(); return source; } } public NamespaceEntry[] Namespaces { get { ReadData(); NamespaceEntry[] array = new NamespaceEntry[namespaces.Count]; namespaces.CopyTo(array, 0); return array; } } public SourceFileEntry[] IncludeFiles { get { ReadData(); if (include_files == null) { return new SourceFileEntry[0]; } SourceFileEntry[] array = new SourceFileEntry[include_files.Count]; include_files.CopyTo(array, 0); return array; } } public CompileUnitEntry(MonoSymbolFile file, SourceFileEntry source) { this.file = file; this.source = source; Index = file.AddCompileUnit(this); creating = true; namespaces = new List<NamespaceEntry>(); } public void AddFile(SourceFileEntry file) { if (!creating) { throw new InvalidOperationException(); } if (include_files == null) { include_files = new List<SourceFileEntry>(); } include_files.Add(file); } public int DefineNamespace(string name, string[] using_clauses, int parent) { if (!creating) { throw new InvalidOperationException(); } int nextNamespaceIndex = file.GetNextNamespaceIndex(); NamespaceEntry item = new NamespaceEntry(name, nextNamespaceIndex, using_clauses, parent); namespaces.Add(item); return nextNamespaceIndex; } internal void WriteData(MyBinaryWriter bw) { DataOffset = (int)bw.BaseStream.Position; bw.WriteLeb128(source.Index); int value = ((include_files != null) ? include_files.Count : 0); bw.WriteLeb128(value); if (include_files != null) { foreach (SourceFileEntry include_file in include_files) { bw.WriteLeb128(include_file.Index); } } bw.WriteLeb128(namespaces.Count); foreach (NamespaceEntry @namespace in namespaces) { @namespace.Write(file, bw); } } internal void Write(BinaryWriter bw) { bw.Write(Index); bw.Write(DataOffset); } internal CompileUnitEntry(MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32(); DataOffset = reader.ReadInt32(); } public void ReadAll() { ReadData(); } private void ReadData() { if (creating) { throw new InvalidOperationException(); } lock (file) { if (namespaces != null) { return; } MyBinaryReader binaryReader = file.BinaryReader; int num = (int)binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = DataOffset; int index = binaryReader.ReadLeb128(); source = file.GetSourceFile(index); int num2 = binaryReader.ReadLeb128(); if (num2 > 0) { include_files = new List<SourceFileEntry>(); for (int i = 0; i < num2; i++) { include_files.Add(file.GetSourceFile(binaryReader.ReadLeb128())); } } int num3 = binaryReader.ReadLeb128(); namespaces = new List<NamespaceEntry>(); for (int j = 0; j < num3; j++) { namespaces.Add(new NamespaceEntry(file, binaryReader)); } binaryReader.BaseStream.Position = num; } } } public class SourceFileEntry { public readonly int Index; private int DataOffset; private MonoSymbolFile file; private string file_name; private byte[] guid; private byte[] hash; private bool creating; private bool auto_generated; private readonly string sourceFile; public static int Size => 8; public byte[] Checksum => hash; public string FileName { get { return file_name; } set { file_name = value; } } public bool AutoGenerated => auto_generated; public SourceFileEntry(MonoSymbolFile file, string file_name) { this.file = file; this.file_name = file_name; Index = file.AddSource(this); creating = true; } public SourceFileEntry(MonoSymbolFile file, string sourceFile, byte[] guid, byte[] checksum) : this(file, sourceFile, sourceFile, guid, checksum) { } public SourceFileEntry(MonoSymbolFile file, string fileName, string sourceFile, byte[] guid, byte[] checksum) : this(file, fileName) { this.guid = guid; hash = checksum; this.sourceFile = sourceFile; } internal void WriteData(MyBinaryWriter bw) { DataOffset = (int)bw.BaseStream.Position; bw.Write(file_name); if (guid == null) { guid = new byte[16]; } if (hash == null) { try { using FileStream inputStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read); MD5 mD = MD5.Create(); hash = mD.ComputeHash(inputStream); } catch { hash = new byte[16]; } } bw.Write(guid); bw.Write(hash); bw.Write(auto_generated ? ((byte)1) : ((byte)0)); } internal void Write(BinaryWriter bw) { bw.Write(Index); bw.Write(DataOffset); } internal SourceFileEntry(MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32(); DataOffset = reader.ReadInt32(); int num = (int)reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; sourceFile = (file_name = reader.ReadString()); guid = reader.ReadBytes(16); hash = reader.ReadBytes(16); auto_generated = reader.ReadByte() == 1; reader.BaseStream.Position = num; } public void SetAutoGenerated() { if (!creating) { throw new InvalidOperationException(); } auto_generated = true; file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource; } public bool CheckChecksum() { try { using FileStream inputStream = new FileStream(sourceFile, FileMode.Open); byte[] array = MD5.Create().ComputeHash(inputStream); for (int i = 0; i < 16; i++) { if (array[i] != hash[i]) { return false; } } return true; } catch { return false; } } public override string ToString() { return $"SourceFileEntry ({Index}:{DataOffset})"; } } public class LineNumberTable { protected LineNumberEntry[] _line_numbers; public readonly int LineBase; public readonly int LineRange; public readonly byte OpcodeBase; public readonly int MaxAddressIncrement; public const int Default_LineBase = -1; public const int Default_LineRange = 8; public const byte Default_OpcodeBase = 9; public const byte DW_LNS_copy = 1; public const byte DW_LNS_advance_pc = 2; public const byte DW_LNS_advance_line = 3; public const byte DW_LNS_set_file = 4; public const byte DW_LNS_const_add_pc = 8; public const byte DW_LNE_end_sequence = 1; public const byte DW_LNE_MONO_negate_is_hidden = 64; internal const byte DW_LNE_MONO__extensions_start = 64; internal const byte DW_LNE_MONO__extensions_end = 127; public LineNumberEntry[] LineNumbers => _line_numbers; protected LineNumberTable(MonoSymbolFile file) { LineBase = file.OffsetTable.LineNumberTable_LineBase; LineRange = file.OffsetTable.LineNumberTable_LineRange; OpcodeBase = (byte)file.OffsetTable.LineNumberTable_OpcodeBase; MaxAddressIncrement = (255 - OpcodeBase) / LineRange; } internal LineNumberTable(MonoSymbolFile file, LineNumberEntry[] lines) : this(file) { _line_numbers = lines; } internal void Write(MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo) { int num = (int)bw.BaseStream.Position; bool flag = false; int num2 = 1; int num3 = 0; int num4 = 1; for (int i = 0; i < LineNumbers.Length; i++) { int num5 = LineNumbers[i].Row - num2; int num6 = LineNumbers[i].Offset - num3; if (LineNumbers[i].File != num4) { bw.Write((byte)4); bw.WriteLeb128(LineNumbers[i].File); num4 = LineNumbers[i].File; } if (LineNumbers[i].IsHidden != flag) { bw.Write((byte)0); bw.Write((byte)1); bw.Write((byte)64); flag = LineNumbers[i].IsHidden; } if (num6 >= MaxAddressIncrement) { if (num6 < 2 * MaxAddressIncrement) { bw.Write((byte)8); num6 -= MaxAddressIncrement; } else { bw.Write((byte)2); bw.WriteLeb128(num6); num6 = 0; } } if (num5 < LineBase || num5 >= LineBase + LineRange) { bw.Write((byte)3); bw.WriteLeb128(num5); if (num6 != 0) { bw.Write((byte)2); bw.WriteLeb128(num6); } bw.Write((byte)1); } else { byte value = (byte)(num5 - LineBase + LineRange * num6 + OpcodeBase); bw.Write(value); } num2 = LineNumbers[i].Row; num3 = LineNumbers[i].Offset; } bw.Write((byte)0); bw.Write((byte)1); bw.Write((byte)1); if (hasColumnsInfo) { for (int j = 0; j < LineNumbers.Length; j++) { LineNumberEntry lineNumberEntry = LineNumbers[j]; if (lineNumberEntry.Row >= 0) { bw.WriteLeb128(lineNumberEntry.Column); } } } if (hasEndInfo) { for (int k = 0; k < LineNumbers.Length; k++) { LineNumberEntry lineNumberEntry2 = LineNumbers[k]; if (lineNumberEntry2.EndRow == -1 || lineNumberEntry2.EndColumn == -1 || lineNumberEntry2.Row > lineNumberEntry2.EndRow) { bw.WriteLeb128(16777215); continue; } bw.WriteLeb128(lineNumberEntry2.EndRow - lineNumberEntry2.Row); bw.WriteLeb128(lineNumberEntry2.EndColumn); } } file.ExtendedLineNumberSize += (int)bw.BaseStream.Position - num; } internal static LineNumberTable Read(MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo) { LineNumberTable lineNumberTable = new LineNumberTable(file); lineNumberTable.DoRead(file, br, readColumnsInfo, readEndInfo); return lineNumberTable; } private void DoRead(MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds) { List<LineNumberEntry> list = new List<LineNumberEntry>(); bool flag = false; bool flag2 = false; int num = 1; int num2 = 0; int file2 = 1; while (true) { byte b = br.ReadByte(); if (b == 0) { byte b2 = br.ReadByte(); long position = br.BaseStream.Position + b2; b = br.ReadByte(); switch (b) { case 1: { if (flag2) { list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); } _line_numbers = list.ToArray(); if (includesColumns) { for (int i = 0; i < _line_numbers.Length; i++) { LineNumberEntry lineNumberEntry = _line_numbers[i]; if (lineNumberEntry.Row >= 0) { lineNumberEntry.Column = br.ReadLeb128(); } } } if (!includesEnds) { return; } for (int j = 0; j < _line_numbers.Length; j++) { LineNumberEntry lineNumberEntry2 = _line_numbers[j]; int num3 = br.ReadLeb128(); if (num3 == 16777215) { lineNumberEntry2.EndRow = -1; lineNumberEntry2.EndColumn = -1; } else { lineNumberEntry2.EndRow = lineNumberEntry2.Row + num3; lineNumberEntry2.EndColumn = br.ReadLeb128(); } } return; } case 64: flag = !flag; flag2 = true; break; default: throw new MonoSymbolFileException("Unknown extended opcode {0:x}", b); case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: break; } br.BaseStream.Position = position; } else if (b < OpcodeBase) { switch (b) { case 1: list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); flag2 = false; break; case 2: num2 += br.ReadLeb128(); flag2 = true; break; case 3: num += br.ReadLeb128(); flag2 = true; break; case 4: file2 = br.ReadLeb128(); flag2 = true; break; case 8: num2 += MaxAddressIncrement; flag2 = true; break; default: throw new MonoSymbolFileException("Unknown standard opcode {0:x} in LNT", b); } } else { b -= OpcodeBase; num2 += b / LineRange; num += LineBase + b % LineRange; list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); flag2 = false; } } } public bool GetMethodBounds(out LineNumberEntry start, out LineNumberEntry end) { if (_line_numbers.Length > 1) { start = _line_numbers[0]; end = _line_numbers[_line_numbers.Length - 1]; return true; } start = LineNumberEntry.Null; end = LineNumberEntry.Null; return false; } } public class MethodEntry : IComparable { [Flags] public enum Flags { LocalNamesAmbiguous = 1, ColumnsInfoIncluded = 2, EndInfoIncluded = 4 } public readonly int CompileUnitIndex; public readonly int Token; public readonly int NamespaceID; private int DataOffset; private int LocalVariableTableOffset; private int LineNumberTableOffset; private int CodeBlockTableOffset; private int ScopeVariableTableOffset; private int RealNameOffset; private Flags flags; private int index; public readonly CompileUnitEntry CompileUnit; private LocalVariableEntry[] locals; private CodeBlockEntry[] code_blocks; private ScopeVariable[] scope_vars; private LineNumberTable lnt; private string real_name; public readonly MonoSymbolFile SymbolFile; public const int Size = 12; public Flags MethodFlags => flags; public int Index { get { return index; } set { index = value; } } internal MethodEntry(MonoSymbolFile file, MyBinaryReader reader, int index) { SymbolFile = file; this.index = index; Token = reader.ReadInt32(); DataOffset = reader.ReadInt32(); LineNumberTableOffset = reader.ReadInt32(); long position = reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; CompileUnitIndex = reader.ReadLeb128(); LocalVariableTableOffset = reader.ReadLeb128(); NamespaceID = reader.ReadLeb128(); CodeBlockTableOffset = reader.ReadLeb128(); ScopeVariableTableOffset = reader.ReadLeb128(); RealNameOffset = reader.ReadLeb128(); flags = (Flags)reader.ReadLeb128(); reader.BaseStream.Position = position; CompileUnit = file.GetCompileUnit(CompileUnitIndex); } internal MethodEntry(MonoSymbolFile file, CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, Flags flags, int namespace_id) { SymbolFile = file; this.real_name = real_name; this.locals = locals; this.code_blocks = code_blocks; this.scope_vars = scope_vars; this.flags = flags; index = -1; Token = token; CompileUnitIndex = comp_unit.Index; CompileUnit = comp_unit; NamespaceID = namespace_id; CheckLineNumberTable(lines); lnt = new LineNumberTable(file, lines); file.NumLineNumbers += lines.Length; int num = ((locals != null) ? locals.Length : 0); if (num <= 32) { for (int i = 0; i < num; i++) { string name = locals[i].Name; for (int j = i + 1; j < num; j++) { if (locals[j].Name == name) { flags |= Flags.LocalNamesAmbiguous; return; } } } return; } Dictionary<string, LocalVariableEntry> dictionary = new Dictionary<string, LocalVariableEntry>(); for (int k = 0; k < locals.Length; k++) { LocalVariableEntry value = locals[k]; if (dictionary.ContainsKey(value.Name)) { flags |= Flags.LocalNamesAmbiguous; break; } dictionary.Add(value.Name, value); } } private static void CheckLineNumberTable(LineNumberEntry[] line_numbers) { int num = -1; int num2 = -1; if (line_numbers == null) { return; } foreach (LineNumberEntry lineNumberEntry in line_numbers) { if (lineNumberEntry.Equals(LineNumberEntry.Null)) { throw new MonoSymbolFileException(); } if (lineNumberEntry.Offset < num) { throw new MonoSymbolFileException(); } if (lineNumberEntry.Offset > num) { num2 = lineNumberEntry.Row; num = lineNumberEntry.Offset; } else if (lineNumberEntry.Row > num2) { num2 = lineNumberEntry.Row; } } } internal void Write(MyBinaryWriter bw) { if (index <= 0 || DataOffset == 0) { throw new InvalidOperationException(); } bw.Write(Token); bw.Write(DataOffset); bw.Write(LineNumberTableOffset); } internal void WriteData(MonoSymbolFile file, MyBinaryWriter bw) { if (index <= 0) { throw new InvalidOperationException(); } LocalVariableTableOffset = (int)bw.BaseStream.Position; int num = ((locals != null) ? locals.Length : 0); bw.WriteLeb128(num); for (int i = 0; i < num; i++) { locals[i].Write(file, bw); } file.LocalCount += num; CodeBlockTableOffset = (int)bw.BaseStream.Position; int num2 = ((code_blocks != null) ? code_blocks.Length : 0); bw.WriteLeb128(num2); for (int j = 0; j < num2; j++) { code_blocks[j].Write(bw); } ScopeVariableTableOffset = (int)bw.BaseStream.Position; int num3 = ((scope_vars != null) ? scope_vars.Length : 0); bw.WriteLeb128(num3); for (int k = 0; k < num3; k++) { scope_vars[k].Write(bw); } if (real_name != null) { RealNameOffset = (int)bw.BaseStream.Position; bw.Write(real_name); } LineNumberEntry[] lineNumbers = lnt.LineNumbers; foreach (LineNumberEntry lineNumberEntry in lineNumbers) { if (lineNumberEntry.EndRow != -1 || lineNumberEntry.EndColumn != -1) { flags |= Flags.EndInfoIncluded; } } LineNumberTableOffset = (int)bw.BaseStream.Position; lnt.Write(file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); DataOffset = (int)bw.BaseStream.Position; bw.WriteLeb128(CompileUnitIndex); bw.WriteLeb128(LocalVariableTableOffset); bw.WriteLeb128(NamespaceID); bw.WriteLeb128(CodeBlockTableOffset); bw.WriteLeb128(ScopeVariableTableOffset); bw.WriteLeb128(RealNameOffset); bw.WriteLeb128((int)flags); } public void ReadAll() { GetLineNumberTable(); GetLocals(); GetCodeBlocks(); GetScopeVariables(); GetRealName(); } public LineNumberTable GetLineNumberTable() { lock (SymbolFile) { if (lnt != null) { return lnt; } if (LineNumberTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = LineNumberTableOffset; lnt = LineNumberTable.Read(SymbolFile, binaryReader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); binaryReader.BaseStream.Position = position; return lnt; } } public LocalVariableEntry[] GetLocals() { lock (SymbolFile) { if (locals != null) { return locals; } if (LocalVariableTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = LocalVariableTableOffset; int num = binaryReader.ReadLeb128(); locals = new LocalVariableEntry[num]; for (int i = 0; i < num; i++) { locals[i] = new LocalVariableEntry(SymbolFile, binaryReader); } binaryReader.BaseStream.Position = position; return locals; } } public CodeBlockEntry[] GetCodeBlocks() { lock (SymbolFile) { if (code_blocks != null) { return code_blocks; } if (CodeBlockTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = CodeBlockTableOffset; int num = binaryReader.ReadLeb128(); code_blocks = new CodeBlockEntry[num]; for (int i = 0; i < num; i++) { code_blocks[i] = new CodeBlockEntry(i, binaryReader); } binaryReader.BaseStream.Position = position; return code_blocks; } } public ScopeVariable[] GetScopeVariables() { lock (SymbolFile) { if (scope_vars != null) { return scope_vars; } if (ScopeVariableTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = ScopeVariableTableOffset; int num = binaryReader.ReadLeb128(); scope_vars = new ScopeVariable[num]; for (int i = 0; i < num; i++) { scope_vars[i] = new ScopeVariable(binaryReader); } binaryReader.BaseStream.Position = position; return scope_vars; } } public string GetRealName() { lock (SymbolFile) { if (real_name != null) { return real_name; } if (RealNameOffset == 0) { return null; } real_name = SymbolFile.BinaryReader.ReadString(RealNameOffset); return real_name; } } public int CompareTo(object obj) { MethodEntry methodEntry = (MethodEntry)obj; if (methodEntry.Token < Token) { return 1; } if (methodEntry.Token > Token) { return -1; } return 0; } public override string ToString() { return $"[Method {index}:{Token:x}:{CompileUnitIndex}:{CompileUnit}]"; } } public struct NamespaceEntry { public readonly string Name; public readonly int Index; public readonly int Parent; public readonly string[] UsingClauses; public NamespaceEntry(string name, int index, string[] using_clauses, int parent) { Name = name; Index = index; Parent = parent; UsingClauses = ((using_clauses != null) ? using_clauses : new string[0]); } internal NamespaceEntry(MonoSymbolFile file, MyBinaryReader reader) { Name = reader.ReadString(); Index = reader.ReadLeb128(); Parent = reader.ReadLeb128(); int num = reader.ReadLeb128(); UsingClauses = new string[num]; for (int i = 0; i < num; i++) { UsingClauses[i] = reader.ReadString(); } } internal void Write(MonoSymbolFile file, MyBinaryWriter bw) { bw.Write(Name); bw.WriteLeb128(Index); bw.WriteLeb128(Parent); bw.WriteLeb128(UsingClauses.Length); string[] usingClauses = UsingClauses; foreach (string value in usingClauses) { bw.Write(value); } } public override string ToString() { return $"[Namespace {Name}:{Index}:{Parent}]"; } } public class SourceMethodBuilder { private List<LocalVariableEntry> _locals; private List<CodeBlockEntry> _blocks; private List<ScopeVariable> _scope_vars; private Stack<CodeBlockEntry> _block_stack; private readonly List<LineNumberEntry> method_lines; private readonly ICompileUnit _comp_unit; private readonly int ns_id; private readonly IMethodDef method; public CodeBlockEntry[] Blocks { get { if (_blocks == null) { return new CodeBlockEntry[0]; } CodeBlockEntry[] array = new CodeBlockEntry[_blocks.Count]; _blocks.CopyTo(array, 0); return array; } } public CodeBlockEntry CurrentBlock { get { if (_block_stack != null && _block_stack.Count > 0) { return _block_stack.Peek(); } return null; } } public LocalVariableEntry[] Locals { get { if (_locals == null) { return new LocalVariableEntry[0]; } return _locals.ToArray(); } } public ICompileUnit SourceFile => _comp_unit; public ScopeVariable[] ScopeVariables { get { if (_scope_vars == null) { return new ScopeVariable[0]; } return _scope_vars.ToArray(); } } public SourceMethodBuilder(ICompileUnit comp_unit) { _comp_unit = comp_unit; method_lines = new List<LineNumberEntry>(); } public SourceMethodBuilder(ICompileUnit comp_unit, int ns_id, IMethodDef method) : this(comp_unit) { this.ns_id = ns_id; this.method = method; } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden) { MarkSequencePoint(offset, file, line, column, -1, -1, is_hidden); } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden) { LineNumberEntry lineNumberEntry = new LineNumberEntry(file?.Index ?? 0, line, column, end_line, end_column, offset, is_hidden); if (method_lines.Count > 0) { LineNumberEntry lineNumberEntry2 = method_lines[method_lines.Count - 1]; if (lineNumberEntry2.Offset == offset) { if (LineNumberEntry.LocationComparer.Default.Compare(lineNumberEntry, lineNumberEntry2) > 0) { method_lines[method_lines.Count - 1] = lineNumberEntry; } return; } } method_lines.Add(lineNumberEntry); } public void StartBlock(CodeBlockEntry.Type type, int start_offset) { StartBlock(type, start_offset, (_blocks == null) ? 1 : (_blocks.Count + 1)); } public void StartBlock(CodeBlockEntry.Type type, int start_offset, int scopeIndex) { if (_block_stack == null) { _block_stack = new Stack<CodeBlockEntry>(); } if (_blocks == null) { _blocks = new List<CodeBlockEntry>(); } int parent = ((CurrentBlock != null) ? CurrentBlock.Index : (-1)); CodeBlockEntry item = new CodeBlockEntry(scopeIndex, parent, type, start_offset); _block_stack.Push(item); _blocks.Add(item); } public void EndBlock(int end_offset) { _block_stack.Pop().Close(end_offset); } public void AddLocal(int index, string name) { if (_locals == null) { _locals = new List<LocalVariableEntry>(); } int block = ((CurrentBlock != null) ? CurrentBlock.Index : 0); _locals.Add(new LocalVariableEntry(index, name, block)); } public void AddScopeVariable(int scope, int index) { if (_scope_vars == null) { _scope_vars = new List<ScopeVariable>(); } _scope_vars.Add(new ScopeVariable(scope, index)); } public void DefineMethod(MonoSymbolFile file) { DefineMethod(file, method.Token); } public void DefineMethod(MonoSymbolFile file, int token) { CodeBlockEntry[] array = Blocks; if (array.Length != 0) { List<CodeBlockEntry> list = new List<CodeBlockEntry>(array.Length); int num = 0; for (int i = 0; i < array.Length; i++) { num = Math.Max(num, array[i].Index); } for (int j = 0; j < num; j++) { int num2 = j + 1; if (j < array.Length && array[j].Index == num2) { list.Add(array[j]); continue; } bool flag = false; for (int k = 0; k < array.Length; k++) { if (array[k].Index == num2) { list.Add(array[k]); flag = true; break; } } if (!flag) { list.Add(new CodeBlockEntry(num2, -1, CodeBlockEntry.Type.CompilerGenerated, 0)); } } array = list.ToArray(); } MethodEntry entry = new MethodEntry(file, _comp_unit.Entry, token, ScopeVariables, Locals, method_lines.ToArray(), array, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id); file.AddMethod(entry); } } } namespace Mono.Security.Cryptography { public sealed class CryptoConvert { private CryptoConvert() { } private static int ToInt32LE(byte[] bytes, int offset) { return (bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]; } private static uint ToUInt32LE(byte[] bytes, int offset) { return (uint)((bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]); } private static byte[] GetBytesLE(int val) { return new byte[4] { (byte)((uint)val & 0xFFu), (byte)((uint)(val >> 8) & 0xFFu), (byte)((uint)(val >> 16) & 0xFFu), (byte)((uint)(val >> 24) & 0xFFu) }; } private static byte[] Trim(byte[] array) { for (int i = 0; i < array.Length; i++) { if (array[i] != 0) { byte[] array2 = new byte[array.Length - i]; Buffer.BlockCopy(array, i, array2, 0, array2.Length); return array2; } } return null; } public static RSA FromCapiPrivateKeyBlob(byte[] blob) { return FromCapiPrivateKeyBlob(blob, 0); } public static RSA FromCapiPrivateKeyBlob(byte[] blob, int offset) { RSAParameters parametersFromCapiPrivateKeyBlob = GetParametersFromCapiPrivateKeyBlob(blob, offset); RSA rSA = null; try { rSA = RSA.Create(); rSA.ImportParameters(parametersFromCapiPrivateKeyBlob); } catch (CryptographicException ex) { try { rSA = new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore }); rSA.ImportParameters(parametersFromCapiPrivateKeyBlob); } catch { throw ex; } } return rSA; } private static RSAParameters GetParametersFromCapiPrivateKeyBlob(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } RSAParameters result = default(RSAParameters); try { if (blob[offset] != 7 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 843141970) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12); byte[] array = new byte[4]; Buffer.BlockCopy(blob, offset + 16, array, 0, 4); Array.Reverse((Array)array); result.Exponent = Trim(array); int num2 = offset + 20; int num3 = num >> 3; result.Modulus = new byte[num3]; Buffer.BlockCopy(blob, num2, result.Modulus, 0, num3); Array.Reverse((Array)result.Modulus); num2 += num3; int num4 = num3 >> 1; result.P = new byte[num4]; Buffer.BlockCopy(blob, num2, result.P, 0, num4); Array.Reverse((Array)result.P); num2 += num4; result.Q = new byte[num4]; Buffer.BlockCopy(blob, num2, result.Q, 0, num4); Array.Reverse((Array)result.Q); num2 += num4; result.DP = new byte[num4]; Buffer.BlockCopy(blob, num2, result.DP, 0, num4); Array.Reverse((Array)result.DP); num2 += num4; result.DQ = new byte[num4]; Buffer.BlockCopy(blob, num2, result.DQ, 0, num4); Array.Reverse((Array)result.DQ); num2 += num4; result.InverseQ = new byte[num4]; Buffer.BlockCopy(blob, num2, result.InverseQ, 0, num4); Array.Reverse((Array)result.InverseQ); num2 += num4; result.D = new byte[num3]; if (num2 + num3 + offset <= blob.Length) { Buffer.BlockCopy(blob, num2, result.D, 0, num3); Array.Reverse((Array)result.D); } return result; } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } } public static DSA FromCapiPrivateKeyBlobDSA(byte[] blob) { return FromCapiPrivateKeyBlobDSA(blob, 0); } public static DSA FromCapiPrivateKeyBlobDSA(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } DSAParameters parameters = default(DSAParameters); try { if (blob[offset] != 7 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 844321604) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12) >> 3; int num2 = offset + 16; parameters.P = new byte[num]; Buffer.BlockCopy(blob, num2, parameters.P, 0, num); Array.Reverse((Array)parameters.P); num2 += num; parameters.Q = new byte[20]; Buffer.BlockCopy(blob, num2, parameters.Q, 0, 20); Array.Reverse((Array)parameters.Q); num2 += 20; parameters.G = new byte[num]; Buffer.BlockCopy(blob, num2, parameters.G, 0, num); Array.Reverse((Array)parameters.G); num2 += num; parameters.X = new byte[20]; Buffer.BlockCopy(blob, num2, parameters.X, 0, 20); Array.Reverse((Array)parameters.X); num2 += 20; parameters.Counter = ToInt32LE(blob, num2); num2 += 4; parameters.Seed = new byte[20]; Buffer.BlockCopy(blob, num2, parameters.Seed, 0, 20); Array.Reverse((Array)parameters.Seed); num2 += 20; } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } DSA dSA = null; try { dSA = DSA.Create(); dSA.ImportParameters(parameters); } catch (CryptographicException ex) { try { dSA = new DSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore }); dSA.ImportParameters(parameters); } catch { throw ex; } } return dSA; } public static byte[] ToCapiPrivateKeyBlob(RSA rsa) { RSAParameters rSAParameters = rsa.ExportParameters(includePrivateParameters: true); int num = rSAParameters.Modulus.Length; byte[] array = new byte[20 + (num << 2) + (num >> 1)]; array[0] = 7; array[1] = 2; array[5] = 36; array[8] = 82; array[9] = 83; array[10] = 65; array[11] = 50; byte[] bytesLE = GetBytesLE(num << 3); array[12] = bytesLE[0]; array[13] = bytesLE[1]; array[14] = bytesLE[2]; array[15] = bytesLE[3]; int num2 = 16; int num3 = rSAParameters.Exponent.Length; while (num3 > 0) { array[num2++] = rSAParameters.Exponent[--num3]; } num2 = 20; byte[]? modulus = rSAParameters.Modulus; int num4 = modulus.Length; Array.Reverse((Array)modulus, 0, num4); Buffer.BlockCopy(modulus, 0, array, num2, num4); num2 += num4; byte[]? p = rSAParameters.P; num4 = p.Length; Array.Reverse((Array)p, 0, num4); Buffer.BlockCopy(p, 0, array, num2, num4); num2 += num4; byte[]? q = rSAParameters.Q; num4 = q.Length; Array.Reverse((Array)q, 0, num4); Buffer.BlockCopy(q, 0, array, num2, num4); num2 += num4; byte[]? dP = rSAParameters.DP; num4 = dP.Length; Array.Reverse((Array)dP, 0, num4); Buffer.BlockCopy(dP, 0, array, num2, num4); num2 += num4; byte[]? dQ = rSAParameters.DQ; num4 = dQ.Length; Array.Reverse((Array)dQ, 0, num4); Buffer.BlockCopy(dQ, 0, array, num2, num4); num2 += num4; byte[]? inverseQ = rSAParameters.InverseQ; num4 = inverseQ.Length; Array.Reverse((Array)inverseQ, 0, num4); Buffer.BlockCopy(inverseQ, 0, array, num2, num4); num2 += num4; byte[]? d = rSAParameters.D; num4 = d.Length; Array.Reverse((Array)d, 0, num4); Buffer.BlockCopy(d, 0, array, num2, num4); return array; } public static byte[] ToCapiPrivateKeyBlob(DSA dsa) { DSAParameters dSAParameters = dsa.ExportParameters(includePrivateParameters: true); int num = dSAParameters.P.Length; byte[] array = new byte[16 + num + 20 + num + 20 + 4 + 20]; array[0] = 7; array[1] = 2; array[5] = 34; array[8] = 68; array[9] = 83; array[10] = 83; array[11] = 50; byte[] bytesLE = GetBytesLE(num << 3); array[12] = bytesLE[0]; array[13] = bytesLE[1]; array[14] = bytesLE[2]; array[15] = bytesLE[3]; int num2 = 16; byte[]? p = dSAParameters.P; Array.Reverse((Array)p); Buffer.BlockCopy(p, 0, array, num2, num); num2 += num; byte[]? q = dSAParameters.Q; Array.Reverse((Array)q); Buffer.BlockCopy(q, 0, array, num2, 20); num2 += 20; byte[]? g = dSAParameters.G; Array.Reverse((Array)g); Buffer.BlockCopy(g, 0, array, num2, num); num2 += num; byte[]? x = dSAParameters.X; Array.Reverse((Array)x); Buffer.BlockCopy(x, 0, array, num2, 20); num2 += 20; Buffer.BlockCopy(GetBytesLE(dSAParameters.Counter), 0, array, num2, 4); num2 += 4; byte[]? seed = dSAParameters.Seed; Array.Reverse((Array)seed); Buffer.BlockCopy(seed, 0, array, num2, 20); return array; } public static RSA FromCapiPublicKeyBlob(byte[] blob) { return FromCapiPublicKeyBlob(blob, 0); } public static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { RSAParameters parametersFromCapiPublicKeyBlob = GetParametersFromCapiPublicKeyBlob(blob, offset); try { RSA rSA = null; try { rSA = RSA.Create(); rSA.ImportParameters(parametersFromCapiPublicKeyBlob); } catch (CryptographicException) { rSA = new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore }); rSA.ImportParameters(parametersFromCapiPublicKeyBlob); } return rSA; } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } } private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } try { if (blob[offset] != 6 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 826364754) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12); RSAParameters result = new RSAParameters { Exponent = new byte[3] }; result.Exponent[0] = blob[offset + 18]; result.Exponent[1] = blob[offset + 17]; result.Exponent[2] = blob[offset + 16]; int srcOffset = offset + 20; int num2 = num >> 3; result.Modulus = new byte[num2]; Buffer.BlockCopy(blob, srcOffset, result.Modulus, 0, num2); Array.Reverse((Array)result.Modulus); return result; } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } } public static DSA FromCapiPublicKeyBlobDSA(byte[] blob) { return FromCapiPublicKeyBlobDSA(blob, 0); } public static DSA FromCapiPublicKeyBlobDSA(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } try { if (blob[offset] != 6 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 827544388) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12); DSAParameters parameters = default(DSAParameters); int num2 = num >> 3; int num3 = offset + 16; parameters.P = new byte[num2]; Buffer.BlockCopy(blob, num3, parameters.P, 0, num2); Array.Reverse((Array)parameters.P); num3 += num2; parameters.Q = new byte[20]; Buffer.BlockCopy(blob, num3, parameters.Q, 0, 20); Array.Reverse((Array)parameters.Q); num3 += 20; parameters.G = new byte[num2]; Buffer.BlockCopy(blob, num3, parameters.G, 0, num2); Array.Reverse((Array)parameters.G); num3 += num2; parameters.Y = new byte[num2]; Buffer.BlockCopy(blob, num3, parameters.Y, 0, num2); Array.Reverse((Array)parameters.Y); num3 += num2; parameters.Counter = ToInt32LE(blob, num3); num3 += 4; parameters.Seed = new byte[20]; Buffer.BlockCopy(blob, num3, parameters.Seed, 0, 20); Array.Reverse((Array)parameters.Seed); num3 += 20; DSA dSA = DSA.Create(); dSA.ImportParameters(parameters); return dSA; } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } } public static byte[] ToCapiPublicKeyBlob(RSA rsa) { RSAParameters rSAParameters = rsa.ExportParameters(includePrivateParameters: false); int num = rSAParameters.Modulus.Length; byte[] array = new byte[20 + num]; array[0] = 6; array[1] = 2; array[5] = 36; array[8] = 82; array[9] = 83; array[10] = 65; array[11] = 49; byte[] bytesLE = GetBytesLE(num << 3); array[12] = bytesLE[0]; array[13] = bytesLE[1]; array[14] = bytesLE[2]; array[15] = bytesLE[3]; int num2 = 16; int num3 = rSAParameters.Exponent.Length; while (num3 > 0) { array[num2++] = rSAParameters.Exponent[--num3]; } num2 = 20; byte[]? modulus = rSAParameters.Modulus; int num4 = modulus.Length; Array.Reverse((Array)modulus, 0, num4); Buffer.BlockCopy(modulus, 0, array, num2, num4); num2 += num4; return array; } public static byte[] ToCapiPublicKeyBlob(DSA dsa) { DSAParameters dSAParameters = dsa.ExportParameters(includePrivateParameters: false); int num = dSAParameters.P.Length; byte[] array = new byte[16 + num + 20 + num + num + 4 + 20]; array[0] = 6; array[1] = 2; array[5] = 34; array[8] = 68; array[9] = 83; array[10] = 83; array[11] = 49; byte[] bytesLE = GetBytesLE(num << 3); array[12] = bytesLE[0]; array[13] = bytesLE[1]; array[14] = bytesLE[2]; array[15] = bytesLE[3]; int num2 = 16; byte[]? p = dSAParameters.P; Array.Reverse((Array)p); Buffer.BlockCopy(p, 0, array, num2, num);
UMM/Mods/Runtime Unity Editor/Mono.Cecil.dll
Decompiled a month 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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Text; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using Mono.Cecil.PE; using Mono.Collections.Generic; using Mono.Security.Cryptography; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.10.4.0")] [assembly: AssemblyInformationalVersion("0.10.4.0")] [assembly: AssemblyTitle("Mono.Cecil")] [assembly: Guid("fd225bb4-fa53-44b2-a6db-85f5e48dcb54")] [assembly: InternalsVisibleTo("Mono.Cecil.Pdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: InternalsVisibleTo("Mono.Cecil.Mdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: InternalsVisibleTo("Mono.Cecil.Rocks, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: InternalsVisibleTo("Mono.Cecil.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: AssemblyVersion("0.10.4.0")] internal static class Consts { public const string AssemblyName = "Mono.Cecil"; public const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf"; } namespace Mono { internal static class Disposable { public static Disposable<T> Owned<T>(T value) where T : class, IDisposable { return new Disposable<T>(value, owned: true); } public static Disposable<T> NotOwned<T>(T value) where T : class, IDisposable { return new Disposable<T>(value, owned: false); } } internal struct Disposable<T> : IDisposable where T : class, IDisposable { internal readonly T value; private readonly bool owned; public Disposable(T value, bool owned) { this.value = value; this.owned = owned; } public void Dispose() { if (value != null && owned) { value.Dispose(); } } } internal static class Empty<T> { public static readonly T[] Array = new T[0]; } internal class ArgumentNullOrEmptyException : ArgumentException { public ArgumentNullOrEmptyException(string paramName) : base("Argument null or empty", paramName) { } } internal class MergeSort<T> { private readonly T[] elements; private readonly T[] buffer; private readonly IComparer<T> comparer; private MergeSort(T[] elements, IComparer<T> comparer) { this.elements = elements; buffer = new T[elements.Length]; Array.Copy(this.elements, buffer, elements.Length); this.comparer = comparer; } public static void Sort(T[] source, IComparer<T> comparer) { Sort(source, 0, source.Length, comparer); } public static void Sort(T[] source, int start, int length, IComparer<T> comparer) { new MergeSort<T>(source, comparer).Sort(start, length); } private void Sort(int start, int length) { TopDownSplitMerge(buffer, elements, start, length); } private void TopDownSplitMerge(T[] a, T[] b, int start, int end) { if (end - start >= 2) { int num = (end + start) / 2; TopDownSplitMerge(b, a, start, num); TopDownSplitMerge(b, a, num, end); TopDownMerge(a, b, start, num, end); } } private void TopDownMerge(T[] a, T[] b, int start, int middle, int end) { int num = start; int num2 = middle; for (int i = start; i < end; i++) { if (num < middle && (num2 >= end || comparer.Compare(a[num], a[num2]) <= 0)) { b[i] = a[num++]; } else { b[i] = a[num2++]; } } } } internal static class TypeExtensions { public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static Assembly Assembly(this Type type) { return type.Assembly; } public static MethodBase DeclaringMethod(this Type type) { return type.DeclaringMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GetGenericArguments(); } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } public static bool IsValueType(this Type type) { return type.IsValueType; } } } namespace Mono.Security.Cryptography { internal static class CryptoConvert { private static int ToInt32LE(byte[] bytes, int offset) { return (bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]; } private static uint ToUInt32LE(byte[] bytes, int offset) { return (uint)((bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]); } private static byte[] Trim(byte[] array) { for (int i = 0; i < array.Length; i++) { if (array[i] != 0) { byte[] array2 = new byte[array.Length - i]; Buffer.BlockCopy(array, i, array2, 0, array2.Length); return array2; } } return null; } private static RSA FromCapiPrivateKeyBlob(byte[] blob, int offset) { RSAParameters parameters = default(RSAParameters); try { if (blob[offset] != 7 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 843141970) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12); byte[] array = new byte[4]; Buffer.BlockCopy(blob, offset + 16, array, 0, 4); Array.Reverse((Array)array); parameters.Exponent = Trim(array); int num2 = offset + 20; int num3 = num >> 3; parameters.Modulus = new byte[num3]; Buffer.BlockCopy(blob, num2, parameters.Modulus, 0, num3); Array.Reverse((Array)parameters.Modulus); num2 += num3; int num4 = num3 >> 1; parameters.P = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.P, 0, num4); Array.Reverse((Array)parameters.P); num2 += num4; parameters.Q = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.Q, 0, num4); Array.Reverse((Array)parameters.Q); num2 += num4; parameters.DP = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.DP, 0, num4); Array.Reverse((Array)parameters.DP); num2 += num4; parameters.DQ = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.DQ, 0, num4); Array.Reverse((Array)parameters.DQ); num2 += num4; parameters.InverseQ = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.InverseQ, 0, num4); Array.Reverse((Array)parameters.InverseQ); num2 += num4; parameters.D = new byte[num3]; if (num2 + num3 + offset <= blob.Length) { Buffer.BlockCopy(blob, num2, parameters.D, 0, num3); Array.Reverse((Array)parameters.D); } } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } RSA rSA = null; try { rSA = RSA.Create(); rSA.ImportParameters(parameters); } catch (CryptographicException) { bool flag = false; try { rSA = new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore }); rSA.ImportParameters(parameters); } catch { flag = true; } if (flag) { throw; } } return rSA; } private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { try { if (blob[offset] != 6 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 826364754) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12); RSAParameters parameters = new RSAParameters { Exponent = new byte[3] }; parameters.Exponent[0] = blob[offset + 18]; parameters.Exponent[1] = blob[offset + 17]; parameters.Exponent[2] = blob[offset + 16]; int srcOffset = offset + 20; int num2 = num >> 3; parameters.Modulus = new byte[num2]; Buffer.BlockCopy(blob, srcOffset, parameters.Modulus, 0, num2); Array.Reverse((Array)parameters.Modulus); RSA rSA = null; try { rSA = RSA.Create(); rSA.ImportParameters(parameters); } catch (CryptographicException) { rSA = new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore }); rSA.ImportParameters(parameters); } return rSA; } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } } public static RSA FromCapiKeyBlob(byte[] blob) { return FromCapiKeyBlob(blob, 0); } public static RSA FromCapiKeyBlob(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } switch (blob[offset]) { case 0: if (blob[offset + 12] == 6) { return FromCapiPublicKeyBlob(blob, offset + 12); } break; case 6: return FromCapiPublicKeyBlob(blob, offset); case 7: return FromCapiPrivateKeyBlob(blob, offset); } throw new CryptographicException("Unknown blob format."); } } } namespace Mono.Collections.Generic { public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection { public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator { private Collection<T> collection; private T current; private int next; private readonly int version; public T Current => current; object IEnumerator.Current { get { CheckState(); if (next <= 0) { throw new InvalidOperationException(); } return current; } } internal Enumerator(Collection<T> collection) { this = default(Enumerator); this.collection = collection; version = collection.version; } public bool MoveNext() { CheckState(); if (next < 0) { return false; } if (next < collection.size) { current = collection.items[next++]; return true; } next = -1; return false; } public void Reset() { CheckState(); next = 0; } private void CheckState() { if (collection == null) { throw new ObjectDisposedException(GetType().FullName); } if (version != collection.version) { throw new InvalidOperationException(); } } public void Dispose() { collection = null; } } internal T[] items; internal int size; private int version; public int Count => size; public T this[int index] { get { if (index >= size) { throw new ArgumentOutOfRangeException(); } return items[index]; } set { CheckIndex(index); if (index == size) { throw new ArgumentOutOfRangeException(); } OnSet(value, index); items[index] = value; } } public int Capacity { get { return items.Length; } set { if (value < 0 || value < size) { throw new ArgumentOutOfRangeException(); } Resize(value); } } bool ICollection<T>.IsReadOnly => false; bool IList.IsFixedSize => false; bool IList.IsReadOnly => false; object IList.this[int index] { get { return this[index]; } set { CheckIndex(index); try { this[index] = (T)value; return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException(); } } int ICollection.Count => Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; public Collection() { items = Empty<T>.Array; } public Collection(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(); } items = new T[capacity]; } public Collection(ICollection<T> items) { if (items == null) { throw new ArgumentNullException("items"); } this.items = new T[items.Count]; items.CopyTo(this.items, 0); size = this.items.Length; } public void Add(T item) { if (size == items.Length) { Grow(1); } OnAdd(item, size); items[size++] = item; version++; } public bool Contains(T item) { return IndexOf(item) != -1; } public int IndexOf(T item) { return Array.IndexOf(items, item, 0, size); } public void Insert(int index, T item) { CheckIndex(index); if (size == items.Length) { Grow(1); } OnInsert(item, index); Shift(index, 1); items[index] = item; version++; } public void RemoveAt(int index) { if (index < 0 || index >= size) { throw new ArgumentOutOfRangeException(); } T item = items[index]; OnRemove(item, index); Shift(index, -1); version++; } public bool Remove(T item) { int num = IndexOf(item); if (num == -1) { return false; } OnRemove(item, num); Shift(num, -1); version++; return true; } public void Clear() { OnClear(); Array.Clear(items, 0, size); size = 0; version++; } public void CopyTo(T[] array, int arrayIndex) { Array.Copy(items, 0, array, arrayIndex, size); } public T[] ToArray() { T[] array = new T[size]; Array.Copy(items, 0, array, 0, size); return array; } private void CheckIndex(int index) { if (index < 0 || index > size) { throw new ArgumentOutOfRangeException(); } } private void Shift(int start, int delta) { if (delta < 0) { start -= delta; } if (start < size) { Array.Copy(items, start, items, start + delta, size - start); } size += delta; if (delta < 0) { Array.Clear(items, size, -delta); } } protected virtual void OnAdd(T item, int index) { } protected virtual void OnInsert(T item, int index) { } protected virtual void OnSet(T item, int index) { } protected virtual void OnRemove(T item, int index) { } protected virtual void OnClear() { } internal virtual void Grow(int desired) { int num = size + desired; if (num > items.Length) { num = Math.Max(Math.Max(items.Length * 2, 4), num); Resize(num); } } protected void Resize(int new_size) { if (new_size != size) { if (new_size < size) { throw new ArgumentOutOfRangeException(); } items = items.Resize(new_size); } } int IList.Add(object value) { try { Add((T)value); return size - 1; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException(); } void IList.Clear() { Clear(); } bool IList.Contains(object value) { return ((IList)this).IndexOf(value) > -1; } int IList.IndexOf(object value) { try { return IndexOf((T)value); } catch (InvalidCastException) { } catch (NullReferenceException) { } return -1; } void IList.Insert(int index, object value) { CheckIndex(index); try { Insert(index, (T)value); return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException(); } void IList.Remove(object value) { try { Remove((T)value); } catch (InvalidCastException) { } catch (NullReferenceException) { } } void IList.RemoveAt(int index) { RemoveAt(index); } void ICollection.CopyTo(Array array, int index) { Array.Copy(items, 0, array, index, size); } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } } public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection { private static ReadOnlyCollection<T> empty; public static ReadOnlyCollection<T> Empty => empty ?? (empty = new ReadOnlyCollection<T>()); bool ICollection<T>.IsReadOnly => true; bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; private ReadOnlyCollection() { } public ReadOnlyCollection(T[] array) { if (array == null) { throw new ArgumentNullException(); } Initialize(array, array.Length); } public ReadOnlyCollection(Collection<T> collection) { if (collection == null) { throw new ArgumentNullException(); } Initialize(collection.items, collection.size); } private void Initialize(T[] items, int size) { base.items = new T[size]; Array.Copy(items, 0, base.items, 0, size); base.size = size; } internal override void Grow(int desired) { throw new InvalidOperationException(); } protected override void OnAdd(T item, int index) { throw new InvalidOperationException(); } protected override void OnClear() { throw new InvalidOperationException(); } protected override void OnInsert(T item, int index) { throw new InvalidOperationException(); } protected override void OnRemove(T item, int index) { throw new InvalidOperationException(); } protected override void OnSet(T item, int index) { throw new InvalidOperationException(); } } } namespace Mono.Cecil { internal static class Mixin { public enum Argument { name, fileName, fullName, stream, type, method, field, parameters, module, modifierType, eventType, fieldType, declaringType, returnType, propertyType, interfaceType } public static Version ZeroVersion = new Version(0, 0, 0, 0); public const int NotResolvedMarker = -2; public const int NoDataMarker = -1; internal static object NoValue = new object(); internal static object NotResolved = new object(); public const string mscorlib = "mscorlib"; public const string system_runtime = "System.Runtime"; public const string system_private_corelib = "System.Private.CoreLib"; public const string netstandard = "netstandard"; public const int TableCount = 58; public const int CodedIndexCount = 14; public static bool IsNullOrEmpty<T>(this T[] self) { if (self != null) { return self.Length == 0; } return true; } public static bool IsNullOrEmpty<T>(this Collection<T> self) { if (self != null) { return self.size == 0; } return true; } public static T[] Resize<T>(this T[] self, int length) { Array.Resize(ref self, length); return self; } public static T[] Add<T>(this T[] self, T item) { if (self == null) { self = new T[1] { item }; return self; } self = self.Resize(self.Length + 1); self[^1] = item; return self; } public static Version CheckVersion(Version version) { if (version == null) { return ZeroVersion; } if (version.Build == -1) { return new Version(version.Major, version.Minor, 0, 0); } if (version.Revision == -1) { return new Version(version.Major, version.Minor, version.Build, 0); } return version; } public static bool TryGetUniqueDocument(this MethodDebugInformation info, out Document document) { document = info.SequencePoints[0].Document; for (int i = 1; i < info.SequencePoints.Count; i++) { if (info.SequencePoints[i].Document != document) { return false; } } return true; } public static void ResolveConstant(this IConstantProvider self, ref object constant, ModuleDefinition module) { if (module == null) { constant = NoValue; return; } lock (module.SyncRoot) { if (constant != NotResolved) { return; } if (module.HasImage()) { constant = module.Read(self, (IConstantProvider provider, MetadataReader reader) => reader.ReadConstant(provider)); } else { constant = NoValue; } } } public static bool GetHasCustomAttributes(this ICustomAttributeProvider self, ModuleDefinition module) { if (module.HasImage()) { return module.Read(self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.HasCustomAttributes(provider)); } return false; } public static Collection<CustomAttribute> GetCustomAttributes(this ICustomAttributeProvider self, ref Collection<CustomAttribute> variable, ModuleDefinition module) { if (!module.HasImage()) { return variable = new Collection<CustomAttribute>(); } return module.Read(ref variable, self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.ReadCustomAttributes(provider)); } public static bool ContainsGenericParameter(this IGenericInstance self) { Collection<TypeReference> genericArguments = self.GenericArguments; for (int i = 0; i < genericArguments.Count; i++) { if (genericArguments[i].ContainsGenericParameter) { return true; } } return false; } public static void GenericInstanceFullName(this IGenericInstance self, StringBuilder builder) { builder.Append("<"); Collection<TypeReference> genericArguments = self.GenericArguments; for (int i = 0; i < genericArguments.Count; i++) { if (i > 0) { builder.Append(","); } builder.Append(genericArguments[i].FullName); } builder.Append(">"); } public static bool GetHasGenericParameters(this IGenericParameterProvider self, ModuleDefinition module) { if (module.HasImage()) { return module.Read(self, (IGenericParameterProvider provider, MetadataReader reader) => reader.HasGenericParameters(provider)); } return false; } public static Collection<GenericParameter> GetGenericParameters(this IGenericParameterProvider self, ref Collection<GenericParameter> collection, ModuleDefinition module) { if (!module.HasImage()) { return collection = new GenericParameterCollection(self); } return module.Read(ref collection, self, (IGenericParameterProvider provider, MetadataReader reader) => reader.ReadGenericParameters(provider)); } public static bool GetHasMarshalInfo(this IMarshalInfoProvider self, ModuleDefinition module) { if (module.HasImage()) { return module.Read(self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.HasMarshalInfo(provider)); } return false; } public static MarshalInfo GetMarshalInfo(this IMarshalInfoProvider self, ref MarshalInfo variable, ModuleDefinition module) { if (!module.HasImage()) { return null; } return module.Read(ref variable, self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.ReadMarshalInfo(provider)); } public static bool GetAttributes(this uint self, uint attributes) { return (self & attributes) != 0; } public static uint SetAttributes(this uint self, uint attributes, bool value) { if (value) { return self | attributes; } return self & ~attributes; } public static bool GetMaskedAttributes(this uint self, uint mask, uint attributes) { return (self & mask) == attributes; } public static uint SetMaskedAttributes(this uint self, uint mask, uint attributes, bool value) { if (value) { self &= ~mask; return self | attributes; } return self & ~(mask & attributes); } public static bool GetAttributes(this ushort self, ushort attributes) { return (self & attributes) != 0; } public static ushort SetAttributes(this ushort self, ushort attributes, bool value) { if (value) { return (ushort)(self | attributes); } return (ushort)(self & ~attributes); } public static bool GetMaskedAttributes(this ushort self, ushort mask, uint attributes) { return (self & mask) == attributes; } public static ushort SetMaskedAttributes(this ushort self, ushort mask, uint attributes, bool value) { if (value) { self = (ushort)(self & ~mask); return (ushort)(self | attributes); } return (ushort)(self & ~(mask & attributes)); } public static bool HasImplicitThis(this IMethodSignature self) { if (self.HasThis) { return !self.ExplicitThis; } return false; } public static void MethodSignatureFullName(this IMethodSignature self, StringBuilder builder) { builder.Append("("); if (self.HasParameters) { Collection<ParameterDefinition> parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { ParameterDefinition parameterDefinition = parameters[i]; if (i > 0) { builder.Append(","); } if (parameterDefinition.ParameterType.IsSentinel) { builder.Append("...,"); } builder.Append(parameterDefinition.ParameterType.FullName); } } builder.Append(")"); } public static void CheckModule(ModuleDefinition module) { if (module == null) { throw new ArgumentNullException(Argument.module.ToString()); } } public static bool TryGetAssemblyNameReference(this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference) { Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences; for (int i = 0; i < assemblyReferences.Count; i++) { AssemblyNameReference assemblyNameReference = assemblyReferences[i]; if (Equals(name_reference, assemblyNameReference)) { assembly_reference = assemblyNameReference; return true; } } assembly_reference = null; return false; } private static bool Equals(byte[] a, byte[] b) { if (a == b) { return true; } if (a == null) { return false; } if (a.Length != b.Length) { return false; } for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) { return false; } } return true; } private static bool Equals<T>(T a, T b) where T : class, IEquatable<T> { if (a == b) { return true; } return a?.Equals(b) ?? false; } private static bool Equals(AssemblyNameReference a, AssemblyNameReference b) { if (a == b) { return true; } if (a.Name != b.Name) { return false; } if (!Equals(a.Version, b.Version)) { return false; } if (a.Culture != b.Culture) { return false; } if (!Equals(a.PublicKeyToken, b.PublicKeyToken)) { return false; } return true; } public static ParameterDefinition GetParameter(this Mono.Cecil.Cil.MethodBody self, int index) { MethodDefinition method = self.method; if (method.HasThis) { if (index == 0) { return self.ThisParameter; } index--; } Collection<ParameterDefinition> parameters = method.Parameters; if (index < 0 || index >= parameters.size) { return null; } return parameters[index]; } public static VariableDefinition GetVariable(this Mono.Cecil.Cil.MethodBody self, int index) { Collection<VariableDefinition> variables = self.Variables; if (index < 0 || index >= variables.size) { return null; } return variables[index]; } public static bool GetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics) { return (self.SemanticsAttributes & semantics) != 0; } public static void SetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics, bool value) { if (value) { self.SemanticsAttributes |= semantics; } else { self.SemanticsAttributes &= (MethodSemanticsAttributes)(ushort)(~(int)semantics); } } public static bool IsVarArg(this IMethodSignature self) { return self.CallingConvention == MethodCallingConvention.VarArg; } public static int GetSentinelPosition(this IMethodSignature self) { if (!self.HasParameters) { return -1; } Collection<ParameterDefinition> parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { if (parameters[i].ParameterType.IsSentinel) { return i; } } return -1; } public static void CheckName(object name) { if (name == null) { throw new ArgumentNullException(Argument.name.ToString()); } } public static void CheckName(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullOrEmptyException(Argument.name.ToString()); } } public static void CheckFileName(string fileName) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullOrEmptyException(Argument.fileName.ToString()); } } public static void CheckFullName(string fullName) { if (string.IsNullOrEmpty(fullName)) { throw new ArgumentNullOrEmptyException(Argument.fullName.ToString()); } } public static void CheckStream(object stream) { if (stream == null) { throw new ArgumentNullException(Argument.stream.ToString()); } } public static void CheckWriteSeek(Stream stream) { if (!stream.CanWrite || !stream.CanSeek) { throw new ArgumentException("Stream must be writable and seekable."); } } public static void CheckReadSeek(Stream stream) { if (!stream.CanRead || !stream.CanSeek) { throw new ArgumentException("Stream must be readable and seekable."); } } public static void CheckType(object type) { if (type == null) { throw new ArgumentNullException(Argument.type.ToString()); } } public static void CheckType(object type, Argument argument) { if (type == null) { throw new ArgumentNullException(argument.ToString()); } } public static void CheckField(object field) { if (field == null) { throw new ArgumentNullException(Argument.field.ToString()); } } public static void CheckMethod(object method) { if (method == null) { throw new ArgumentNullException(Argument.method.ToString()); } } public static void CheckParameters(object parameters) { if (parameters == null) { throw new ArgumentNullException(Argument.parameters.ToString()); } } public static uint GetTimestamp() { return (uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; } public static bool HasImage(this ModuleDefinition self) { return self?.HasImage ?? false; } public static string GetFileName(this Stream self) { if (!(self is FileStream fileStream)) { return string.Empty; } return Path.GetFullPath(fileStream.Name); } public static void CopyTo(this Stream self, Stream target) { byte[] array = new byte[8192]; int count; while ((count = self.Read(array, 0, array.Length)) > 0) { target.Write(array, 0, count); } } public static TargetRuntime ParseRuntime(this string self) { if (string.IsNullOrEmpty(self)) { return TargetRuntime.Net_4_0; } switch (self[1]) { case '1': if (self[3] != '0') { return TargetRuntime.Net_1_1; } return TargetRuntime.Net_1_0; case '2': return TargetRuntime.Net_2_0; default: return TargetRuntime.Net_4_0; } } public static string RuntimeVersionString(this TargetRuntime runtime) { return runtime switch { TargetRuntime.Net_1_0 => "v1.0.3705", TargetRuntime.Net_1_1 => "v1.1.4322", TargetRuntime.Net_2_0 => "v2.0.50727", _ => "v4.0.30319", }; } public static bool IsWindowsMetadata(this ModuleDefinition module) { return module.MetadataKind != MetadataKind.Ecma335; } public static byte[] ReadAll(this Stream self) { MemoryStream memoryStream = new MemoryStream((int)self.Length); byte[] array = new byte[1024]; int count; while ((count = self.Read(array, 0, array.Length)) != 0) { memoryStream.Write(array, 0, count); } return memoryStream.ToArray(); } public static void Read(object o) { } public static bool GetHasSecurityDeclarations(this ISecurityDeclarationProvider self, ModuleDefinition module) { if (module.HasImage()) { return module.Read(self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.HasSecurityDeclarations(provider)); } return false; } public static Collection<SecurityDeclaration> GetSecurityDeclarations(this ISecurityDeclarationProvider self, ref Collection<SecurityDeclaration> variable, ModuleDefinition module) { if (!module.HasImage()) { return variable = new Collection<SecurityDeclaration>(); } return module.Read(ref variable, self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.ReadSecurityDeclarations(provider)); } public static TypeReference GetEnumUnderlyingType(this TypeDefinition self) { Collection<FieldDefinition> fields = self.Fields; for (int i = 0; i < fields.Count; i++) { FieldDefinition fieldDefinition = fields[i]; if (!fieldDefinition.IsStatic) { return fieldDefinition.FieldType; } } throw new ArgumentException(); } public static TypeDefinition GetNestedType(this TypeDefinition self, string fullname) { if (!self.HasNestedTypes) { return null; } Collection<TypeDefinition> nestedTypes = self.NestedTypes; for (int i = 0; i < nestedTypes.Count; i++) { TypeDefinition typeDefinition = nestedTypes[i]; if (typeDefinition.TypeFullName() == fullname) { return typeDefinition; } } return null; } public static bool IsPrimitive(this ElementType self) { switch (self) { case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.I: case ElementType.U: return true; default: return false; } } public static string TypeFullName(this TypeReference self) { if (!string.IsNullOrEmpty(self.Namespace)) { return self.Namespace + "." + self.Name; } return self.Name; } public static bool IsTypeOf(this TypeReference self, string @namespace, string name) { if (self.Name == name) { return self.Namespace == @namespace; } return false; } public static bool IsTypeSpecification(this TypeReference type) { switch (type.etype) { case ElementType.Ptr: case ElementType.ByRef: case ElementType.Var: case ElementType.Array: case ElementType.GenericInst: case ElementType.FnPtr: case ElementType.SzArray: case ElementType.MVar: case ElementType.CModReqD: case ElementType.CModOpt: case ElementType.Sentinel: case ElementType.Pinned: return true; default: return false; } } public static TypeDefinition CheckedResolve(this TypeReference self) { return self.Resolve() ?? throw new ResolutionException(self); } public static bool TryGetCoreLibraryReference(this ModuleDefinition module, out AssemblyNameReference reference) { Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences; for (int i = 0; i < assemblyReferences.Count; i++) { reference = assemblyReferences[i]; if (IsCoreLibrary(reference)) { return true; } } reference = null; return false; } public static bool IsCoreLibrary(this ModuleDefinition module) { if (module.Assembly == null) { return false; } if (!IsCoreLibrary(module.Assembly.Name)) { return false; } if (module.HasImage && module.Read(module, (ModuleDefinition m, MetadataReader reader) => reader.image.GetTableLength(Table.AssemblyRef) > 0)) { return false; } return true; } public static void KnownValueType(this TypeReference type) { if (!type.IsDefinition) { type.IsValueType = true; } } private static bool IsCoreLibrary(AssemblyNameReference reference) { string name = reference.Name; switch (name) { default: return name == "netstandard"; case "mscorlib": case "System.Runtime": case "System.Private.CoreLib": return true; } } public static ImageDebugHeaderEntry GetCodeViewEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.CodeView); } public static ImageDebugHeaderEntry GetDeterministicEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.Deterministic); } public static ImageDebugHeader AddDeterministicEntry(this ImageDebugHeader header) { ImageDebugDirectory directory = default(ImageDebugDirectory); directory.Type = ImageDebugType.Deterministic; ImageDebugHeaderEntry imageDebugHeaderEntry = new ImageDebugHeaderEntry(directory, Empty<byte>.Array); if (header == null) { return new ImageDebugHeader(imageDebugHeaderEntry); } ImageDebugHeaderEntry[] array = new ImageDebugHeaderEntry[header.Entries.Length + 1]; Array.Copy(header.Entries, array, header.Entries.Length); array[^1] = imageDebugHeaderEntry; return new ImageDebugHeader(array); } public static ImageDebugHeaderEntry GetEmbeddedPortablePdbEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.EmbeddedPortablePdb); } private static ImageDebugHeaderEntry GetEntry(this ImageDebugHeader header, ImageDebugType type) { if (!header.HasEntries) { return null; } for (int i = 0; i < header.Entries.Length; i++) { ImageDebugHeaderEntry imageDebugHeaderEntry = header.Entries[i]; if (imageDebugHeaderEntry.Directory.Type == type) { return imageDebugHeaderEntry; } } return null; } public static string GetPdbFileName(string assemblyFileName) { return Path.ChangeExtension(assemblyFileName, ".pdb"); } public static string GetMdbFileName(string assemblyFileName) { return assemblyFileName + ".mdb"; } public static bool IsPortablePdb(string fileName) { using FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); return IsPortablePdb(stream); } public static bool IsPortablePdb(Stream stream) { if (stream.Length < 4) { return false; } long position = stream.Position; try { return new BinaryReader(stream).ReadUInt32() == 1112167234; } finally { stream.Position = position; } } public static uint ReadCompressedUInt32(this byte[] data, ref int position) { uint result; if ((data[position] & 0x80) == 0) { result = data[position]; position++; } else if ((data[position] & 0x40) == 0) { result = (uint)((data[position] & -129) << 8); result |= data[position + 1]; position += 2; } else { result = (uint)((data[position] & -193) << 24); result |= (uint)(data[position + 1] << 16); result |= (uint)(data[position + 2] << 8); result |= data[position + 3]; position += 4; } return result; } public static MetadataToken GetMetadataToken(this CodedIndex self, uint data) { uint rid; TokenType type; switch (self) { case CodedIndex.TypeDefOrRef: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_006d; case 2u: goto IL_0078; default: goto end_IL_0001; } type = TokenType.TypeDef; goto IL_05b3; case CodedIndex.HasConstant: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_00ad; case 2u: goto IL_00b8; default: goto end_IL_0001; } type = TokenType.Field; goto IL_05b3; case CodedIndex.HasCustomAttribute: rid = data >> 5; switch (data & 0x1F) { case 0u: break; case 1u: goto IL_013a; case 2u: goto IL_0145; case 3u: goto IL_0150; case 4u: goto IL_015b; case 5u: goto IL_0166; case 6u: goto IL_0171; case 7u: goto IL_017c; case 8u: goto IL_0183; case 9u: goto IL_018e; case 10u: goto IL_0199; case 11u: goto IL_01a4; case 12u: goto IL_01af; case 13u: goto IL_01ba; case 14u: goto IL_01c5; case 15u: goto IL_01d0; case 16u: goto IL_01db; case 17u: goto IL_01e6; case 18u: goto IL_01f1; case 19u: goto IL_01fc; case 20u: goto IL_0207; case 21u: goto IL_0212; default: goto end_IL_0001; } type = TokenType.Method; goto IL_05b3; case CodedIndex.HasFieldMarshal: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.Param; } else { type = TokenType.Field; } goto IL_05b3; } case CodedIndex.HasDeclSecurity: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_0271; case 2u: goto IL_027c; default: goto end_IL_0001; } type = TokenType.TypeDef; goto IL_05b3; case CodedIndex.MemberRefParent: rid = data >> 3; switch (data & 7) { case 0u: break; case 1u: goto IL_02b9; case 2u: goto IL_02c4; case 3u: goto IL_02cf; case 4u: goto IL_02da; default: goto end_IL_0001; } type = TokenType.TypeDef; goto IL_05b3; case CodedIndex.HasSemantics: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.Property; } else { type = TokenType.Event; } goto IL_05b3; } case CodedIndex.MethodDefOrRef: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.MemberRef; } else { type = TokenType.Method; } goto IL_05b3; } case CodedIndex.MemberForwarded: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.Method; } else { type = TokenType.Field; } goto IL_05b3; } case CodedIndex.Implementation: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_038d; case 2u: goto IL_0398; default: goto end_IL_0001; } type = TokenType.File; goto IL_05b3; case CodedIndex.CustomAttributeType: { rid = data >> 3; uint num = data & 7u; if (num != 2) { if (num != 3) { break; } type = TokenType.MemberRef; } else { type = TokenType.Method; } goto IL_05b3; } case CodedIndex.ResolutionScope: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_03f8; case 2u: goto IL_0403; case 3u: goto IL_040e; default: goto end_IL_0001; } type = TokenType.Module; goto IL_05b3; case CodedIndex.TypeOrMethodDef: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.Method; } else { type = TokenType.TypeDef; } goto IL_05b3; } case CodedIndex.HasCustomDebugInformation: { rid = data >> 5; switch (data & 0x1F) { case 0u: break; case 1u: goto IL_04ce; case 2u: goto IL_04d9; case 3u: goto IL_04e4; case 4u: goto IL_04ef; case 5u: goto IL_04fa; case 6u: goto IL_0505; case 7u: goto IL_0510; case 8u: goto IL_0517; case 9u: goto IL_0522; case 10u: goto IL_052d; case 11u: goto IL_0535; case 12u: goto IL_053d; case 13u: goto IL_0545; case 14u: goto IL_054d; case 15u: goto IL_0555; case 16u: goto IL_055d; case 17u: goto IL_0565; case 18u: goto IL_056d; case 19u: goto IL_0575; case 20u: goto IL_057d; case 21u: goto IL_0585; case 22u: goto IL_058d; case 23u: goto IL_0595; case 24u: goto IL_059d; case 25u: goto IL_05a5; case 26u: goto IL_05ad; default: goto end_IL_0001; } type = TokenType.Method; goto IL_05b3; } IL_05ad: type = TokenType.ImportScope; goto IL_05b3; IL_05a5: type = TokenType.LocalConstant; goto IL_05b3; IL_059d: type = TokenType.LocalVariable; goto IL_05b3; IL_0595: type = TokenType.LocalScope; goto IL_05b3; IL_058d: type = TokenType.Document; goto IL_05b3; IL_0585: type = TokenType.MethodSpec; goto IL_05b3; IL_057d: type = TokenType.GenericParamConstraint; goto IL_05b3; IL_0575: type = TokenType.GenericParam; goto IL_05b3; IL_056d: type = TokenType.ManifestResource; goto IL_05b3; IL_0565: type = TokenType.ExportedType; goto IL_05b3; IL_055d: type = TokenType.File; goto IL_05b3; IL_0555: type = TokenType.AssemblyRef; goto IL_05b3; IL_054d: type = TokenType.Assembly; goto IL_05b3; IL_0545: type = TokenType.TypeSpec; goto IL_05b3; IL_053d: type = TokenType.ModuleRef; goto IL_05b3; IL_0535: type = TokenType.Signature; goto IL_05b3; IL_052d: type = TokenType.Event; goto IL_05b3; IL_0522: type = TokenType.Property; goto IL_05b3; IL_0517: type = TokenType.Permission; goto IL_05b3; IL_0510: type = TokenType.Module; goto IL_05b3; IL_0505: type = TokenType.MemberRef; goto IL_05b3; IL_04fa: type = TokenType.InterfaceImpl; goto IL_05b3; IL_04ef: type = TokenType.Param; goto IL_05b3; IL_04e4: type = TokenType.TypeDef; goto IL_05b3; IL_04d9: type = TokenType.TypeRef; goto IL_05b3; IL_04ce: type = TokenType.Field; goto IL_05b3; IL_01db: type = TokenType.File; goto IL_05b3; IL_01d0: type = TokenType.AssemblyRef; goto IL_05b3; IL_01ba: type = TokenType.TypeSpec; goto IL_05b3; IL_01c5: type = TokenType.Assembly; goto IL_05b3; IL_040e: type = TokenType.TypeRef; goto IL_05b3; IL_0403: type = TokenType.AssemblyRef; goto IL_05b3; IL_03f8: type = TokenType.ModuleRef; goto IL_05b3; IL_01af: type = TokenType.ModuleRef; goto IL_05b3; IL_01a4: type = TokenType.Signature; goto IL_05b3; IL_018e: type = TokenType.Property; goto IL_05b3; IL_0199: type = TokenType.Event; goto IL_05b3; IL_0398: type = TokenType.ExportedType; goto IL_05b3; IL_038d: type = TokenType.AssemblyRef; goto IL_05b3; IL_0183: type = TokenType.Permission; goto IL_05b3; IL_017c: type = TokenType.Module; goto IL_05b3; IL_0166: type = TokenType.InterfaceImpl; goto IL_05b3; IL_0171: type = TokenType.MemberRef; goto IL_05b3; IL_015b: type = TokenType.Param; goto IL_05b3; IL_0145: type = TokenType.TypeRef; goto IL_05b3; IL_0150: type = TokenType.TypeDef; goto IL_05b3; IL_013a: type = TokenType.Field; goto IL_05b3; IL_006d: type = TokenType.TypeRef; goto IL_05b3; IL_02da: type = TokenType.TypeSpec; goto IL_05b3; IL_02cf: type = TokenType.Method; goto IL_05b3; IL_02c4: type = TokenType.ModuleRef; goto IL_05b3; IL_02b9: type = TokenType.TypeRef; goto IL_05b3; IL_00b8: type = TokenType.Property; goto IL_05b3; IL_027c: type = TokenType.Assembly; goto IL_05b3; IL_0271: type = TokenType.Method; goto IL_05b3; IL_00ad: type = TokenType.Param; goto IL_05b3; IL_05b3: return new MetadataToken(type, rid); IL_0078: type = TokenType.TypeSpec; goto IL_05b3; IL_0212: type = TokenType.MethodSpec; goto IL_05b3; IL_0207: type = TokenType.GenericParamConstraint; goto IL_05b3; IL_01fc: type = TokenType.GenericParam; goto IL_05b3; IL_01f1: type = TokenType.ManifestResource; goto IL_05b3; IL_01e6: type = TokenType.ExportedType; goto IL_05b3; end_IL_0001: break; } return MetadataToken.Zero; } public static uint CompressMetadataToken(this CodedIndex self, MetadataToken token) { uint result = 0u; if (token.RID == 0) { return result; } switch (self) { case CodedIndex.TypeDefOrRef: result = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.TypeRef: return result | 1u; case TokenType.TypeSpec: return result | 2u; } break; case CodedIndex.HasConstant: result = token.RID << 2; switch (token.TokenType) { case TokenType.Field: return result | 0u; case TokenType.Param: return result | 1u; case TokenType.Property: return result | 2u; } break; case CodedIndex.HasCustomAttribute: result = token.RID << 5; switch (token.TokenType) { case TokenType.Method: return result | 0u; case TokenType.Field: return result | 1u; case TokenType.TypeRef: return result | 2u; case TokenType.TypeDef: return result | 3u; case TokenType.Param: return result | 4u; case TokenType.InterfaceImpl: return result | 5u; case TokenType.MemberRef: return result | 6u; case TokenType.Module: return result | 7u; case TokenType.Permission: return result | 8u; case TokenType.Property: return result | 9u; case TokenType.Event: return result | 0xAu; case TokenType.Signature: return result | 0xBu; case TokenType.ModuleRef: return result | 0xCu; case TokenType.TypeSpec: return result | 0xDu; case TokenType.Assembly: return result | 0xEu; case TokenType.AssemblyRef: return result | 0xFu; case TokenType.File: return result | 0x10u; case TokenType.ExportedType: return result | 0x11u; case TokenType.ManifestResource: return result | 0x12u; case TokenType.GenericParam: return result | 0x13u; case TokenType.GenericParamConstraint: return result | 0x14u; case TokenType.MethodSpec: return result | 0x15u; } break; case CodedIndex.HasFieldMarshal: result = token.RID << 1; switch (token.TokenType) { case TokenType.Field: return result | 0u; case TokenType.Param: return result | 1u; } break; case CodedIndex.HasDeclSecurity: result = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.Method: return result | 1u; case TokenType.Assembly: return result | 2u; } break; case CodedIndex.MemberRefParent: result = token.RID << 3; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.TypeRef: return result | 1u; case TokenType.ModuleRef: return result | 2u; case TokenType.Method: return result | 3u; case TokenType.TypeSpec: return result | 4u; } break; case CodedIndex.HasSemantics: result = token.RID << 1; switch (token.TokenType) { case TokenType.Event: return result | 0u; case TokenType.Property: return result | 1u; } break; case CodedIndex.MethodDefOrRef: result = token.RID << 1; switch (token.TokenType) { case TokenType.Method: return result | 0u; case TokenType.MemberRef: return result | 1u; } break; case CodedIndex.MemberForwarded: result = token.RID << 1; switch (token.TokenType) { case TokenType.Field: return result | 0u; case TokenType.Method: return result | 1u; } break; case CodedIndex.Implementation: result = token.RID << 2; switch (token.TokenType) { case TokenType.File: return result | 0u; case TokenType.AssemblyRef: return result | 1u; case TokenType.ExportedType: return result | 2u; } break; case CodedIndex.CustomAttributeType: result = token.RID << 3; switch (token.TokenType) { case TokenType.Method: return result | 2u; case TokenType.MemberRef: return result | 3u; } break; case CodedIndex.ResolutionScope: result = token.RID << 2; switch (token.TokenType) { case TokenType.Module: return result | 0u; case TokenType.ModuleRef: return result | 1u; case TokenType.AssemblyRef: return result | 2u; case TokenType.TypeRef: return result | 3u; } break; case CodedIndex.TypeOrMethodDef: result = token.RID << 1; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.Method: return result | 1u; } break; case CodedIndex.HasCustomDebugInformation: result = token.RID << 5; switch (token.TokenType) { case TokenType.Method: return result | 0u; case TokenType.Field: return result | 1u; case TokenType.TypeRef: return result | 2u; case TokenType.TypeDef: return result | 3u; case TokenType.Param: return result | 4u; case TokenType.InterfaceImpl: return result | 5u; case TokenType.MemberRef: return result | 6u; case TokenType.Module: return result | 7u; case TokenType.Permission: return result | 8u; case TokenType.Property: return result | 9u; case TokenType.Event: return result | 0xAu; case TokenType.Signature: return result | 0xBu; case TokenType.ModuleRef: return result | 0xCu; case TokenType.TypeSpec: return result | 0xDu; case TokenType.Assembly: return result | 0xEu; case TokenType.AssemblyRef: return result | 0xFu; case TokenType.File: return result | 0x10u; case TokenType.ExportedType: return result | 0x11u; case TokenType.ManifestResource: return result | 0x12u; case TokenType.GenericParam: return result | 0x13u; case TokenType.GenericParamConstraint: return result | 0x14u; case TokenType.MethodSpec: return result | 0x15u; case TokenType.Document: return result | 0x16u; case TokenType.LocalScope: return result | 0x17u; case TokenType.LocalVariable: return result | 0x18u; case TokenType.LocalConstant: return result | 0x19u; case TokenType.ImportScope: return result | 0x1Au; } break; } throw new ArgumentException(); } public static int GetSize(this CodedIndex self, Func<Table, int> counter) { int num; Table[] array; switch (self) { case CodedIndex.TypeDefOrRef: num = 2; array = new Table[3] { Table.TypeDef, Table.TypeRef, Table.TypeSpec }; break; case CodedIndex.HasConstant: num = 2; array = new Table[3] { Table.Field, Table.Param, Table.Property }; break; case CodedIndex.HasCustomAttribute: num = 5; array = new Table[22] { Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef, Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef, Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType, Table.ManifestResource, Table.GenericParam, Table.GenericParamConstraint, Table.MethodSpec }; break; case CodedIndex.HasFieldMarshal: num = 1; array = new Table[2] { Table.Field, Table.Param }; break; case CodedIndex.HasDeclSecurity: num = 2; array = new Table[3] { Table.TypeDef, Table.Method, Table.Assembly }; break; case CodedIndex.MemberRefParent: num = 3; array = new Table[5] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec }; break; case CodedIndex.HasSemantics: num = 1; array = new Table[2] { Table.Event, Table.Property }; break; case CodedIndex.MethodDefOrRef: num = 1; array = new Table[2] { Table.Method, Table.MemberRef }; break; case CodedIndex.MemberForwarded: num = 1; array = new Table[2] { Table.Field, Table.Method }; break; case CodedIndex.Implementation: num = 2; array = new Table[3] { Table.File, Table.AssemblyRef, Table.ExportedType }; break; case CodedIndex.CustomAttributeType: num = 3; array = new Table[2] { Table.Method, Table.MemberRef }; break; case CodedIndex.ResolutionScope: num = 2; array = new Table[4] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef }; break; case CodedIndex.TypeOrMethodDef: num = 1; array = new Table[2] { Table.TypeDef, Table.Method }; break; case CodedIndex.HasCustomDebugInformation: num = 5; array = new Table[27] { Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef, Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef, Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType, Table.ManifestResource, Table.GenericParam, Table.GenericParamConstraint, Table.MethodSpec, Table.Document, Table.LocalScope, Table.LocalVariable, Table.LocalConstant, Table.ImportScope }; break; default: throw new ArgumentException(); } int num2 = 0; for (int i = 0; i < array.Length; i++) { num2 = Math.Max(counter(array[i]), num2); } if (num2 >= 1 << 16 - num) { return 4; } return 2; } public static RSA CreateRSA(this StrongNameKeyPair key_pair) { if (!TryGetKeyContainer(key_pair, out var key, out var key_container)) { return CryptoConvert.FromCapiKeyBlob(key); } return new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore, KeyContainerName = key_container, KeyNumber = 2 }); } private static bool TryGetKeyContainer(ISerializable key_pair, out byte[] key, out string key_container) { SerializationInfo serializationInfo = new SerializationInfo(typeof(StrongNameKeyPair), new FormatterConverter()); key_pair.GetObjectData(serializationInfo, default(StreamingContext)); key = (byte[])serializationInfo.GetValue("_keyPairArray", typeof(byte[])); key_container = serializationInfo.GetString("_keyPairContainer"); return key_container != null; } } public struct ArrayDimension { private int? lower_bound; private int? upper_bound; public int? LowerBound { get { return lower_bound; } set { lower_bound = value; } } public int? UpperBound { get { return upper_bound; } set { upper_bound = value; } } public bool IsSized { get { if (!lower_bound.HasValue) { return upper_bound.HasValue; } return true; } } public ArrayDimension(int? lowerBound, int? upperBound) { lower_bound = lowerBound; upper_bound = upperBound; } public override string ToString() { if (IsSized) { return lower_bound + "..." + upper_bound; } return string.Empty; } } public sealed class ArrayType : TypeSpecification { private Collection<ArrayDimension> dimensions; public Collection<ArrayDimension> Dimensions { get { if (dimensions != null) { return dimensions; } dimensions = new Collection<ArrayDimension>(); dimensions.Add(default(ArrayDimension)); return dimensions; } } public int Rank { get { if (dimensions != null) { return dimensions.Count; } return 1; } } public bool IsVector { get { if (dimensions == null) { return true; } if (dimensions.Count > 1) { return false; } return !dimensions[0].IsSized; } } public override bool IsValueType { get { return false; } set { throw new InvalidOperationException(); } } public override string Name => base.Name + Suffix; public override string FullName => base.FullName + Suffix; private string Suffix { get { if (IsVector) { return "[]"; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("["); for (int i = 0; i < dimensions.Count; i++) { if (i > 0) { stringBuilder.Append(","); } stringBuilder.Append(dimensions[i].ToString()); } stringBuilder.Append("]"); return stringBuilder.ToString(); } } public override bool IsArray => true; public ArrayType(TypeReference type) : base(type) { Mixin.CheckType(type); etype = Mono.Cecil.Metadata.ElementType.Array; } public ArrayType(TypeReference type, int rank) : this(type) { Mixin.CheckType(type); if (rank != 1) { dimensions = new Collection<ArrayDimension>(rank); for (int i = 0; i < rank; i++) { dimensions.Add(default(ArrayDimension)); } etype = Mono.Cecil.Metadata.ElementType.Array; } } } public sealed class AssemblyDefinition : ICustomAttributeProvider, IMetadataTokenProvider, ISecurityDeclarationProvider, IDisposable { private AssemblyNameDefinition name; internal ModuleDefinition main_module; private Collection<ModuleDefinition> modules; private Collection<CustomAttribute> custom_attributes; private Collection<SecurityDeclaration> security_declarations; public AssemblyNameDefinition Name { get { return name; } set { name = value; } } public string FullName { get { if (name == null) { return string.Empty; } return name.FullName; } } public MetadataToken MetadataToken { get { return new MetadataToken(TokenType.Assembly, 1); } set { } } public Collection<ModuleDefinition> Modules { get { if (modules != null) { return modules; } if (main_module.HasImage) { return main_module.Read(ref modules, this, (AssemblyDefinition _, MetadataReader reader) => reader.ReadModules()); } return modules = new Collection<ModuleDefinition>(1) { main_module }; } } public ModuleDefinition MainModule => main_module; public MethodDefinition EntryPoint { get { return main_module.EntryPoint; } set { main_module.EntryPoint = value; } } public bool HasCustomAttributes { get { if (custom_attributes != null) { return custom_attributes.Count > 0; } return this.GetHasCustomAttributes(main_module); } } public Collection<CustomAttribute> CustomAttributes => custom_attributes ?? this.GetCustomAttributes(ref custom_attributes, main_module); public bool HasSecurityDeclarations { get { if (security_declarations != null) { return security_declarations.Count > 0; } return this.GetHasSecurityDeclarations(main_module); } } public Collection<SecurityDeclaration> SecurityDeclarations => security_declarations ?? this.GetSecurityDeclarations(ref security_declarations, main_module); internal AssemblyDefinition() { } public void Dispose() { if (modules == null) { main_module.Dispose(); return; } Collection<ModuleDefinition> collection = Modules; for (int i = 0; i < collection.Count; i++) { collection[i].Dispose(); } } public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind) { return CreateAssembly(assemblyName, moduleName, new ModuleParameters { Kind = kind }); } public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleParameters parameters) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } Mixin.CheckParameters(parameters); if (parameters.Kind == ModuleKind.NetModule) { throw new ArgumentException("kind"); } AssemblyDefinition assembly = ModuleDefinition.CreateModule(moduleName, parameters).Assembly; assembly.Name = assemblyName; return assembly; } public static AssemblyDefinition ReadAssembly(string fileName) { return ReadAssembly(ModuleDefinition.ReadModule(fileName)); } public static AssemblyDefinition ReadAssembly(string fileName, ReaderParameters parameters) { return ReadAssembly(ModuleDefinition.ReadModule(fileName, parameters)); } public static AssemblyDefinition ReadAssembly(Stream stream) { return ReadAssembly(ModuleDefinition.ReadModule(stream)); } public static AssemblyDefinition ReadAssembly(Stream stream, ReaderParameters parameters) { return ReadAssembly(ModuleDefinition.ReadModule(stream, parameters)); } private static AssemblyDefinition ReadAssembly(ModuleDefinition module) { return module.Assembly ?? throw new ArgumentException(); } public void Write(string fileName) { Write(fileName, new WriterParameters()); } public void Write(string fileName, WriterParameters parameters) { main_module.Write(fileName, parameters); } public void Write() { main_module.Write(); } public void Write(WriterParameters parameters) { main_module.Write(parameters); } public void Write(Stream stream) { Write(stream, new WriterParameters()); } public void Write(Stream stream, WriterParameters parameters) { main_module.Write(stream, parameters); } public override string ToString() { return FullName; } } [Flags] public enum AssemblyAttributes : uint { PublicKey = 1u, SideBySideCompatible = 0u, Retargetable = 0x100u, WindowsRuntime = 0x200u, DisableJITCompileOptimizer = 0x4000u, EnableJITCompileTracking = 0x8000u } public enum AssemblyHashAlgorithm : uint { None = 0u, Reserved = 32771u, SHA1 = 32772u } public sealed class AssemblyLinkedResource : Resource { private AssemblyNameReference reference; public AssemblyNameReference Assembly { get { return reference; } set { reference = value; } } public override ResourceType ResourceType => ResourceType.AssemblyLinked; public AssemblyLinkedResource(string name, ManifestResourceAttributes flags) : base(name, flags) { } public AssemblyLinkedResource(string name, ManifestResourceAttributes flags, AssemblyNameReference reference) : base(name, flags) { this.reference = reference; } } public sealed class AssemblyNameDefinition : AssemblyNameReference { public override byte[] Hash => Empty<byte>.Array; internal AssemblyNameDefinition() { token = new MetadataToken(TokenType.Assembly, 1); } public AssemblyNameDefinition(string name, Version version) : base(name, version) { token = new MetadataToken(TokenType.Assembly, 1); } } public class AssemblyNameReference : IMetadataScope, IMetadataTokenProvider { private string name; private string culture; private Version version; private uint attributes; private byte[] public_key; private byte[] public_key_token; private AssemblyHashAlgorithm hash_algorithm; private byte[] hash; internal MetadataToken token; private string full_name; public string Name { get { return name; } set { name = value; full_name = null; } } public string Culture { get { return culture; } set { culture = value; full_name = null; } } public Version Version { get { return version; } set { version = Mixin.CheckVersion(value); full_name = null; } } public AssemblyAttributes Attributes { get { return (AssemblyAttributes)attributes; } set { attributes = (uint)value; } } public bool HasPublicKey { get { return attributes.GetAttributes(1u); } set { attributes = attributes.SetAttributes(1u, value); } } public bool IsSideBySideCompatible { get { return attributes.GetAttributes(0u); } set { attributes = attributes.SetAttributes(0u, value); } } public bool IsRetargetable { get { return attributes.GetAttributes(256u); } set { attributes = attributes.SetAttributes(256u, value); } } public bool IsWindowsRuntime { get { return attributes.GetAttributes(512u); } set { attributes = attributes.SetAttributes(512u, value); } } public byte[] PublicKey { get { return public_key ?? Empty<byte>.Array; } set { public_key = value; HasPublicKey = !public_key.IsNullOrEmpty(); public_key_token = Empty<byte>.Array; full_name = null; } } public byte[] PublicKeyToken { get { if (public_key_token.IsNullOrEmpty() && !public_key.IsNullOrEmpty()) { byte[] array = HashPublicKey(); byte[] array2 = new byte[8]; Array.Copy(array, array.Length - 8, array2, 0, 8); Array.Reverse((Array)array2, 0, 8); public_key_token = array2; } return public_key_token ?? Empty<byte>.Array; } set { public_key_token = value; full_name = null; } } public virtual MetadataScopeType MetadataScopeType => MetadataScopeType.AssemblyNameReference; public string FullName { get { if (full_name != null) { return full_name; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(name); stringBuilder.Append(", "); stringBuilder.Append("Version="); stringBuilder.Append(version.ToString(4)); stringBuilder.Append(", "); stringBuilder.Append("Culture="); stringBuilder.Append(string.IsNullOrEmpty(culture) ? "neutral" : culture); stringBuilder.Append(", "); stringBuilder.Append("PublicKeyToken="); byte[] publicKeyToken = PublicKeyToken; if (!publicKeyToken.IsNullOrEmpty() && publicKeyToken.Length != 0) { for (int i = 0; i < publicKeyToken.Length; i++) { stringBuilder.Append(publicKeyToken[i].ToString("x2")); } } else { stringBuilder.Append("null"); } if (IsRetargetable) { stringBuilder.Append(", "); stringBuilder.Append("Retargetable=Yes"); } return full_name = stringBuilder.ToString(); } } public AssemblyHashAlgorithm HashAlgorithm { get { return hash_algorithm; } set { hash_algorithm = value; } } public virtual byte[] Hash { get { return hash; } set { hash = value; } } public MetadataToken MetadataToken { get { return token; } set { token = value; } } private byte[] HashPublicKey() { AssemblyHashAlgorithm assemblyHashAlgorithm = hash_algorithm; HashAlgorithm hashAlgorithm = ((assemblyHashAlgorithm != AssemblyHashAlgorithm.Reserved) ? ((HashAlgorithm)SHA1.Create()) : ((HashAlgorithm)MD5.Create())); using (hashAlgorithm) { return hashAlgorithm.ComputeHash(public_key); } } public static AssemblyNameReference Parse(string fullName) { if (fullName == null) { throw new ArgumentNullException("fullName"); } if (fullName.Length == 0) { throw new ArgumentException("Name can not be empty"); } AssemblyNameReference assemblyNameReference = new AssemblyNameReference(); string[] array = fullName.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (i == 0) { assemblyNameReference.Name = text; continue; } string[] array2 = text.Split(new char[1] { '=' }); if (array2.Length != 2) { throw new ArgumentException("Malformed name"); } switch (array2[0].ToLowerInvariant()) { case "version": assemblyNameReference.Version = new Version(array2[1]); break; case "culture": assemblyNameReference.Culture = ((array2[1] == "neutral") ? "" : array2[1]); break; case "publickeytoken": { string text2 = array2[1]; if (!(text2 == "null")) { assemblyNameReference.PublicKeyToken = new byte[text2.Length / 2]; for (int j = 0; j < assemblyNameReference.PublicKeyToken.Length; j++) { assemblyNameReference.PublicKeyToken[j] = byte.Parse(text2.Substring(j * 2, 2), NumberStyles.HexNumber); } } break; } } } return assemblyNameReference; } internal AssemblyNameReference() { version = Mixin.ZeroVersion; token = new MetadataToken(TokenType.AssemblyRef); } public AssemblyNameReference(string name, Version version) { Mixin.CheckName(name); this.name = name; this.version = Mixin.CheckVersion(version); hash_algorithm = AssemblyHashAlgorithm.None; token = new MetadataToken(TokenType.AssemblyRef); } public override string ToString() { return FullName; } } internal abstract class ModuleReader { protected readonly ModuleDefinition module; protected ModuleReader(Image image, ReadingMode mode) { module = new ModuleDefinition(image); module.ReadingMode = mode; } protected abstract void ReadModule(); public abstract void ReadSymbols(ModuleDefinition module); protected void ReadModuleManifest(MetadataReader reader) { reader.Populate(module); ReadAssembly(reader); } private void ReadAssembly(MetadataReader reader) { AssemblyNameDefinition assemblyNameDefinition = reader.ReadAssemblyNameDefinition(); if (assemblyNameDefinition == null) { module.kind = ModuleKind.NetModule; return; } AssemblyDefinition assemblyDefinition = new AssemblyDefinition(); assemblyDefinition.Name = assemblyNameDefinition; module.assembly = assemblyDefinition; assemblyDefinition.main_module = module; } public static ModuleDefinition CreateModule(Image image, ReaderParameters parameters) { ModuleReader moduleReader = CreateModuleReader(image, parameters.ReadingMode); ModuleDefinition moduleDefinition = moduleReader.module; if (parameters.assembly_resolver != null) { moduleDefinition.assembly_resolver = Disposable.NotOwned(parameters.assembly_resolver); } if (parameters.metadata_resolver != null) { moduleDefinition.metadata_resolver = parameters.metadata_resolver; } if (parameters.metadata_importer_provider != null) { moduleDefinition.metadata_importer = parameters.metadata_importer_provider.GetMetadataImporter(moduleDefinition); } if (parameters.reflection_importer_provider != null) { moduleDefinition.reflection_importer = parameters.reflection_importer_provider.GetReflectionImporter(moduleDefinition); } GetMetadataKind(moduleDefinition, parameters); moduleReader.ReadModule(); ReadSymbols(moduleDefinition, parameters); moduleReader.ReadSymbols(moduleDefinition); if (parameters.ReadingMode == ReadingMode.Immediate) { moduleDefinition.MetadataSystem.Clear(); } return moduleDefinition; } private static void ReadSymbols(ModuleDefinition module, ReaderParameters parameters) { ISymbolReaderProvider symbolReaderProvider = parameters.SymbolReaderProvider; if (symbolReaderProvider == null && parameters.ReadSymbols) { symbolReaderProvider = new DefaultSymbolReaderProvider(); } if (symbolReaderProvider != null) { module.SymbolReaderProvider = symbolReaderProvider; ISymbolReader symbolReader = ((parameters.SymbolStream != null) ? symbolReaderProvider.GetSymbolReader(module, parameters.SymbolStream) : symbolReaderProvider.GetSymbolReader(module, module.FileName)); if (symbolReader != null) { try { module.ReadSymbols(symbolReader, parameters.ThrowIfSymbolsAreNotMatching); } catch (Exception) { symbolReader.Dispose(); throw; } } } if (module.Image.HasDebugTables()) { module.ReadSymbols(new PortablePdbReader(module.Image, module)); } } private static void GetMetadataKind(ModuleDefinition module, ReaderParameters parameters) { if (!parameters.ApplyWindowsRuntimeProjections) { module.MetadataKind = MetadataKind.Ecma335; return; } string runtimeVersion = module.RuntimeVersion; if (!runtimeVersion.Contains("WindowsRuntime")) { module.MetadataKind = MetadataKind.Ecma335; } else if (runtimeVersion.Contains("CLR")) { module.MetadataKind = MetadataKind.ManagedWindowsMetadata; } else { module.MetadataKind = MetadataKind.WindowsMetadata; } } private static ModuleReader CreateModuleReader(Image image, ReadingMode mode) { return mode switch { ReadingMode.Immediate => new ImmediateModuleReader(image), ReadingMode.Deferred => new DeferredModuleReader(image), _ => throw new ArgumentException(), }; } } internal sealed class ImmediateModuleReader : ModuleReader { private bool resolve_attributes; public ImmediateModuleReader(Image image) : base(image, ReadingMode.Immediate) { } protected override void ReadModule() { module.Read(module, delegate(ModuleDefinition module, MetadataReader reader) { ReadModuleManifest(reader); ReadModule(module, resolve_attributes: true); }); } public void ReadModule(ModuleDefinition module, bool resolve_attributes) { this.resolve_attributes = resolve_attributes; if (module.HasAssemblyReferences) { Mixin.Read(module.AssemblyReferences); } if (module.HasResources) { Mixin.Read(module.Resources); } if (module.HasModuleReferences) { Mixin.Read(module.ModuleReferences); } if (module.HasTypes) { ReadTypes(module.Types); } if (module.HasExportedTypes) { Mixin.Read(module.ExportedTypes); } ReadCustomAttributes(module); AssemblyDefinition assembly = module.Assembly; if (assembly != null) { ReadCustomAttributes(assembly); ReadSecurityDeclarations(assembly); } } private void ReadTypes(Collection<TypeDefinition> types) { for (int i = 0; i < types.Count; i++) { ReadType(types[i]); } } private void ReadType(TypeDefinition type) { ReadGenericParameters(type); if (type.HasInterfaces) { ReadInterfaces(type); } if (type.HasNestedTypes) { ReadTypes(type.NestedTypes); } if (type.HasLayoutInfo) { Mixin.Read(type.ClassSize); } if (type.HasFields) { ReadFields(type); } if (type.HasMethods) { ReadMethods(type); } if (type.HasProperties) { ReadProperties(type); } if (type.HasEvents) { ReadEvents(type); } ReadSecurityDeclarations(type); ReadCustomAttributes(type); } private void ReadInterfaces(TypeDefinition type) { Collection<InterfaceImplementation> interfaces = type.Interfaces; for (int i = 0; i < interfaces.Count; i++) { ReadCustomAttributes(interfaces[i]); } } private void ReadGenericParameters(IGenericParameterProvider provider) { if (!provider.HasGenericParameters) { return; } Collection<GenericParameter> genericParameters = provider.GenericParameters; for (int i = 0; i < genericParameters.Count; i++) { GenericParameter genericParameter = genericParameters[i]; if (genericParameter.HasConstraints) { Mixin.Read(genericParameter.Constraints); } ReadCustomAttributes(genericParameter); } } private void ReadSecurityDeclarations(ISecurityDeclarationProvider provider) { if (!provider.HasSecurityDeclarations) { return; } Collection<SecurityDeclaration> securityDeclarations = provider.SecurityDeclarations; if (resolve_attributes) { for (int i = 0; i < securityDeclarations.Count; i++) { Mixin.Read(securityDeclarations[i].SecurityAttributes); } } } private void ReadCustomAttributes(ICustomAttributeProvider provider) { if (!provider.HasCustomAttributes) { return; } Collection<CustomAttribute> customAttributes = provider.CustomAttributes; if (resolve_attributes) { for (int i = 0; i < customAttributes.Count; i++) { Mixin.Read(customAttributes[i].ConstructorArguments); } } } private void ReadFields(TypeDefinition type) { Collection<FieldDefinition> fields = type.Fields; for (int i = 0; i < fields.Count; i++) { FieldDefinition fieldDefinition = fields[i]; if (fieldDefinition.HasConstant) { Mixin.Read(fieldDefinition.Constant); } if (fieldDefinition.HasLayoutInfo) { Mixin.Read(fieldDefinition.Offset); } if (fieldDefinition.RVA > 0) { Mixin.Read(fieldDefinition.InitialValue); } if (fieldDefinition.HasMarshalInfo) { Mixin.Read(fieldDefinition.MarshalInfo); } ReadCustomAttributes(fieldDefinition); } } private void ReadMethods(TypeDefinition type) { Collection<MethodDefinition> methods = type.Methods; for (int i = 0; i < methods.Count; i++) { MethodDefinition methodDefinition = methods[i]; ReadGenericParameters(methodDefinition); if (methodDefinition.HasParameters) { ReadParameters(methodDefinition); } if (methodDefinition.HasOverrides) { Mixin.Read(methodDefinition.Overrides); } if (methodDefinition.IsPInvokeImpl) { Mixin.Read(methodDefinition.PInvokeInfo); } ReadSecurityDeclarations(methodDefinition); ReadCustomAttributes(methodDefinition); MethodReturnType methodReturnType = methodDefinition.MethodReturnType; if (methodReturnType.HasConstant) { Mixin.Read(methodReturnType.Constant); } if (methodReturnType.HasMarshalInfo) { Mixin.Read(methodReturnType.MarshalInfo); } ReadCustomAttributes(methodReturnType); } } private void ReadParameters(MethodDefinition method) { Collection<ParameterDefinition> parameters = method.Parameters; for (int i = 0; i < parameters.Count; i++) { ParameterDefinition parameterDefinition = parameters[i]; if (parameterDefinition.HasConstant) { Mixin.Read(parameterDefinition.Constant); } if (parameterDefinition.HasMarshalInfo) { Mixin.Read(parameterDefinition.MarshalInfo); } ReadCustomAttributes(parameterDefinition); } } private void ReadProperties(TypeDefinition type) { Collection<PropertyDefinition> properties = type.Properties; for (int i = 0; i < properties.Count; i++) { PropertyDefinition propertyDefinition = properties[i]; Mixin.Read(propertyDefinition.GetMethod); if (propertyDefinition.HasConstant) { Mixin.Read(propertyDefinition.Constant); } ReadCustomAttributes(propertyDefinition); } } private void ReadEvents(TypeDefinition type) { Collection<EventDefinition> events = type.Events; for (int i = 0; i < events.Count; i++) { EventDefinition eventDefinition = events[i]; Mixin.Read(eventDefinition.AddMethod); ReadCustomAttributes(eventDefinition); } } public override void ReadSymbols(ModuleDefinition module) { if (module.symbol_reader != null) { ReadTypesSymbols(module.Types, module.symbol_reader); } } private void ReadTypesSymbols(Collection<TypeDefinition> types, ISymbolReader symbol_reader) { for (int i = 0; i < types.Count; i++) { TypeDefinition typeDefinition = types[i]; if (typeDefinition.HasNestedTypes) { ReadTypesSymbols(typeDefinition.NestedTypes, symbol_reader); } if (typeDefinition.HasMethods) { ReadMethodsSymbols(typeDefinition, symbol_reader); } } } private void ReadMethodsSymbols(TypeDefinition type, ISymbolReader symbol_reader) { Collection<MethodDefinition> methods = type.Methods; for (int i = 0; i < methods.Count; i++) { MethodDefinition methodDefinition = methods[i]; if (methodDefinition.HasBody && methodDefinition.token.RID != 0 && methodDefinition.debug_info == null) { methodDefinition.debug_info = symbol_reader.Read(methodDefinition); } } } } internal sealed class DeferredModuleReader : ModuleReader { public DeferredModuleReader(Image image) : base(image, ReadingMode.Deferred) { } protected override void ReadModule() { module.Read(module, delegate(ModuleDefinition _, MetadataReader reader) { ReadModuleManifest(reader); }); } public override void ReadSymbols(ModuleDefinition module) { } } internal sealed class MetadataReader : ByteBuffer { internal readonly Image image; internal readonly ModuleDefinition module; internal readonly MetadataSystem metadata; internal CodeReader code; internal IGenericContext context; private readonly MetadataReader metadata_reader; public MetadataReader(ModuleDefinition module) : base(module.Image.TableHeap.data) { image = module.Image; this.module = module; metadata = module.MetadataSystem; code = new CodeReader(this); } public MetadataReader(Image image, ModuleDefinition module, MetadataReader metadata_reader) : base(image.TableHeap.data) { this.image = image; this.module = module; metadata = module.MetadataSystem; this.metadata_reader = metadata_reader; } private int GetCodedIndexSize(CodedIndex index) { return image.GetCodedIndexSize(index); } private uint ReadByIndexSize(int size) { if (size == 4) { return ReadUInt32(); } return ReadUInt16(); } private byte[] ReadBlob() { BlobHeap blobHeap = image.BlobHeap; if (blobHeap == null) { position += 2; return Empty<byte>.Array; } return blobHeap.Read(ReadBlobIndex()); } private byte[] ReadBlob(uint signature) { BlobHeap blobHeap = image.BlobHeap; if (blobHeap == null) { return Empty<byte>.Array; } return blobHeap.Read(signature); } private uint ReadBlobIndex() { return ReadByIndexSize(image.BlobHeap?.IndexSize ?? 2); } private void GetBlobView(uint signature, out byte[] blob, out int index, out int count) { BlobHeap blobHeap = image.BlobHeap; if (blobHeap == null) { blob = null; index = (count = 0); } else { blobHeap.GetView(signature, out blob, out index, out count); } } private string ReadString() { return image.StringHeap.Read(ReadByIndexSize(image.StringHeap.IndexSize)); } private uint ReadStringIndex() { return ReadByIndexSize(image.StringHeap.IndexSize); } private Guid ReadGuid() { return image.GuidHeap.Read(ReadByIndexSize(image.GuidHeap.IndexSize)); } private uint ReadTableIndex(Table table) { return ReadByIndexSize(image.GetTableIndexSize(table)); } private MetadataToken ReadMetadataToken(CodedIndex index) { return index.GetMetadataToken(ReadByIndexSize(GetCodedIndexSize(index))); } private int MoveTo(Table table) { TableInformation tableInformation = image.TableHeap[table]; if (tableInformation.Length != 0) { position = (int)tableInformation.Offset; } return (int)tableInformation.Length; } private bool MoveTo(Table table, uint row) { TableInformation tableInformation = image.TableHeap[table]; uint num = tableInformation.Length; if (num == 0 || row > num) { return false; } position = (int)(tableInformation.Offset + tableInformation.RowSize * (row - 1)); return true; } public AssemblyNameDefinition ReadAssemblyNameDefinition() { if (MoveTo(Table.Assembly) == 0) { return null; } AssemblyNameDefinition assemblyNameDefinition = new AssemblyNameDefinition(); assemblyNameDefinition.HashAlgorithm = (AssemblyHashAlgorithm)ReadUInt32(); PopulateVersionAndFlags(assemblyNameDefinition); assemblyNameDefinition.PublicKey = ReadBlob(); PopulateNameAndCulture(assemblyNameDefinition); return assemblyNameDefinition; } public ModuleDefinition Populate(ModuleDefinition module) { if (MoveTo(Table.Module) == 0) { return module; } Advance(2); module.Name = ReadString(); module.Mvid = ReadGuid(); return module; } private void InitializeAssemblyReferences() { if (metadata.AssemblyReferences != null) { return; } int num = MoveTo(Table.AssemblyRef); AssemblyNameReference[] array = (metadata.AssemblyReferences = new AssemblyNameReference[num]); for (uint num2 = 0u; num2 < num; num2++) { AssemblyNameReference assemblyNameReference = new AssemblyNameReference(); assemblyNameReference.token = new MetadataToken(TokenType.AssemblyRef, num2 + 1); PopulateVersionAndFlags(assemblyNameReference); byte[] array2 = ReadBlob(); if (assemblyNameReference.HasPublicKey) { assemblyNameReference.PublicKey = array2; } else { assemblyNameReference.PublicKeyToken = array2; } PopulateNameAndCulture(assemblyNameReference); assemblyNameReference.Hash = ReadBlob(); array[num2] = assemblyNameReference; } } public Collection<AssemblyNameReference> ReadAssemblyReferences() { InitializeAssemblyReferences(); Collection<AssemblyNameReference> collection = new Collection<AssemblyNameReference>(metadata.AssemblyReferences); if (module.IsWindowsMetadata()) { module.Projections.AddVirtualReferences(collection); } return collection; } public MethodDefinition ReadEntryPoint() { if (module.Image.EntryPointToken == 0) { return null; } return GetMethodDefinition(new MetadataToken(module.Image.EntryPointToken).RID); } public Collection<ModuleDefinition> ReadModules() { Collection<ModuleDefinition> collection = new Collection<ModuleDefinition>(1); collection.Add(module); int num = MoveTo(Table.File); for (uint num2 = 1u; num2 <= num; num2++) { uint num3 = ReadUInt32(); string name = ReadString(); ReadBlobIndex(); if (num3 == 0) { ReaderParameters parameters = new ReaderParameters { ReadingMode = module.ReadingMode, SymbolReaderProvider = module.SymbolReaderProvider, AssemblyResolver = module.AssemblyResolver }; collection.Add(ModuleDefinition.ReadModule(GetModuleFileName(name), parameters)); } } return collection; } private string GetModuleFileName(string name) { if (module.FileName == null) { throw new NotSupportedException(); } return Path.Combine(Path.GetDirectoryName(module.FileName), name); } private void InitializeModuleReferences() { if (metadata.ModuleReferences == null) { int num = MoveTo(Table.ModuleRef); ModuleReference[] array = (metadata.ModuleReferences = new ModuleReference[num]); for (uint num2 = 0u; num2 < num; num2++) { ModuleReference moduleReference = new ModuleReference(ReadString()); moduleReference.token = new MetadataToken(TokenType.ModuleRef, num2 + 1); array[num2] = moduleReference; } } } public Collection<ModuleReference> ReadModuleReferences() { InitializeModuleReferences(); return new Collection<ModuleReference>(metadata.ModuleReferences); } public bool HasFileResource() { int num = MoveTo(Table.File); if (num == 0) { return false; } for (uint num2 = 1u; num2 <= num; num2++) { if (ReadFileRecord(num2).Col1 == FileAttributes.ContainsNoMetaData) { return true; } } return false; } public Collection<Resource> ReadResources() { int num = MoveTo(Table.ManifestResource); Collection<Resource> collection = new Collection<Resource>(num); for (int i = 1; i <= num; i++) { uint offset = ReadUInt32(); ManifestResourceAttributes manifestResourceAttributes = (ManifestResourceAttributes)ReadUInt32(); string name = ReadString(); MetadataToken scope = ReadMetadataToken(CodedIndex.Implementation); Resource item; if (scope.RID == 0) { item = new EmbeddedResource(name, manifestResourceAttributes, offset, this); } else if (scope.TokenType == TokenType.AssemblyRef) { item = new AssemblyLinkedResource(name, manifestResourceAttributes) { Assembly = (AssemblyNameReference)GetTypeReferenceScope(scope) }; } else { if (scope.TokenType != TokenType.File) { continue; } Row<FileAttributes, string, uint> row = ReadFileRecord(scope.RID); item = new LinkedResource(name, manifestResourceAttributes) { File = row.Col2, hash = ReadBlob(row.Col3) }; } collection.Add(item); } return collection; } private Row<FileAttributes, string, uint> ReadFileRecord(uint rid) { int num = position; if (!MoveTo(Table.File, rid)) { throw new ArgumentException(); } Row<FileAttributes, string, uint> result = new Row<FileAttributes, string, uint>((FileAttributes)ReadUInt32(), ReadString(), ReadBlobIndex()); position = num; return result; } public byte[] GetManagedResource(uint offset) { return image.GetReaderAt(image.Resources.VirtualAddress, offset, delegate(uint o, BinaryStreamReader reader) { reader.Advance((int)o); return reader.ReadBytes(reader.ReadInt32()); }) ?? Empty<byte>.Array; } private void PopulateVersionAndFlags(AssemblyNameReference name) { name.Version = new Version(ReadUInt16(), ReadUInt16(), ReadUInt16(), ReadUInt16()); name.Attributes = (AssemblyAttributes)ReadUInt32(); } private void PopulateNameAndCulture(AssemblyNameReference name) { name.Name = ReadString(); name.Culture = ReadString(); } public TypeDefinitionCollection ReadTypes() { InitializeTypeDefinitions(); TypeDefinition[] types = metadata.Types; int capacity = types.Length - metadata.NestedTypes.Count; TypeDefinitionCollection typeDefinitionCollection = new TypeDefinitionCollection(module, capacity); foreach (TypeDefinition typeDefinition in types) { if (!IsNested(typeDefinition.Attributes)) { typeDefinitionCollection.Add(typeDefinition); } } if (image.HasTable(Table.MethodPtr) || image.HasTable(Table.FieldPtr)) { CompleteTypes(); } return typeDefinitionCollection; } private void CompleteTypes() { TypeDefinition[] types = metadata.Types; foreach (TypeDefinition obj in types) { Mixin.Read(obj.Fields); Mixin.Read(obj.Methods); } } private void InitializeTypeDefinitions() { if (metadata.Types != null) { return; } InitializeNestedTypes(); InitializeFields(); InitializeMethods(); int num = MoveTo(Table.TypeDef); TypeDefinition[] array = (metadata.Types = new TypeDefinition[num]); for (uint num2 = 0u; num2 < num; num2++) { if (array[num2] == null) { array[num2] = ReadType(num2 + 1); } } if (module.IsWindowsMetadata()) { for (uint num3 = 0u; num3 < num; num3++) { WindowsRuntimeProjections.Project(array[num3]); } } } private static bool IsNested(TypeAttributes attributes) { switch (attributes & TypeAttributes.VisibilityMask) { case TypeAttributes.NestedPublic: case TypeAttributes.NestedPrivate: case TypeAttributes.NestedFamily: case TypeAttributes.NestedAssembly: case TypeAttributes.NestedFamANDAssem: case TypeAttributes.VisibilityMask: return true; default: return false; } } public bool HasNestedTypes(TypeDefinition type) { InitializeNestedTypes(); if (!metadata.TryGetNestedTypeMapping(type, out var mapping)) { return false; } return mapping.Count > 0; } public Collection<TypeDefinition> ReadNestedTypes(TypeDefinition type) { InitializeNestedTypes(); if (!metadata.TryGetNestedTypeMapping(type, out var mapping)) { return new MemberDefinitionCollection<TypeDefinition>(type); } MemberDefinitionCollection<TypeDefinition> memberDefinitionCollection = new MemberDefinitionCollection<TypeDefinition>(type, mapping.Count); for (int i = 0; i < mapping.Count; i++) { TypeDefinition typeDefinition = GetTypeDefinition(mapping[i]); if (typeDefinition != null) { memberDefinitionCollection.Add(typeDefinition); } } metadata.RemoveNestedTypeMapping(type); return memberDefinitionCollection; } private void InitializeNestedTypes() { if (metadata.NestedTypes != null) { return; } int num = MoveTo(Table.NestedClass); metadata.NestedTypes = new Dictionary<uint, Collection<uint>>(num); metadata.ReverseNestedTypes = new Dictionary<uint, uint>(num); if (num != 0) { for (int i = 1; i <= num; i++) { uint nested = ReadTableIndex(Table.TypeDef); uint declaring = ReadTableIndex(Table.TypeDef); AddNestedMapping(declaring, nested); } } } private void AddNestedMapping(uint declaring, uint nested) { metadata.SetNestedTypeMapping(declaring, AddMapping(metadata.NestedTypes, declaring, nested)); metadata.SetReverseNestedTypeMapping(nested, declaring); } private static Collection<TValue> AddMapping<TKey, TValue>(Dictionary<TKey, Collection<TValue>> cache, TKey key, TValue value) { if (!cache.TryGetValue(key, out var value2)) { value2 = new Collection<TValue>(); } value2.Add(value); return value2; } private TypeDefinition ReadType(uint rid) { if (!MoveTo(Table.TypeDef, rid)) { return null; } TypeAttributes attributes = (TypeAttributes)ReadUInt32(); string name = ReadString(); TypeDefinition typeDefinition = new TypeDefinition(ReadString(), name, attributes); typeDefinition.token = new MetadataToken(TokenType.TypeDef, rid); typeDefinition.scope = module; typeDefinition.module = module; metadata.AddTypeDefinition(typeDefinition); context = typeDefinition; typeDefinition.BaseType = GetTypeDefOrRef(ReadMetadataToken(CodedIndex.TypeDefOrRef)); typeDefinition.fields_range = ReadListRange(rid, Table.TypeDef, Table.Field); typeDefinition.methods_range = ReadListRange(rid, Table.TypeDef, Table.Method); if (IsNested(attributes)) { typeDefinition.DeclaringType = GetNestedTypeDeclaringType(typeDefinition); } return typeDefinition; } private TypeDefinition GetNestedTypeDeclaringType(TypeDefinition type) { if (!metadata.TryGetReverseNestedTypeMapping(type, out var declaring)) { return null; } metadata.RemoveReverseNestedTypeMapping(type); return GetTypeDefinition(declaring); } private Range ReadListRange(uint current_index, Table current, Table target) { Range result = default(Range); uint num = ReadTableIndex(target); if (num == 0) { return result; } TableInformation tableInformation = image.TableHeap[current]; uint num2; if (current_index == tableInformation.Length) { num2 = image.TableHeap[target].Length + 1; } else { int num3 = position; position += (int)(tableInformation.RowSize - image.GetTableIndexSize(target)); num2 = ReadTableIndex(target); position = num3; } result.Start = num; result.Length = num2 - num; return result; } public Row<short, int> ReadTypeLayout(TypeDefinition type) { InitializeTypeLayouts(); uint rID = type.token.RID; if (!metadata.ClassLayouts.TryGetValue(rID, out var value)) { return new Row<short, int>(-1, -1); } type.PackingSize = (short)value.Col1; type.ClassSize = (int)value.Col2; metadata.ClassLayouts.Remove(rID); return new Row<short, int>((short)value.Col1, (int)value.Col2); } private void InitializeTypeLayouts() { if (metadata.ClassLayouts == null) { int num = MoveTo(Table.ClassLayout); Dictionary<uint, Row<ushort, uint>> dictionary = (metadata.ClassLayouts = new Dictionary<uint, Row<ushort, uint>>(num)); for (uint num2 = 0u;
UMM/Mods/Runtime Unity Editor/Mono.Cecil.Mdb.dll
Decompiled a month agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.SymbolStore; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using Mono.Cecil.Cil; using Mono.Collections.Generic; using Mono.CompilerServices.SymbolWriter; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.10.4.0")] [assembly: AssemblyInformationalVersion("0.10.4.0")] [assembly: AssemblyTitle("Mono.Cecil.Mdb")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("0.10.4.0")] namespace Mono.CompilerServices.SymbolWriter { public class MonoSymbolFileException : Exception { public MonoSymbolFileException() { } public MonoSymbolFileException(string message, params object[] args) : base(string.Format(message, args)) { } public MonoSymbolFileException(string message, Exception innerException) : base(message, innerException) { } } internal sealed class MyBinaryWriter : BinaryWriter { public MyBinaryWriter(Stream stream) : base(stream) { } public void WriteLeb128(int value) { Write7BitEncodedInt(value); } } internal class MyBinaryReader : BinaryReader { public MyBinaryReader(Stream stream) : base(stream) { } public int ReadLeb128() { return Read7BitEncodedInt(); } public string ReadString(int offset) { long position = BaseStream.Position; BaseStream.Position = offset; string result = ReadString(); BaseStream.Position = position; return result; } } public interface ISourceFile { SourceFileEntry Entry { get; } } public interface ICompileUnit { CompileUnitEntry Entry { get; } } public interface IMethodDef { string Name { get; } int Token { get; } } public class MonoSymbolFile : IDisposable { private List<MethodEntry> methods = new List<MethodEntry>(); private List<SourceFileEntry> sources = new List<SourceFileEntry>(); private List<CompileUnitEntry> comp_units = new List<CompileUnitEntry>(); private Dictionary<int, AnonymousScopeEntry> anonymous_scopes; private OffsetTable ot; private int last_type_index; private int last_method_index; private int last_namespace_index; public readonly int MajorVersion = 50; public readonly int MinorVersion; public int NumLineNumbers; private MyBinaryReader reader; private Dictionary<int, SourceFileEntry> source_file_hash; private Dictionary<int, CompileUnitEntry> compile_unit_hash; private List<MethodEntry> method_list; private Dictionary<int, MethodEntry> method_token_hash; private Dictionary<string, int> source_name_hash; private Guid guid; internal int LineNumberCount; internal int LocalCount; internal int StringSize; internal int LineNumberSize; internal int ExtendedLineNumberSize; public int CompileUnitCount => ot.CompileUnitCount; public int SourceCount => ot.SourceCount; public int MethodCount => ot.MethodCount; public int TypeCount => ot.TypeCount; public int AnonymousScopeCount => ot.AnonymousScopeCount; public int NamespaceCount => last_namespace_index; public Guid Guid => guid; public OffsetTable OffsetTable => ot; public SourceFileEntry[] Sources { get { if (reader == null) { throw new InvalidOperationException(); } SourceFileEntry[] array = new SourceFileEntry[SourceCount]; for (int i = 0; i < SourceCount; i++) { array[i] = GetSourceFile(i + 1); } return array; } } public CompileUnitEntry[] CompileUnits { get { if (reader == null) { throw new InvalidOperationException(); } CompileUnitEntry[] array = new CompileUnitEntry[CompileUnitCount]; for (int i = 0; i < CompileUnitCount; i++) { array[i] = GetCompileUnit(i + 1); } return array; } } public MethodEntry[] Methods { get { if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); MethodEntry[] array = new MethodEntry[MethodCount]; method_list.CopyTo(array, 0); return array; } } } internal MyBinaryReader BinaryReader { get { if (reader == null) { throw new InvalidOperationException(); } return reader; } } public MonoSymbolFile() { ot = new OffsetTable(); } public int AddSource(SourceFileEntry source) { sources.Add(source); return sources.Count; } public int AddCompileUnit(CompileUnitEntry entry) { comp_units.Add(entry); return comp_units.Count; } public void AddMethod(MethodEntry entry) { methods.Add(entry); } public MethodEntry DefineMethod(CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id) { if (reader != null) { throw new InvalidOperationException(); } MethodEntry methodEntry = new MethodEntry(this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id); AddMethod(methodEntry); return methodEntry; } internal void DefineAnonymousScope(int id) { if (reader != null) { throw new InvalidOperationException(); } if (anonymous_scopes == null) { anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>(); } anonymous_scopes.Add(id, new AnonymousScopeEntry(id)); } internal void DefineCapturedVariable(int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind) { if (reader != null) { throw new InvalidOperationException(); } anonymous_scopes[scope_id].AddCapturedVariable(name, captured_name, kind); } internal void DefineCapturedScope(int scope_id, int id, string captured_name) { if (reader != null) { throw new InvalidOperationException(); } anonymous_scopes[scope_id].AddCapturedScope(id, captured_name); } internal int GetNextTypeIndex() { return ++last_type_index; } internal int GetNextMethodIndex() { return ++last_method_index; } internal int GetNextNamespaceIndex() { return ++last_namespace_index; } private void Write(MyBinaryWriter bw, Guid guid) { bw.Write(5037318119232611860L); bw.Write(MajorVersion); bw.Write(MinorVersion); bw.Write(guid.ToByteArray()); long position = bw.BaseStream.Position; ot.Write(bw, MajorVersion, MinorVersion); methods.Sort(); for (int i = 0; i < methods.Count; i++) { methods[i].Index = i + 1; } ot.DataSectionOffset = (int)bw.BaseStream.Position; foreach (SourceFileEntry source in sources) { source.WriteData(bw); } foreach (CompileUnitEntry comp_unit in comp_units) { comp_unit.WriteData(bw); } foreach (MethodEntry method in methods) { method.WriteData(this, bw); } ot.DataSectionSize = (int)bw.BaseStream.Position - ot.DataSectionOffset; ot.MethodTableOffset = (int)bw.BaseStream.Position; for (int j = 0; j < methods.Count; j++) { methods[j].Write(bw); } ot.MethodTableSize = (int)bw.BaseStream.Position - ot.MethodTableOffset; ot.SourceTableOffset = (int)bw.BaseStream.Position; for (int k = 0; k < sources.Count; k++) { sources[k].Write(bw); } ot.SourceTableSize = (int)bw.BaseStream.Position - ot.SourceTableOffset; ot.CompileUnitTableOffset = (int)bw.BaseStream.Position; for (int l = 0; l < comp_units.Count; l++) { comp_units[l].Write(bw); } ot.CompileUnitTableSize = (int)bw.BaseStream.Position - ot.CompileUnitTableOffset; ot.AnonymousScopeCount = ((anonymous_scopes != null) ? anonymous_scopes.Count : 0); ot.AnonymousScopeTableOffset = (int)bw.BaseStream.Position; if (anonymous_scopes != null) { foreach (AnonymousScopeEntry value in anonymous_scopes.Values) { value.Write(bw); } } ot.AnonymousScopeTableSize = (int)bw.BaseStream.Position - ot.AnonymousScopeTableOffset; ot.TypeCount = last_type_index; ot.MethodCount = methods.Count; ot.SourceCount = sources.Count; ot.CompileUnitCount = comp_units.Count; ot.TotalFileSize = (int)bw.BaseStream.Position; bw.Seek((int)position, SeekOrigin.Begin); ot.Write(bw, MajorVersion, MinorVersion); bw.Seek(0, SeekOrigin.End); } public void CreateSymbolFile(Guid guid, FileStream fs) { if (reader != null) { throw new InvalidOperationException(); } Write(new MyBinaryWriter(fs), guid); } private MonoSymbolFile(Stream stream) { reader = new MyBinaryReader(stream); try { long num = reader.ReadInt64(); int num2 = reader.ReadInt32(); int num3 = reader.ReadInt32(); if (num != 5037318119232611860L) { throw new MonoSymbolFileException("Symbol file is not a valid"); } if (num2 != 50) { throw new MonoSymbolFileException("Symbol file has version {0} but expected {1}", num2, 50); } if (num3 != 0) { throw new MonoSymbolFileException("Symbol file has version {0}.{1} but expected {2}.{3}", num2, num3, 50, 0); } MajorVersion = num2; MinorVersion = num3; guid = new Guid(reader.ReadBytes(16)); ot = new OffsetTable(reader, num2, num3); } catch (Exception innerException) { throw new MonoSymbolFileException("Cannot read symbol file", innerException); } source_file_hash = new Dictionary<int, SourceFileEntry>(); compile_unit_hash = new Dictionary<int, CompileUnitEntry>(); } public static MonoSymbolFile ReadSymbolFile(Assembly assembly) { string mdbFilename = assembly.Location + ".mdb"; Guid moduleVersionId = assembly.GetModules()[0].ModuleVersionId; return ReadSymbolFile(mdbFilename, moduleVersionId); } public static MonoSymbolFile ReadSymbolFile(string mdbFilename) { return ReadSymbolFile(new FileStream(mdbFilename, FileMode.Open, FileAccess.Read)); } public static MonoSymbolFile ReadSymbolFile(string mdbFilename, Guid assemblyGuid) { MonoSymbolFile monoSymbolFile = ReadSymbolFile(mdbFilename); if (assemblyGuid != monoSymbolFile.guid) { throw new MonoSymbolFileException("Symbol file `{0}' does not match assembly", mdbFilename); } return monoSymbolFile; } public static MonoSymbolFile ReadSymbolFile(Stream stream) { return new MonoSymbolFile(stream); } public SourceFileEntry GetSourceFile(int index) { if (index < 1 || index > ot.SourceCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (source_file_hash.TryGetValue(index, out var value)) { return value; } long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1); value = new SourceFileEntry(this, reader); source_file_hash.Add(index, value); reader.BaseStream.Position = position; return value; } } public CompileUnitEntry GetCompileUnit(int index) { if (index < 1 || index > ot.CompileUnitCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (compile_unit_hash.TryGetValue(index, out var value)) { return value; } long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1); value = new CompileUnitEntry(this, reader); compile_unit_hash.Add(index, value); reader.BaseStream.Position = position; return value; } } private void read_methods() { lock (this) { if (method_token_hash == null) { method_token_hash = new Dictionary<int, MethodEntry>(); method_list = new List<MethodEntry>(); long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.MethodTableOffset; for (int i = 0; i < MethodCount; i++) { MethodEntry methodEntry = new MethodEntry(this, reader, i + 1); method_token_hash.Add(methodEntry.Token, methodEntry); method_list.Add(methodEntry); } reader.BaseStream.Position = position; } } } public MethodEntry GetMethodByToken(int token) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); method_token_hash.TryGetValue(token, out var value); return value; } } public MethodEntry GetMethod(int index) { if (index < 1 || index > ot.MethodCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); return method_list[index - 1]; } } public int FindSource(string file_name) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (source_name_hash == null) { source_name_hash = new Dictionary<string, int>(); for (int i = 0; i < ot.SourceCount; i++) { SourceFileEntry sourceFile = GetSourceFile(i + 1); source_name_hash.Add(sourceFile.FileName, i); } } if (!source_name_hash.TryGetValue(file_name, out var value)) { return -1; } return value; } } public AnonymousScopeEntry GetAnonymousScope(int id) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (anonymous_scopes != null) { anonymous_scopes.TryGetValue(id, out var value); return value; } anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>(); reader.BaseStream.Position = ot.AnonymousScopeTableOffset; for (int i = 0; i < ot.AnonymousScopeCount; i++) { AnonymousScopeEntry value = new AnonymousScopeEntry(reader); anonymous_scopes.Add(value.ID, value); } return anonymous_scopes[id]; } } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { if (disposing && reader != null) { reader.Close(); reader = null; } } } public class OffsetTable { [Flags] public enum Flags { IsAspxSource = 1, WindowsFileNames = 2 } public const int MajorVersion = 50; public const int MinorVersion = 0; public const long Magic = 5037318119232611860L; public int TotalFileSize; public int DataSectionOffset; public int DataSectionSize; public int CompileUnitCount; public int CompileUnitTableOffset; public int CompileUnitTableSize; public int SourceCount; public int SourceTableOffset; public int SourceTableSize; public int MethodCount; public int MethodTableOffset; public int MethodTableSize; public int TypeCount; public int AnonymousScopeCount; public int AnonymousScopeTableOffset; public int AnonymousScopeTableSize; public Flags FileFlags; public int LineNumberTable_LineBase = -1; public int LineNumberTable_LineRange = 8; public int LineNumberTable_OpcodeBase = 9; internal OffsetTable() { int platform = (int)Environment.OSVersion.Platform; if (platform != 4 && platform != 128) { FileFlags |= Flags.WindowsFileNames; } } internal OffsetTable(BinaryReader reader, int major_version, int minor_version) { TotalFileSize = reader.ReadInt32(); DataSectionOffset = reader.ReadInt32(); DataSectionSize = reader.ReadInt32(); CompileUnitCount = reader.ReadInt32(); CompileUnitTableOffset = reader.ReadInt32(); CompileUnitTableSize = reader.ReadInt32(); SourceCount = reader.ReadInt32(); SourceTableOffset = reader.ReadInt32(); SourceTableSize = reader.ReadInt32(); MethodCount = reader.ReadInt32(); MethodTableOffset = reader.ReadInt32(); MethodTableSize = reader.ReadInt32(); TypeCount = reader.ReadInt32(); AnonymousScopeCount = reader.ReadInt32(); AnonymousScopeTableOffset = reader.ReadInt32(); AnonymousScopeTableSize = reader.ReadInt32(); LineNumberTable_LineBase = reader.ReadInt32(); LineNumberTable_LineRange = reader.ReadInt32(); LineNumberTable_OpcodeBase = reader.ReadInt32(); FileFlags = (Flags)reader.ReadInt32(); } internal void Write(BinaryWriter bw, int major_version, int minor_version) { bw.Write(TotalFileSize); bw.Write(DataSectionOffset); bw.Write(DataSectionSize); bw.Write(CompileUnitCount); bw.Write(CompileUnitTableOffset); bw.Write(CompileUnitTableSize); bw.Write(SourceCount); bw.Write(SourceTableOffset); bw.Write(SourceTableSize); bw.Write(MethodCount); bw.Write(MethodTableOffset); bw.Write(MethodTableSize); bw.Write(TypeCount); bw.Write(AnonymousScopeCount); bw.Write(AnonymousScopeTableOffset); bw.Write(AnonymousScopeTableSize); bw.Write(LineNumberTable_LineBase); bw.Write(LineNumberTable_LineRange); bw.Write(LineNumberTable_OpcodeBase); bw.Write((int)FileFlags); } public override string ToString() { return $"OffsetTable [{TotalFileSize} - {DataSectionOffset}:{DataSectionSize} - {SourceCount}:{SourceTableOffset}:{SourceTableSize} - {MethodCount}:{MethodTableOffset}:{MethodTableSize} - {TypeCount}]"; } } public class LineNumberEntry { public sealed class LocationComparer : IComparer<LineNumberEntry> { public static readonly LocationComparer Default = new LocationComparer(); public int Compare(LineNumberEntry l1, LineNumberEntry l2) { if (l1.Row != l2.Row) { int row = l1.Row; return row.CompareTo(l2.Row); } return l1.Column.CompareTo(l2.Column); } } public readonly int Row; public int Column; public int EndRow; public int EndColumn; public readonly int File; public readonly int Offset; public readonly bool IsHidden; public static readonly LineNumberEntry Null = new LineNumberEntry(0, 0, 0, 0); public LineNumberEntry(int file, int row, int column, int offset) : this(file, row, column, offset, is_hidden: false) { } public LineNumberEntry(int file, int row, int offset) : this(file, row, -1, offset, is_hidden: false) { } public LineNumberEntry(int file, int row, int column, int offset, bool is_hidden) : this(file, row, column, -1, -1, offset, is_hidden) { } public LineNumberEntry(int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden) { File = file; Row = row; Column = column; EndRow = end_row; EndColumn = end_column; Offset = offset; IsHidden = is_hidden; } public override string ToString() { return $"[Line {File}:{Row},{Column}-{EndRow},{EndColumn}:{Offset}]"; } } public class CodeBlockEntry { public enum Type { Lexical = 1, CompilerGenerated, IteratorBody, IteratorDispatcher } public int Index; public int Parent; public Type BlockType; public int StartOffset; public int EndOffset; public CodeBlockEntry(int index, int parent, Type type, int start_offset) { Index = index; Parent = parent; BlockType = type; StartOffset = start_offset; } internal CodeBlockEntry(int index, MyBinaryReader reader) { Index = index; int num = reader.ReadLeb128(); BlockType = (Type)(num & 0x3F); Parent = reader.ReadLeb128(); StartOffset = reader.ReadLeb128(); EndOffset = reader.ReadLeb128(); if (((uint)num & 0x40u) != 0) { int num2 = reader.ReadInt16(); reader.BaseStream.Position += num2; } } public void Close(int end_offset) { EndOffset = end_offset; } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128((int)BlockType); bw.WriteLeb128(Parent); bw.WriteLeb128(StartOffset); bw.WriteLeb128(EndOffset); } public override string ToString() { return $"[CodeBlock {Index}:{Parent}:{BlockType}:{StartOffset}:{EndOffset}]"; } } public struct LocalVariableEntry { public readonly int Index; public readonly string Name; public readonly int BlockIndex; public LocalVariableEntry(int index, string name, int block) { Index = index; Name = name; BlockIndex = block; } internal LocalVariableEntry(MonoSymbolFile file, MyBinaryReader reader) { Index = reader.ReadLeb128(); Name = reader.ReadString(); BlockIndex = reader.ReadLeb128(); } internal void Write(MonoSymbolFile file, MyBinaryWriter bw) { bw.WriteLeb128(Index); bw.Write(Name); bw.WriteLeb128(BlockIndex); } public override string ToString() { return $"[LocalVariable {Name}:{Index}:{BlockIndex - 1}]"; } } public struct CapturedVariable { public enum CapturedKind : byte { Local, Parameter, This } public readonly string Name; public readonly string CapturedName; public readonly CapturedKind Kind; public CapturedVariable(string name, string captured_name, CapturedKind kind) { Name = name; CapturedName = captured_name; Kind = kind; } internal CapturedVariable(MyBinaryReader reader) { Name = reader.ReadString(); CapturedName = reader.ReadString(); Kind = (CapturedKind)reader.ReadByte(); } internal void Write(MyBinaryWriter bw) { bw.Write(Name); bw.Write(CapturedName); bw.Write((byte)Kind); } public override string ToString() { return $"[CapturedVariable {Name}:{CapturedName}:{Kind}]"; } } public struct CapturedScope { public readonly int Scope; public readonly string CapturedName; public CapturedScope(int scope, string captured_name) { Scope = scope; CapturedName = captured_name; } internal CapturedScope(MyBinaryReader reader) { Scope = reader.ReadLeb128(); CapturedName = reader.ReadString(); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(Scope); bw.Write(CapturedName); } public override string ToString() { return $"[CapturedScope {Scope}:{CapturedName}]"; } } public struct ScopeVariable { public readonly int Scope; public readonly int Index; public ScopeVariable(int scope, int index) { Scope = scope; Index = index; } internal ScopeVariable(MyBinaryReader reader) { Scope = reader.ReadLeb128(); Index = reader.ReadLeb128(); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(Scope); bw.WriteLeb128(Index); } public override string ToString() { return $"[ScopeVariable {Scope}:{Index}]"; } } public class AnonymousScopeEntry { public readonly int ID; private List<CapturedVariable> captured_vars = new List<CapturedVariable>(); private List<CapturedScope> captured_scopes = new List<CapturedScope>(); public CapturedVariable[] CapturedVariables { get { CapturedVariable[] array = new CapturedVariable[captured_vars.Count]; captured_vars.CopyTo(array, 0); return array; } } public CapturedScope[] CapturedScopes { get { CapturedScope[] array = new CapturedScope[captured_scopes.Count]; captured_scopes.CopyTo(array, 0); return array; } } public AnonymousScopeEntry(int id) { ID = id; } internal AnonymousScopeEntry(MyBinaryReader reader) { ID = reader.ReadLeb128(); int num = reader.ReadLeb128(); for (int i = 0; i < num; i++) { captured_vars.Add(new CapturedVariable(reader)); } int num2 = reader.ReadLeb128(); for (int j = 0; j < num2; j++) { captured_scopes.Add(new CapturedScope(reader)); } } internal void AddCapturedVariable(string name, string captured_name, CapturedVariable.CapturedKind kind) { captured_vars.Add(new CapturedVariable(name, captured_name, kind)); } internal void AddCapturedScope(int scope, string captured_name) { captured_scopes.Add(new CapturedScope(scope, captured_name)); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(ID); bw.WriteLeb128(captured_vars.Count); foreach (CapturedVariable captured_var in captured_vars) { captured_var.Write(bw); } bw.WriteLeb128(captured_scopes.Count); foreach (CapturedScope captured_scope in captured_scopes) { captured_scope.Write(bw); } } public override string ToString() { return $"[AnonymousScope {ID}]"; } } public class CompileUnitEntry : ICompileUnit { public readonly int Index; private int DataOffset; private MonoSymbolFile file; private SourceFileEntry source; private List<SourceFileEntry> include_files; private List<NamespaceEntry> namespaces; private bool creating; public static int Size => 8; CompileUnitEntry ICompileUnit.Entry => this; public SourceFileEntry SourceFile { get { if (creating) { return source; } ReadData(); return source; } } public NamespaceEntry[] Namespaces { get { ReadData(); NamespaceEntry[] array = new NamespaceEntry[namespaces.Count]; namespaces.CopyTo(array, 0); return array; } } public SourceFileEntry[] IncludeFiles { get { ReadData(); if (include_files == null) { return new SourceFileEntry[0]; } SourceFileEntry[] array = new SourceFileEntry[include_files.Count]; include_files.CopyTo(array, 0); return array; } } public CompileUnitEntry(MonoSymbolFile file, SourceFileEntry source) { this.file = file; this.source = source; Index = file.AddCompileUnit(this); creating = true; namespaces = new List<NamespaceEntry>(); } public void AddFile(SourceFileEntry file) { if (!creating) { throw new InvalidOperationException(); } if (include_files == null) { include_files = new List<SourceFileEntry>(); } include_files.Add(file); } public int DefineNamespace(string name, string[] using_clauses, int parent) { if (!creating) { throw new InvalidOperationException(); } int nextNamespaceIndex = file.GetNextNamespaceIndex(); NamespaceEntry item = new NamespaceEntry(name, nextNamespaceIndex, using_clauses, parent); namespaces.Add(item); return nextNamespaceIndex; } internal void WriteData(MyBinaryWriter bw) { DataOffset = (int)bw.BaseStream.Position; bw.WriteLeb128(source.Index); int value = ((include_files != null) ? include_files.Count : 0); bw.WriteLeb128(value); if (include_files != null) { foreach (SourceFileEntry include_file in include_files) { bw.WriteLeb128(include_file.Index); } } bw.WriteLeb128(namespaces.Count); foreach (NamespaceEntry @namespace in namespaces) { @namespace.Write(file, bw); } } internal void Write(BinaryWriter bw) { bw.Write(Index); bw.Write(DataOffset); } internal CompileUnitEntry(MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32(); DataOffset = reader.ReadInt32(); } public void ReadAll() { ReadData(); } private void ReadData() { if (creating) { throw new InvalidOperationException(); } lock (file) { if (namespaces != null) { return; } MyBinaryReader binaryReader = file.BinaryReader; int num = (int)binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = DataOffset; int index = binaryReader.ReadLeb128(); source = file.GetSourceFile(index); int num2 = binaryReader.ReadLeb128(); if (num2 > 0) { include_files = new List<SourceFileEntry>(); for (int i = 0; i < num2; i++) { include_files.Add(file.GetSourceFile(binaryReader.ReadLeb128())); } } int num3 = binaryReader.ReadLeb128(); namespaces = new List<NamespaceEntry>(); for (int j = 0; j < num3; j++) { namespaces.Add(new NamespaceEntry(file, binaryReader)); } binaryReader.BaseStream.Position = num; } } } public class SourceFileEntry { public readonly int Index; private int DataOffset; private MonoSymbolFile file; private string file_name; private byte[] guid; private byte[] hash; private bool creating; private bool auto_generated; private readonly string sourceFile; public static int Size => 8; public byte[] Checksum => hash; public string FileName { get { return file_name; } set { file_name = value; } } public bool AutoGenerated => auto_generated; public SourceFileEntry(MonoSymbolFile file, string file_name) { this.file = file; this.file_name = file_name; Index = file.AddSource(this); creating = true; } public SourceFileEntry(MonoSymbolFile file, string sourceFile, byte[] guid, byte[] checksum) : this(file, sourceFile, sourceFile, guid, checksum) { } public SourceFileEntry(MonoSymbolFile file, string fileName, string sourceFile, byte[] guid, byte[] checksum) : this(file, fileName) { this.guid = guid; hash = checksum; this.sourceFile = sourceFile; } internal void WriteData(MyBinaryWriter bw) { DataOffset = (int)bw.BaseStream.Position; bw.Write(file_name); if (guid == null) { guid = new byte[16]; } if (hash == null) { try { using FileStream inputStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read); MD5 mD = MD5.Create(); hash = mD.ComputeHash(inputStream); } catch { hash = new byte[16]; } } bw.Write(guid); bw.Write(hash); bw.Write((byte)(auto_generated ? 1u : 0u)); } internal void Write(BinaryWriter bw) { bw.Write(Index); bw.Write(DataOffset); } internal SourceFileEntry(MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32(); DataOffset = reader.ReadInt32(); int num = (int)reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; sourceFile = (file_name = reader.ReadString()); guid = reader.ReadBytes(16); hash = reader.ReadBytes(16); auto_generated = reader.ReadByte() == 1; reader.BaseStream.Position = num; } public void SetAutoGenerated() { if (!creating) { throw new InvalidOperationException(); } auto_generated = true; file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource; } public bool CheckChecksum() { try { using FileStream inputStream = new FileStream(sourceFile, FileMode.Open); byte[] array = MD5.Create().ComputeHash(inputStream); for (int i = 0; i < 16; i++) { if (array[i] != hash[i]) { return false; } } return true; } catch { return false; } } public override string ToString() { return $"SourceFileEntry ({Index}:{DataOffset})"; } } public class LineNumberTable { protected LineNumberEntry[] _line_numbers; public readonly int LineBase; public readonly int LineRange; public readonly byte OpcodeBase; public readonly int MaxAddressIncrement; public const int Default_LineBase = -1; public const int Default_LineRange = 8; public const byte Default_OpcodeBase = 9; public const byte DW_LNS_copy = 1; public const byte DW_LNS_advance_pc = 2; public const byte DW_LNS_advance_line = 3; public const byte DW_LNS_set_file = 4; public const byte DW_LNS_const_add_pc = 8; public const byte DW_LNE_end_sequence = 1; public const byte DW_LNE_MONO_negate_is_hidden = 64; internal const byte DW_LNE_MONO__extensions_start = 64; internal const byte DW_LNE_MONO__extensions_end = 127; public LineNumberEntry[] LineNumbers => _line_numbers; protected LineNumberTable(MonoSymbolFile file) { LineBase = file.OffsetTable.LineNumberTable_LineBase; LineRange = file.OffsetTable.LineNumberTable_LineRange; OpcodeBase = (byte)file.OffsetTable.LineNumberTable_OpcodeBase; MaxAddressIncrement = (255 - OpcodeBase) / LineRange; } internal LineNumberTable(MonoSymbolFile file, LineNumberEntry[] lines) : this(file) { _line_numbers = lines; } internal void Write(MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo) { int num = (int)bw.BaseStream.Position; bool flag = false; int num2 = 1; int num3 = 0; int num4 = 1; for (int i = 0; i < LineNumbers.Length; i++) { int num5 = LineNumbers[i].Row - num2; int num6 = LineNumbers[i].Offset - num3; if (LineNumbers[i].File != num4) { bw.Write((byte)4); bw.WriteLeb128(LineNumbers[i].File); num4 = LineNumbers[i].File; } if (LineNumbers[i].IsHidden != flag) { bw.Write((byte)0); bw.Write((byte)1); bw.Write((byte)64); flag = LineNumbers[i].IsHidden; } if (num6 >= MaxAddressIncrement) { if (num6 < 2 * MaxAddressIncrement) { bw.Write((byte)8); num6 -= MaxAddressIncrement; } else { bw.Write((byte)2); bw.WriteLeb128(num6); num6 = 0; } } if (num5 < LineBase || num5 >= LineBase + LineRange) { bw.Write((byte)3); bw.WriteLeb128(num5); if (num6 != 0) { bw.Write((byte)2); bw.WriteLeb128(num6); } bw.Write((byte)1); } else { byte value = (byte)(num5 - LineBase + LineRange * num6 + OpcodeBase); bw.Write(value); } num2 = LineNumbers[i].Row; num3 = LineNumbers[i].Offset; } bw.Write((byte)0); bw.Write((byte)1); bw.Write((byte)1); if (hasColumnsInfo) { for (int j = 0; j < LineNumbers.Length; j++) { LineNumberEntry lineNumberEntry = LineNumbers[j]; if (lineNumberEntry.Row >= 0) { bw.WriteLeb128(lineNumberEntry.Column); } } } if (hasEndInfo) { for (int k = 0; k < LineNumbers.Length; k++) { LineNumberEntry lineNumberEntry2 = LineNumbers[k]; if (lineNumberEntry2.EndRow == -1 || lineNumberEntry2.EndColumn == -1 || lineNumberEntry2.Row > lineNumberEntry2.EndRow) { bw.WriteLeb128(16777215); continue; } bw.WriteLeb128(lineNumberEntry2.EndRow - lineNumberEntry2.Row); bw.WriteLeb128(lineNumberEntry2.EndColumn); } } file.ExtendedLineNumberSize += (int)bw.BaseStream.Position - num; } internal static LineNumberTable Read(MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo) { LineNumberTable lineNumberTable = new LineNumberTable(file); lineNumberTable.DoRead(file, br, readColumnsInfo, readEndInfo); return lineNumberTable; } private void DoRead(MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds) { List<LineNumberEntry> list = new List<LineNumberEntry>(); bool flag = false; bool flag2 = false; int num = 1; int num2 = 0; int file2 = 1; while (true) { byte b = br.ReadByte(); if (b == 0) { byte b2 = br.ReadByte(); long position = br.BaseStream.Position + b2; b = br.ReadByte(); switch (b) { case 1: { if (flag2) { list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); } _line_numbers = list.ToArray(); if (includesColumns) { for (int i = 0; i < _line_numbers.Length; i++) { LineNumberEntry lineNumberEntry = _line_numbers[i]; if (lineNumberEntry.Row >= 0) { lineNumberEntry.Column = br.ReadLeb128(); } } } if (!includesEnds) { return; } for (int j = 0; j < _line_numbers.Length; j++) { LineNumberEntry lineNumberEntry2 = _line_numbers[j]; int num3 = br.ReadLeb128(); if (num3 == 16777215) { lineNumberEntry2.EndRow = -1; lineNumberEntry2.EndColumn = -1; } else { lineNumberEntry2.EndRow = lineNumberEntry2.Row + num3; lineNumberEntry2.EndColumn = br.ReadLeb128(); } } return; } case 64: flag = !flag; flag2 = true; break; default: throw new MonoSymbolFileException("Unknown extended opcode {0:x}", b); case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: break; } br.BaseStream.Position = position; } else if (b < OpcodeBase) { switch (b) { case 1: list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); flag2 = false; break; case 2: num2 += br.ReadLeb128(); flag2 = true; break; case 3: num += br.ReadLeb128(); flag2 = true; break; case 4: file2 = br.ReadLeb128(); flag2 = true; break; case 8: num2 += MaxAddressIncrement; flag2 = true; break; default: throw new MonoSymbolFileException("Unknown standard opcode {0:x} in LNT", b); } } else { b -= OpcodeBase; num2 += b / LineRange; num += LineBase + b % LineRange; list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); flag2 = false; } } } public bool GetMethodBounds(out LineNumberEntry start, out LineNumberEntry end) { if (_line_numbers.Length > 1) { start = _line_numbers[0]; end = _line_numbers[_line_numbers.Length - 1]; return true; } start = LineNumberEntry.Null; end = LineNumberEntry.Null; return false; } } public class MethodEntry : IComparable { [Flags] public enum Flags { LocalNamesAmbiguous = 1, ColumnsInfoIncluded = 2, EndInfoIncluded = 4 } public readonly int CompileUnitIndex; public readonly int Token; public readonly int NamespaceID; private int DataOffset; private int LocalVariableTableOffset; private int LineNumberTableOffset; private int CodeBlockTableOffset; private int ScopeVariableTableOffset; private int RealNameOffset; private Flags flags; private int index; public readonly CompileUnitEntry CompileUnit; private LocalVariableEntry[] locals; private CodeBlockEntry[] code_blocks; private ScopeVariable[] scope_vars; private LineNumberTable lnt; private string real_name; public readonly MonoSymbolFile SymbolFile; public const int Size = 12; public Flags MethodFlags => flags; public int Index { get { return index; } set { index = value; } } internal MethodEntry(MonoSymbolFile file, MyBinaryReader reader, int index) { SymbolFile = file; this.index = index; Token = reader.ReadInt32(); DataOffset = reader.ReadInt32(); LineNumberTableOffset = reader.ReadInt32(); long position = reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; CompileUnitIndex = reader.ReadLeb128(); LocalVariableTableOffset = reader.ReadLeb128(); NamespaceID = reader.ReadLeb128(); CodeBlockTableOffset = reader.ReadLeb128(); ScopeVariableTableOffset = reader.ReadLeb128(); RealNameOffset = reader.ReadLeb128(); flags = (Flags)reader.ReadLeb128(); reader.BaseStream.Position = position; CompileUnit = file.GetCompileUnit(CompileUnitIndex); } internal MethodEntry(MonoSymbolFile file, CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, Flags flags, int namespace_id) { SymbolFile = file; this.real_name = real_name; this.locals = locals; this.code_blocks = code_blocks; this.scope_vars = scope_vars; this.flags = flags; index = -1; Token = token; CompileUnitIndex = comp_unit.Index; CompileUnit = comp_unit; NamespaceID = namespace_id; CheckLineNumberTable(lines); lnt = new LineNumberTable(file, lines); file.NumLineNumbers += lines.Length; int num = ((locals != null) ? locals.Length : 0); if (num <= 32) { for (int i = 0; i < num; i++) { string name = locals[i].Name; for (int j = i + 1; j < num; j++) { if (locals[j].Name == name) { flags |= Flags.LocalNamesAmbiguous; return; } } } return; } Dictionary<string, LocalVariableEntry> dictionary = new Dictionary<string, LocalVariableEntry>(); for (int k = 0; k < locals.Length; k++) { LocalVariableEntry value = locals[k]; if (dictionary.ContainsKey(value.Name)) { flags |= Flags.LocalNamesAmbiguous; break; } dictionary.Add(value.Name, value); } } private static void CheckLineNumberTable(LineNumberEntry[] line_numbers) { int num = -1; int num2 = -1; if (line_numbers == null) { return; } foreach (LineNumberEntry lineNumberEntry in line_numbers) { if (lineNumberEntry.Equals(LineNumberEntry.Null)) { throw new MonoSymbolFileException(); } if (lineNumberEntry.Offset < num) { throw new MonoSymbolFileException(); } if (lineNumberEntry.Offset > num) { num2 = lineNumberEntry.Row; num = lineNumberEntry.Offset; } else if (lineNumberEntry.Row > num2) { num2 = lineNumberEntry.Row; } } } internal void Write(MyBinaryWriter bw) { if (index <= 0 || DataOffset == 0) { throw new InvalidOperationException(); } bw.Write(Token); bw.Write(DataOffset); bw.Write(LineNumberTableOffset); } internal void WriteData(MonoSymbolFile file, MyBinaryWriter bw) { if (index <= 0) { throw new InvalidOperationException(); } LocalVariableTableOffset = (int)bw.BaseStream.Position; int num = ((locals != null) ? locals.Length : 0); bw.WriteLeb128(num); for (int i = 0; i < num; i++) { locals[i].Write(file, bw); } file.LocalCount += num; CodeBlockTableOffset = (int)bw.BaseStream.Position; int num2 = ((code_blocks != null) ? code_blocks.Length : 0); bw.WriteLeb128(num2); for (int j = 0; j < num2; j++) { code_blocks[j].Write(bw); } ScopeVariableTableOffset = (int)bw.BaseStream.Position; int num3 = ((scope_vars != null) ? scope_vars.Length : 0); bw.WriteLeb128(num3); for (int k = 0; k < num3; k++) { scope_vars[k].Write(bw); } if (real_name != null) { RealNameOffset = (int)bw.BaseStream.Position; bw.Write(real_name); } LineNumberEntry[] lineNumbers = lnt.LineNumbers; foreach (LineNumberEntry lineNumberEntry in lineNumbers) { if (lineNumberEntry.EndRow != -1 || lineNumberEntry.EndColumn != -1) { flags |= Flags.EndInfoIncluded; } } LineNumberTableOffset = (int)bw.BaseStream.Position; lnt.Write(file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); DataOffset = (int)bw.BaseStream.Position; bw.WriteLeb128(CompileUnitIndex); bw.WriteLeb128(LocalVariableTableOffset); bw.WriteLeb128(NamespaceID); bw.WriteLeb128(CodeBlockTableOffset); bw.WriteLeb128(ScopeVariableTableOffset); bw.WriteLeb128(RealNameOffset); bw.WriteLeb128((int)flags); } public void ReadAll() { GetLineNumberTable(); GetLocals(); GetCodeBlocks(); GetScopeVariables(); GetRealName(); } public LineNumberTable GetLineNumberTable() { lock (SymbolFile) { if (lnt != null) { return lnt; } if (LineNumberTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = LineNumberTableOffset; lnt = LineNumberTable.Read(SymbolFile, binaryReader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); binaryReader.BaseStream.Position = position; return lnt; } } public LocalVariableEntry[] GetLocals() { lock (SymbolFile) { if (locals != null) { return locals; } if (LocalVariableTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = LocalVariableTableOffset; int num = binaryReader.ReadLeb128(); locals = new LocalVariableEntry[num]; for (int i = 0; i < num; i++) { locals[i] = new LocalVariableEntry(SymbolFile, binaryReader); } binaryReader.BaseStream.Position = position; return locals; } } public CodeBlockEntry[] GetCodeBlocks() { lock (SymbolFile) { if (code_blocks != null) { return code_blocks; } if (CodeBlockTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = CodeBlockTableOffset; int num = binaryReader.ReadLeb128(); code_blocks = new CodeBlockEntry[num]; for (int i = 0; i < num; i++) { code_blocks[i] = new CodeBlockEntry(i, binaryReader); } binaryReader.BaseStream.Position = position; return code_blocks; } } public ScopeVariable[] GetScopeVariables() { lock (SymbolFile) { if (scope_vars != null) { return scope_vars; } if (ScopeVariableTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = ScopeVariableTableOffset; int num = binaryReader.ReadLeb128(); scope_vars = new ScopeVariable[num]; for (int i = 0; i < num; i++) { scope_vars[i] = new ScopeVariable(binaryReader); } binaryReader.BaseStream.Position = position; return scope_vars; } } public string GetRealName() { lock (SymbolFile) { if (real_name != null) { return real_name; } if (RealNameOffset == 0) { return null; } real_name = SymbolFile.BinaryReader.ReadString(RealNameOffset); return real_name; } } public int CompareTo(object obj) { MethodEntry methodEntry = (MethodEntry)obj; if (methodEntry.Token < Token) { return 1; } if (methodEntry.Token > Token) { return -1; } return 0; } public override string ToString() { return $"[Method {index}:{Token:x}:{CompileUnitIndex}:{CompileUnit}]"; } } public struct NamespaceEntry { public readonly string Name; public readonly int Index; public readonly int Parent; public readonly string[] UsingClauses; public NamespaceEntry(string name, int index, string[] using_clauses, int parent) { Name = name; Index = index; Parent = parent; UsingClauses = ((using_clauses != null) ? using_clauses : new string[0]); } internal NamespaceEntry(MonoSymbolFile file, MyBinaryReader reader) { Name = reader.ReadString(); Index = reader.ReadLeb128(); Parent = reader.ReadLeb128(); int num = reader.ReadLeb128(); UsingClauses = new string[num]; for (int i = 0; i < num; i++) { UsingClauses[i] = reader.ReadString(); } } internal void Write(MonoSymbolFile file, MyBinaryWriter bw) { bw.Write(Name); bw.WriteLeb128(Index); bw.WriteLeb128(Parent); bw.WriteLeb128(UsingClauses.Length); string[] usingClauses = UsingClauses; foreach (string value in usingClauses) { bw.Write(value); } } public override string ToString() { return $"[Namespace {Name}:{Index}:{Parent}]"; } } public class MonoSymbolWriter { private List<SourceMethodBuilder> methods; private List<SourceFileEntry> sources; private List<CompileUnitEntry> comp_units; protected readonly MonoSymbolFile file; private string filename; private SourceMethodBuilder current_method; private Stack<SourceMethodBuilder> current_method_stack = new Stack<SourceMethodBuilder>(); public MonoSymbolFile SymbolFile => file; public MonoSymbolWriter(string filename) { methods = new List<SourceMethodBuilder>(); sources = new List<SourceFileEntry>(); comp_units = new List<CompileUnitEntry>(); file = new MonoSymbolFile(); this.filename = filename + ".mdb"; } public void CloseNamespace() { } public void DefineLocalVariable(int index, string name) { if (current_method != null) { current_method.AddLocal(index, name); } } public void DefineCapturedLocal(int scope_id, string name, string captured_name) { file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Local); } public void DefineCapturedParameter(int scope_id, string name, string captured_name) { file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Parameter); } public void DefineCapturedThis(int scope_id, string captured_name) { file.DefineCapturedVariable(scope_id, "this", captured_name, CapturedVariable.CapturedKind.This); } public void DefineCapturedScope(int scope_id, int id, string captured_name) { file.DefineCapturedScope(scope_id, id, captured_name); } public void DefineScopeVariable(int scope, int index) { if (current_method != null) { current_method.AddScopeVariable(scope, index); } } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden) { if (current_method != null) { current_method.MarkSequencePoint(offset, file, line, column, is_hidden); } } public SourceMethodBuilder OpenMethod(ICompileUnit file, int ns_id, IMethodDef method) { SourceMethodBuilder result = new SourceMethodBuilder(file, ns_id, method); current_method_stack.Push(current_method); current_method = result; methods.Add(current_method); return result; } public void CloseMethod() { current_method = current_method_stack.Pop(); } public SourceFileEntry DefineDocument(string url) { SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url); sources.Add(sourceFileEntry); return sourceFileEntry; } public SourceFileEntry DefineDocument(string url, byte[] guid, byte[] checksum) { SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url, guid, checksum); sources.Add(sourceFileEntry); return sourceFileEntry; } public CompileUnitEntry DefineCompilationUnit(SourceFileEntry source) { CompileUnitEntry compileUnitEntry = new CompileUnitEntry(file, source); comp_units.Add(compileUnitEntry); return compileUnitEntry; } public int DefineNamespace(string name, CompileUnitEntry unit, string[] using_clauses, int parent) { if (unit == null || using_clauses == null) { throw new NullReferenceException(); } return unit.DefineNamespace(name, using_clauses, parent); } public int OpenScope(int start_offset) { if (current_method == null) { return 0; } current_method.StartBlock(CodeBlockEntry.Type.Lexical, start_offset); return 0; } public void CloseScope(int end_offset) { if (current_method != null) { current_method.EndBlock(end_offset); } } public void OpenCompilerGeneratedBlock(int start_offset) { if (current_method != null) { current_method.StartBlock(CodeBlockEntry.Type.CompilerGenerated, start_offset); } } public void CloseCompilerGeneratedBlock(int end_offset) { if (current_method != null) { current_method.EndBlock(end_offset); } } public void StartIteratorBody(int start_offset) { current_method.StartBlock(CodeBlockEntry.Type.IteratorBody, start_offset); } public void EndIteratorBody(int end_offset) { current_method.EndBlock(end_offset); } public void StartIteratorDispatcher(int start_offset) { current_method.StartBlock(CodeBlockEntry.Type.IteratorDispatcher, start_offset); } public void EndIteratorDispatcher(int end_offset) { current_method.EndBlock(end_offset); } public void DefineAnonymousScope(int id) { file.DefineAnonymousScope(id); } public void WriteSymbolFile(Guid guid) { foreach (SourceMethodBuilder method in methods) { method.DefineMethod(file); } try { File.Delete(filename); } catch { } using FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write); file.CreateSymbolFile(guid, fs); } } public class SourceMethodBuilder { private List<LocalVariableEntry> _locals; private List<CodeBlockEntry> _blocks; private List<ScopeVariable> _scope_vars; private Stack<CodeBlockEntry> _block_stack; private readonly List<LineNumberEntry> method_lines; private readonly ICompileUnit _comp_unit; private readonly int ns_id; private readonly IMethodDef method; public CodeBlockEntry[] Blocks { get { if (_blocks == null) { return new CodeBlockEntry[0]; } CodeBlockEntry[] array = new CodeBlockEntry[_blocks.Count]; _blocks.CopyTo(array, 0); return array; } } public CodeBlockEntry CurrentBlock { get { if (_block_stack != null && _block_stack.Count > 0) { return _block_stack.Peek(); } return null; } } public LocalVariableEntry[] Locals { get { if (_locals == null) { return new LocalVariableEntry[0]; } return _locals.ToArray(); } } public ICompileUnit SourceFile => _comp_unit; public ScopeVariable[] ScopeVariables { get { if (_scope_vars == null) { return new ScopeVariable[0]; } return _scope_vars.ToArray(); } } public SourceMethodBuilder(ICompileUnit comp_unit) { _comp_unit = comp_unit; method_lines = new List<LineNumberEntry>(); } public SourceMethodBuilder(ICompileUnit comp_unit, int ns_id, IMethodDef method) : this(comp_unit) { this.ns_id = ns_id; this.method = method; } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden) { MarkSequencePoint(offset, file, line, column, -1, -1, is_hidden); } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden) { LineNumberEntry lineNumberEntry = new LineNumberEntry(file?.Index ?? 0, line, column, end_line, end_column, offset, is_hidden); if (method_lines.Count > 0) { LineNumberEntry lineNumberEntry2 = method_lines[method_lines.Count - 1]; if (lineNumberEntry2.Offset == offset) { if (LineNumberEntry.LocationComparer.Default.Compare(lineNumberEntry, lineNumberEntry2) > 0) { method_lines[method_lines.Count - 1] = lineNumberEntry; } return; } } method_lines.Add(lineNumberEntry); } public void StartBlock(CodeBlockEntry.Type type, int start_offset) { StartBlock(type, start_offset, (_blocks == null) ? 1 : (_blocks.Count + 1)); } public void StartBlock(CodeBlockEntry.Type type, int start_offset, int scopeIndex) { if (_block_stack == null) { _block_stack = new Stack<CodeBlockEntry>(); } if (_blocks == null) { _blocks = new List<CodeBlockEntry>(); } int parent = ((CurrentBlock != null) ? CurrentBlock.Index : (-1)); CodeBlockEntry item = new CodeBlockEntry(scopeIndex, parent, type, start_offset); _block_stack.Push(item); _blocks.Add(item); } public void EndBlock(int end_offset) { _block_stack.Pop().Close(end_offset); } public void AddLocal(int index, string name) { if (_locals == null) { _locals = new List<LocalVariableEntry>(); } int block = ((CurrentBlock != null) ? CurrentBlock.Index : 0); _locals.Add(new LocalVariableEntry(index, name, block)); } public void AddScopeVariable(int scope, int index) { if (_scope_vars == null) { _scope_vars = new List<ScopeVariable>(); } _scope_vars.Add(new ScopeVariable(scope, index)); } public void DefineMethod(MonoSymbolFile file) { DefineMethod(file, method.Token); } public void DefineMethod(MonoSymbolFile file, int token) { CodeBlockEntry[] array = Blocks; if (array.Length != 0) { List<CodeBlockEntry> list = new List<CodeBlockEntry>(array.Length); int num = 0; for (int i = 0; i < array.Length; i++) { num = Math.Max(num, array[i].Index); } for (int j = 0; j < num; j++) { int num2 = j + 1; if (j < array.Length && array[j].Index == num2) { list.Add(array[j]); continue; } bool flag = false; for (int k = 0; k < array.Length; k++) { if (array[k].Index == num2) { list.Add(array[k]); flag = true; break; } } if (!flag) { list.Add(new CodeBlockEntry(num2, -1, CodeBlockEntry.Type.CompilerGenerated, 0)); } } array = list.ToArray(); } MethodEntry entry = new MethodEntry(file, _comp_unit.Entry, token, ScopeVariables, Locals, method_lines.ToArray(), array, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id); file.AddMethod(entry); } } public class SymbolWriterImpl : ISymbolWriter { private MonoSymbolWriter msw; private int nextLocalIndex; private int currentToken; private string methodName; private Stack namespaceStack = new Stack(); private bool methodOpened; private Hashtable documents = new Hashtable(); private Guid guid; public SymbolWriterImpl(Guid guid) { this.guid = guid; } public void Close() { msw.WriteSymbolFile(guid); } public void CloseMethod() { if (methodOpened) { methodOpened = false; nextLocalIndex = 0; msw.CloseMethod(); } } public void CloseNamespace() { namespaceStack.Pop(); msw.CloseNamespace(); } public void CloseScope(int endOffset) { msw.CloseScope(endOffset); } public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) { SymbolDocumentWriterImpl symbolDocumentWriterImpl = (SymbolDocumentWriterImpl)documents[url]; if (symbolDocumentWriterImpl == null) { SourceFileEntry source = msw.DefineDocument(url); symbolDocumentWriterImpl = new SymbolDocumentWriterImpl(msw.DefineCompilationUnit(source)); documents[url] = symbolDocumentWriterImpl; } return symbolDocumentWriterImpl; } public void DefineField(SymbolToken parent, string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineGlobalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineLocalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset) { msw.DefineLocalVariable(nextLocalIndex++, name); } public void DefineParameter(string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) { SourceFileEntry file = ((SymbolDocumentWriterImpl)document)?.Entry.SourceFile; for (int i = 0; i < offsets.Length; i++) { if (i <= 0 || offsets[i] != offsets[i - 1] || lines[i] != lines[i - 1] || columns[i] != columns[i - 1]) { msw.MarkSequencePoint(offsets[i], file, lines[i], columns[i], is_hidden: false); } } } public void Initialize(IntPtr emitter, string filename, bool fFullBuild) { msw = new MonoSymbolWriter(filename); } public void OpenMethod(SymbolToken method) { currentToken = method.GetToken(); } public void OpenNamespace(string name) { NamespaceInfo namespaceInfo = new NamespaceInfo(); namespaceInfo.NamespaceID = -1; namespaceInfo.Name = name; namespaceStack.Push(namespaceInfo); } public int OpenScope(int startOffset) { return msw.OpenScope(startOffset); } public void SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn) { int currentNamespace = GetCurrentNamespace(startDoc); SourceMethodImpl method = new SourceMethodImpl(methodName, currentToken, currentNamespace); msw.OpenMethod(((ICompileUnit)startDoc).Entry, currentNamespace, method); methodOpened = true; } public void SetScopeRange(int scopeID, int startOffset, int endOffset) { } public void SetSymAttribute(SymbolToken parent, string name, byte[] data) { if (name == "__name") { methodName = Encoding.UTF8.GetString(data); } } public void SetUnderlyingWriter(IntPtr underlyingWriter) { } public void SetUserEntryPoint(SymbolToken entryMethod) { } public void UsingNamespace(string fullName) { if (namespaceStack.Count == 0) { OpenNamespace(""); } NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek(); if (namespaceInfo.NamespaceID != -1) { NamespaceInfo namespaceInfo2 = namespaceInfo; CloseNamespace(); OpenNamespace(namespaceInfo2.Name); namespaceInfo = (NamespaceInfo)namespaceStack.Peek(); namespaceInfo.UsingClauses = namespaceInfo2.UsingClauses; } namespaceInfo.UsingClauses.Add(fullName); } private int GetCurrentNamespace(ISymbolDocumentWriter doc) { if (namespaceStack.Count == 0) { OpenNamespace(""); } NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek(); if (namespaceInfo.NamespaceID == -1) { string[] using_clauses = (string[])namespaceInfo.UsingClauses.ToArray(typeof(string)); int parent = 0; if (namespaceStack.Count > 1) { namespaceStack.Pop(); parent = ((NamespaceInfo)namespaceStack.Peek()).NamespaceID; namespaceStack.Push(namespaceInfo); } namespaceInfo.NamespaceID = msw.DefineNamespace(namespaceInfo.Name, ((ICompileUnit)doc).Entry, using_clauses, parent); } return namespaceInfo.NamespaceID; } } internal class SymbolDocumentWriterImpl : ISymbolDocumentWriter, ISourceFile, ICompileUnit { private CompileUnitEntry comp_unit; SourceFileEntry ISourceFile.Entry => comp_unit.SourceFile; public CompileUnitEntry Entry => comp_unit; public SymbolDocumentWriterImpl(CompileUnitEntry comp_unit) { this.comp_unit = comp_unit; } public void SetCheckSum(Guid algorithmId, byte[] checkSum) { } public void SetSource(byte[] source) { } } internal class SourceMethodImpl : IMethodDef { private string name; private int token; private int namespaceID; public string Name => name; public int NamespaceID => namespaceID; public int Token => token; public SourceMethodImpl(string name, int token, int namespaceID) { this.name = name; this.token = token; this.namespaceID = namespaceID; } } internal class NamespaceInfo { public string Name; public int NamespaceID; public ArrayList UsingClauses = new ArrayList(); } } namespace Mono.Cecil.Mdb { public sealed class MdbReaderProvider : ISymbolReaderProvider { public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(Mixin.GetMdbFileName(fileName))); } public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(symbolStream)); } } public sealed class MdbReader : ISymbolReader, IDisposable { private readonly ModuleDefinition module; private readonly MonoSymbolFile symbol_file; private readonly Dictionary<string, Document> documents; public MdbReader(ModuleDefinition module, MonoSymbolFile symFile) { this.module = module; symbol_file = symFile; documents = new Dictionary<string, Document>(); } public ISymbolWriterProvider GetWriterProvider() { return (ISymbolWriterProvider)(object)new MdbWriterProvider(); } public bool ProcessDebugHeader(ImageDebugHeader header) { return symbol_file.Guid == module.Mvid; } public MethodDebugInformation Read(MethodDefinition method) { //IL_0001: 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_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown MetadataToken metadataToken = ((MemberReference)method).MetadataToken; MethodEntry methodByToken = symbol_file.GetMethodByToken(((MetadataToken)(ref metadataToken)).ToInt32()); if (methodByToken == null) { return null; } MethodDebugInformation val = new MethodDebugInformation(method); val.code_size = ReadCodeSize(method); ScopeDebugInformation[] scopes = ReadScopes(methodByToken, val); ReadLineNumbers(methodByToken, val); ReadLocalVariables(methodByToken, scopes); return val; } private static int ReadCodeSize(MethodDefinition method) { return ((MemberReference)method).Module.Read<MethodDefinition, int>(method, (Func<MethodDefinition, MetadataReader, int>)((MethodDefinition m, MetadataReader reader) => reader.ReadCodeSize(m))); } private static void ReadLocalVariables(MethodEntry entry, ScopeDebugInformation[] scopes) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown LocalVariableEntry[] locals = entry.GetLocals(); for (int i = 0; i < locals.Length; i++) { LocalVariableEntry localVariableEntry = locals[i]; VariableDebugInformation val = new VariableDebugInformation(localVariableEntry.Index, localVariableEntry.Name); int blockIndex = localVariableEntry.BlockIndex; if (blockIndex >= 0 && blockIndex < scopes.Length) { ScopeDebugInformation val2 = scopes[blockIndex]; if (val2 != null) { val2.Variables.Add(val); } } } } private void ReadLineNumbers(MethodEntry entry, MethodDebugInformation info) { LineNumberTable lineNumberTable = entry.GetLineNumberTable(); info.sequence_points = new Collection<SequencePoint>(lineNumberTable.LineNumbers.Length); for (int i = 0; i < lineNumberTable.LineNumbers.Length; i++) { LineNumberEntry lineNumberEntry = lineNumberTable.LineNumbers[i]; if (i <= 0 || lineNumberTable.LineNumbers[i - 1].Offset != lineNumberEntry.Offset) { info.sequence_points.Add(LineToSequencePoint(lineNumberEntry)); } } } private Document GetDocument(SourceFileEntry file) { //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_002c: Expected O, but got Unknown string fileName = file.FileName; if (documents.TryGetValue(fileName, out var value)) { return value; } value = new Document(fileName) { Hash = file.Checksum }; documents.Add(fileName, value); return value; } private static ScopeDebugInformation[] ReadScopes(MethodEntry entry, MethodDebugInformation info) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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_0038: Expected O, but got Unknown //IL_0039: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) CodeBlockEntry[] codeBlocks = entry.GetCodeBlocks(); ScopeDebugInformation[] array = (ScopeDebugInformation[])(object)new ScopeDebugInformation[codeBlocks.Length + 1]; ScopeDebugInformation val = new ScopeDebugInformation { Start = new InstructionOffset(0), End = new InstructionOffset(info.code_size) }; ScopeDebugInformation scope = val; array[0] = val; info.scope = scope; CodeBlockEntry[] array2 = codeBlocks; foreach (CodeBlockEntry codeBlockEntry in array2) { if (codeBlockEntry.BlockType == CodeBlockEntry.Type.Lexical || codeBlockEntry.BlockType == CodeBlockEntry.Type.CompilerGenerated) { ScopeDebugInformation val2 = new ScopeDebugInformation(); val2.Start = new InstructionOffset(codeBlockEntry.StartOffset); val2.End = new InstructionOffset(codeBlockEntry.EndOffset); array[codeBlockEntry.Index + 1] = val2; if (!AddScope(info.scope.Scopes, val2)) { info.scope.Scopes.Add(val2); } } } return array; } private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope) { //IL_0001: 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_002c: 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) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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) //IL_005d: Unknown result type (might be due to invalid IL or missing references) Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator(); try { while (enumerator.MoveNext()) { ScopeDebugInformation current = enumerator.Current; if (current.HasScopes && AddScope(current.Scopes, scope)) { return true; } InstructionOffset val = scope.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = current.Start; if (offset >= ((InstructionOffset)(ref val)).Offset) { val = scope.End; int offset2 = ((InstructionOffset)(ref val)).Offset; val = current.End; if (offset2 <= ((InstructionOffset)(ref val)).Offset) { current.Scopes.Add(scope); return true; } } } } finally { ((IDisposable)enumerator).Dispose(); } return false; } private SequencePoint LineToSequencePoint(LineNumberEntry line) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown SourceFileEntry sourceFile = symbol_file.GetSourceFile(line.File); return new SequencePoint(line.Offset, GetDocument(sourceFile)) { StartLine = line.Row, EndLine = line.EndRow, StartColumn = line.Column, EndColumn = line.EndColumn }; } public void Dispose() { symbol_file.Dispose(); } } internal static class MethodEntryExtensions { public static bool HasColumnInfo(this MethodEntry entry) { return (entry.MethodFlags & MethodEntry.Flags.ColumnsInfoIncluded) != 0; } public static bool HasEndInfo(this MethodEntry entry) { return (entry.MethodFlags & MethodEntry.Flags.EndInfoIncluded) != 0; } } public sealed class MdbWriterProvider : ISymbolWriterProvider { public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName) { Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolWriter)(object)new MdbWriter(module.Mvid, fileName); } public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream) { throw new NotImplementedException(); } } public sealed class MdbWriter : ISymbolWriter, IDisposable { private class SourceFile : ISourceFile { private readonly CompileUnitEntry compilation_unit; private readonly SourceFileEntry entry; public SourceFileEntry Entry => entry; public CompileUnitEntry CompilationUnit => compilation_unit; public SourceFile(CompileUnitEntry comp_unit, SourceFileEntry entry) { compilation_unit = comp_unit; this.entry = entry; } } private class SourceMethod : IMethodDef { private readonly MethodDefinition method; public string Name => ((MemberReference)method).Name; public int Token { get { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) MetadataToken metadataToken = ((MemberReference)method).MetadataToken; return ((MetadataToken)(ref metadataToken)).ToInt32(); } } public SourceMethod(MethodDefinition method) { this.method = method; } } private readonly Guid mvid; private readonly MonoSymbolWriter writer; private readonly Dictionary<string, SourceFile> source_files; public MdbWriter(Guid mvid, string assembly) { this.mvid = mvid; writer = new MonoSymbolWriter(assembly); source_files = new Dictionary<string, SourceFile>(); } public ISymbolReaderProvider GetReaderProvider() { return (ISymbolReaderProvider)(object)new MdbReaderProvider(); } private SourceFile GetSourceFile(Document document) { string url = document.Url; if (source_files.TryGetValue(url, out var value)) { return value; } SourceFileEntry sourceFileEntry = writer.DefineDocument(url, null, (document.Hash != null && document.Hash.Length == 16) ? document.Hash : null); value = new SourceFile(writer.DefineCompilationUnit(sourceFileEntry), sourceFileEntry); source_files.Add(url, value); return value; } private void Populate(Collection<SequencePoint> sequencePoints, int[] offsets, int[] startRows, int[] endRows, int[] startCols, int[] endCols, out SourceFile file) { SourceFile sourceFile = null; for (int i = 0; i < sequencePoints.Count; i++) { SequencePoint val = sequencePoints[i]; offsets[i] = val.Offset; if (sourceFile == null) { sourceFile = GetSourceFile(val.Document); } startRows[i] = val.StartLine; endRows[i] = val.EndLine; startCols[i] = val.StartColumn; endCols[i] = val.EndColumn; } file = sourceFile; } public void Write(MethodDebugInformation info) { SourceMethod method = new SourceMethod(info.method); Collection<SequencePoint> sequencePoints = info.SequencePoints; int count = sequencePoints.Count; if (count != 0) { int[] array = new int[count]; int[] array2 = new int[count]; int[] array3 = new int[count]; int[] array4 = new int[count]; int[] array5 = new int[count]; Populate(sequencePoints, array, array2, array3, array4, array5, out var file); SourceMethodBuilder sourceMethodBuilder = writer.OpenMethod(file.CompilationUnit, 0, method); for (int i = 0; i < count; i++) { sourceMethodBuilder.MarkSequencePoint(array[i], file.CompilationUnit.SourceFile, array2[i], array4[i], array3[i], array5[i], is_hidden: false); } if (info.scope != null) { WriteRootScope(info.scope, info); } writer.CloseMethod(); } } private void WriteRootScope(ScopeDebugInformation scope, MethodDebugInformation info) { WriteScopeVariables(scope); if (scope.HasScopes) { WriteScopes(scope.Scopes, info); } } private void WriteScope(ScopeDebugInformation scope, MethodDebugInformation info) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: 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_0052: Unknown result type (might be due to invalid IL or missing references) MonoSymbolWriter monoSymbolWriter = writer; InstructionOffset val = scope.Start; monoSymbolWriter.OpenScope(((InstructionOffset)(ref val)).Offset); WriteScopeVariables(scope); if (scope.HasScopes) { WriteScopes(scope.Scopes, info); } MonoSymbolWriter monoSymbolWriter2 = writer; val = scope.End; int end_offset; if (!((InstructionOffset)(ref val)).IsEndOfMethod) { val = scope.End; end_offset = ((InstructionOffset)(ref val)).Offset; } else { end_offset = info.code_size; } monoSymbolWriter2.CloseScope(end_offset); } private void WriteScopes(Collection<ScopeDebugInformation> scopes, MethodDebugInformation info) { for (int i = 0; i < scopes.Count; i++) { WriteScope(scopes[i], info); } } private void WriteScopeVariables(ScopeDebugInformation scope) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (!scope.HasVariables) { return; } Enumerator<VariableDebugInformation> enumerator = scope.variables.GetEnumerator(); try { while (enumerator.MoveNext()) { VariableDebugInformation current = enumerator.Current; if (!string.IsNullOrEmpty(current.Name)) { writer.DefineLocalVariable(current.Index, current.Name); } } } finally { ((IDisposable)enumerator).Dispose(); } } public ImageDebugHeader GetDebugHeader() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown return new ImageDebugHeader(); } public void Dispose() { writer.WriteSymbolFile(mvid); } } }
UMM/Mods/Runtime Unity Editor/Mono.Cecil.Pdb.dll
Decompiled a month 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.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; using Microsoft.Cci; using Microsoft.Cci.Pdb; using Mono.Cecil.Cil; using Mono.Cecil.PE; using Mono.Collections.Generic; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.10.4.0")] [assembly: AssemblyInformationalVersion("0.10.4.0")] [assembly: AssemblyTitle("Mono.Cecil.Pdb")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("0.10.4.0")] namespace Mono.Cecil.Pdb { [ComImport] [Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISymUnmanagedDocumentWriter { } [ComImport] [Guid("0B97726E-9E6D-4f05-9A26-424022093CAA")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISymUnmanagedWriter2 { void DefineDocument([In][MarshalAs(UnmanagedType.LPWStr)] string url, [In] ref Guid langauge, [In] ref Guid languageVendor, [In] ref Guid documentType, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedDocumentWriter pRetVal); void SetUserEntryPoint([In] int methodToken); void OpenMethod([In] int methodToken); void CloseMethod(); void OpenScope([In] int startOffset, out int pRetVal); void CloseScope([In] int endOffset); void SetScopeRange_Placeholder(); void DefineLocalVariable_Placeholder(); void DefineParameter_Placeholder(); void DefineField_Placeholder(); void DefineGlobalVariable_Placeholder(); void Close(); void SetSymAttribute(uint parent, string name, uint data, IntPtr signature); void OpenNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string name); void CloseNamespace(); void UsingNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string fullName); void SetMethodSourceRange_Placeholder(); void Initialize([In][MarshalAs(UnmanagedType.IUnknown)] object emitter, [In][MarshalAs(UnmanagedType.LPWStr)] string filename, [In] IStream pIStream, [In] bool fFullBuild); void GetDebugInfo(out ImageDebugDirectory pIDD, [In] int cData, out int pcData, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data); void DefineSequencePoints([In][MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document, [In] int spCount, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); void RemapToken_Placeholder(); void Initialize2_Placeholder(); void DefineConstant_Placeholder(); void Abort_Placeholder(); void DefineLocalVariable2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In] int attributes, [In] int sigToken, [In] int addrKind, [In] int addr1, [In] int addr2, [In] int addr3, [In] int startOffset, [In] int endOffset); void DefineGlobalVariable2_Placeholder(); void DefineConstant2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In][MarshalAs(UnmanagedType.Struct)] object variant, [In] int sigToken); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")] internal interface IMetaDataEmit { void SetModuleProps(string szName); void Save(string szFile, uint dwSaveFlags); void SaveToStream(IntPtr pIStream, uint dwSaveFlags); uint GetSaveSize(uint fSave); uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements); uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser); void SetHandler([In][MarshalAs(UnmanagedType.IUnknown)] object pUnk); uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags); void DefineMethodImpl(uint td, uint tkBody, uint tkDecl); uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName); uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit); uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob); uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent); uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods); void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize); void DeleteClassLayout(uint td); void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType); void DeleteFieldMarshal(uint tk); uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission); void SetRVA(uint md, uint ulRVA); uint GetTokenFromSig(IntPtr pvSig, uint cbSig); uint DefineModuleRef(string szName); void SetParent(uint mr, uint tk); uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig); void SaveToMemory(IntPtr pbData, uint cbData); uint DefineUserString(string szString, uint cchString); void DeleteToken(uint tkObj); void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags); void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements); void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods); uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission); void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL); void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL); void DeletePinvokeMap(uint tk); uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute); void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute); uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods); uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods); void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs); void ApplyEditAndContinue([MarshalAs(UnmanagedType.IUnknown)] object pImport); uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax); void SetMethodImplFlags(uint md, uint dwImplFlags); void SetFieldRVA(uint fd, uint ulRVA); void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs(UnmanagedType.IUnknown)] object pHandler); void MergeEnd(); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44")] internal interface IMetaDataImport { [PreserveSig] void CloseEnum(uint hEnum); uint CountEnum(uint hEnum); void ResetEnum(uint hEnum, uint ulPos); uint EnumTypeDefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeDefs, uint cMax); uint EnumInterfaceImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rImpls, uint cMax); uint EnumTypeRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeRefs, uint cMax); uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass); Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName); uint GetModuleFromScope(); uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags); uint GetInterfaceImplProps(uint iiImpl, out uint pClass); uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName); uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope); uint EnumMembers(ref uint phEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMembers, uint cMax); uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMembers, uint cMax); uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax); uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethods, uint cMax); uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax); uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rFields, uint cMax); uint EnumParams(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rParams, uint cMax); uint EnumMemberRefs(ref uint phEnum, uint tkParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMemberRefs, uint cMax); uint EnumMethodImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodDecl, uint cMax); uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rPermission, uint cMax); uint FindMember(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint FindMethod(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint FindField(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint FindMemberRef(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA); uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob); uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax); uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax); uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint cMax); uint EnumMethodSemantics(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rEventProp, uint cMax); uint GetMethodSemantics(uint mb, uint tkEventProp); uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset); uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType); uint GetRVA(uint tk, out uint pulCodeRVA); uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission); uint GetSigFromToken(uint mdSig, out IntPtr ppvSig); uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName); uint EnumModuleRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rModuleRefs, uint cmax); uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig); uint GetNameFromToken(uint tk); uint EnumUnresolvedMethods(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rMethods, uint cMax); uint GetUserString(uint stk, StringBuilder szString, uint cchString); uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName); uint EnumSignatures(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rSignatures, uint cmax); uint EnumTypeSpecs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeSpecs, uint cmax); uint EnumUserStrings(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rStrings, uint cmax); [PreserveSig] int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam); uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rCustomAttributes, uint cMax); uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob); uint FindTypeRef(uint tkResolutionScope, string szName); uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue); uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue); uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint cMax); uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue); uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData); [PreserveSig] [return: MarshalAs(UnmanagedType.Bool)] bool IsValidToken(uint tk); uint GetNestedClassProps(uint tdNestedClass); uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig); int IsGlobal(uint pd); } internal class ModuleMetadata : IMetaDataEmit, IMetaDataImport { private readonly ModuleDefinition module; private Dictionary<uint, TypeDefinition> types; private Dictionary<uint, MethodDefinition> methods; public ModuleMetadata(ModuleDefinition module) { this.module = module; } private bool TryGetType(uint token, out TypeDefinition type) { if (types == null) { InitializeMetadata(module); } return types.TryGetValue(token, out type); } private bool TryGetMethod(uint token, out MethodDefinition method) { if (methods == null) { InitializeMetadata(module); } return methods.TryGetValue(token, out method); } private void InitializeMetadata(ModuleDefinition module) { //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) types = new Dictionary<uint, TypeDefinition>(); methods = new Dictionary<uint, MethodDefinition>(); foreach (TypeDefinition type in module.GetTypes()) { Dictionary<uint, TypeDefinition> dictionary = types; MetadataToken metadataToken = ((MemberReference)type).MetadataToken; dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), type); InitializeMethods(type); } } private void InitializeMethods(TypeDefinition type) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; Dictionary<uint, MethodDefinition> dictionary = methods; MetadataToken metadataToken = ((MemberReference)current).MetadataToken; dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), current); } } finally { ((IDisposable)enumerator).Dispose(); } } public void SetModuleProps(string szName) { throw new NotImplementedException(); } public void Save(string szFile, uint dwSaveFlags) { throw new NotImplementedException(); } public void SaveToStream(IntPtr pIStream, uint dwSaveFlags) { throw new NotImplementedException(); } public uint GetSaveSize(uint fSave) { throw new NotImplementedException(); } public uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements) { throw new NotImplementedException(); } public uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser) { throw new NotImplementedException(); } public void SetHandler(object pUnk) { throw new NotImplementedException(); } public uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags) { throw new NotImplementedException(); } public void DefineMethodImpl(uint td, uint tkBody, uint tkDecl) { throw new NotImplementedException(); } public uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName) { throw new NotImplementedException(); } public uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit) { throw new NotImplementedException(); } public uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent) { throw new NotImplementedException(); } public uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize) { throw new NotImplementedException(); } public void DeleteClassLayout(uint td) { throw new NotImplementedException(); } public void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType) { throw new NotImplementedException(); } public void DeleteFieldMarshal(uint tk) { throw new NotImplementedException(); } public uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission) { throw new NotImplementedException(); } public void SetRVA(uint md, uint ulRVA) { throw new NotImplementedException(); } public uint GetTokenFromSig(IntPtr pvSig, uint cbSig) { throw new NotImplementedException(); } public uint DefineModuleRef(string szName) { throw new NotImplementedException(); } public void SetParent(uint mr, uint tk) { throw new NotImplementedException(); } public uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig) { throw new NotImplementedException(); } public void SaveToMemory(IntPtr pbData, uint cbData) { throw new NotImplementedException(); } public uint DefineUserString(string szString, uint cchString) { throw new NotImplementedException(); } public void DeleteToken(uint tkObj) { throw new NotImplementedException(); } public void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags) { throw new NotImplementedException(); } public void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements) { throw new NotImplementedException(); } public void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission) { throw new NotImplementedException(); } public void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL) { throw new NotImplementedException(); } public void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL) { throw new NotImplementedException(); } public void DeletePinvokeMap(uint tk) { throw new NotImplementedException(); } public uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute) { throw new NotImplementedException(); } public void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute) { throw new NotImplementedException(); } public uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs) { throw new NotImplementedException(); } public void ApplyEditAndContinue(object pImport) { throw new NotImplementedException(); } public uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax) { throw new NotImplementedException(); } public void SetMethodImplFlags(uint md, uint dwImplFlags) { throw new NotImplementedException(); } public void SetFieldRVA(uint fd, uint ulRVA) { throw new NotImplementedException(); } public void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, object pHandler) { throw new NotImplementedException(); } public void MergeEnd() { throw new NotImplementedException(); } public void CloseEnum(uint hEnum) { throw new NotImplementedException(); } public uint CountEnum(uint hEnum) { throw new NotImplementedException(); } public void ResetEnum(uint hEnum, uint ulPos) { throw new NotImplementedException(); } public uint EnumTypeDefs(ref uint phEnum, uint[] rTypeDefs, uint cMax) { throw new NotImplementedException(); } public uint EnumInterfaceImpls(ref uint phEnum, uint td, uint[] rImpls, uint cMax) { throw new NotImplementedException(); } public uint EnumTypeRefs(ref uint phEnum, uint[] rTypeRefs, uint cMax) { throw new NotImplementedException(); } public uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass) { throw new NotImplementedException(); } public Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName) { throw new NotImplementedException(); } public uint GetModuleFromScope() { throw new NotImplementedException(); } public uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected I4, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (!TryGetType(td, out var type)) { Marshal.WriteInt16(szTypeDef, 0); pchTypeDef = 1u; return 0u; } WriteString(((TypeReference)type).IsNested ? ((MemberReference)type).Name : ((MemberReference)type).FullName, szTypeDef, cchTypeDef, out pchTypeDef); WriteIntPtr(pdwTypeDefFlags, (uint)(int)type.Attributes); if (type.BaseType == null) { return 0u; } MetadataToken metadataToken = ((MemberReference)type.BaseType).MetadataToken; return ((MetadataToken)(ref metadataToken)).ToUInt32(); } private static void WriteIntPtr(IntPtr ptr, uint value) { if (!(ptr == IntPtr.Zero)) { Marshal.WriteInt32(ptr, (int)value); } } private static void WriteString(string str, IntPtr buffer, uint bufferSize, out uint chars) { uint num = ((str.Length + 1 >= bufferSize) ? (bufferSize - 1) : ((uint)str.Length)); chars = num + 1; int num2 = 0; for (int i = 0; i < num; i++) { Marshal.WriteInt16(buffer, num2, str[i]); num2 += 2; } Marshal.WriteInt16(buffer, num2, 0); } public uint GetInterfaceImplProps(uint iiImpl, out uint pClass) { throw new NotImplementedException(); } public uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName) { throw new NotImplementedException(); } public uint ResolveTypeRef(uint tr, ref Guid riid, out object ppIScope) { throw new NotImplementedException(); } public uint EnumMembers(ref uint phEnum, uint cl, uint[] rMembers, uint cMax) { throw new NotImplementedException(); } public uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, uint[] rMembers, uint cMax) { throw new NotImplementedException(); } public uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax) { throw new NotImplementedException(); } public uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, uint[] rMethods, uint cMax) { throw new NotImplementedException(); } public uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax) { throw new NotImplementedException(); } public uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, uint[] rFields, uint cMax) { throw new NotImplementedException(); } public uint EnumParams(ref uint phEnum, uint mb, uint[] rParams, uint cMax) { throw new NotImplementedException(); } public uint EnumMemberRefs(ref uint phEnum, uint tkParent, uint[] rMemberRefs, uint cMax) { throw new NotImplementedException(); } public uint EnumMethodImpls(ref uint phEnum, uint td, uint[] rMethodBody, uint[] rMethodDecl, uint cMax) { throw new NotImplementedException(); } public uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, uint[] rPermission, uint cMax) { throw new NotImplementedException(); } public uint FindMember(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint FindMethod(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint FindField(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint FindMemberRef(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected I4, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected I4, but got Unknown if (!TryGetMethod(mb, out var method)) { Marshal.WriteInt16(szMethod, 0); pchMethod = 1u; pClass = 0u; return 0u; } MetadataToken metadataToken = ((MemberReference)method.DeclaringType).MetadataToken; pClass = ((MetadataToken)(ref metadataToken)).ToUInt32(); WriteString(((MemberReference)method).Name, szMethod, cchMethod, out pchMethod); WriteIntPtr(pdwAttr, (uint)(int)method.Attributes); WriteIntPtr(pulCodeRVA, (uint)method.RVA); return (uint)(int)method.ImplAttributes; } public uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob) { throw new NotImplementedException(); } public uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax) { throw new NotImplementedException(); } public uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax) { throw new NotImplementedException(); } public uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, uint[] rmdOtherMethod, uint cMax) { throw new NotImplementedException(); } public uint EnumMethodSemantics(ref uint phEnum, uint mb, uint[] rEventProp, uint cMax) { throw new NotImplementedException(); } public uint GetMethodSemantics(uint mb, uint tkEventProp) { throw new NotImplementedException(); } public uint GetClassLayout(uint td, out uint pdwPackSize, IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset) { throw new NotImplementedException(); } public uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType) { throw new NotImplementedException(); } public uint GetRVA(uint tk, out uint pulCodeRVA) { throw new NotImplementedException(); } public uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission) { throw new NotImplementedException(); } public uint GetSigFromToken(uint mdSig, out IntPtr ppvSig) { throw new NotImplementedException(); } public uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName) { throw new NotImplementedException(); } public uint EnumModuleRefs(ref uint phEnum, uint[] rModuleRefs, uint cmax) { throw new NotImplementedException(); } public uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig) { throw new NotImplementedException(); } public uint GetNameFromToken(uint tk) { throw new NotImplementedException(); } public uint EnumUnresolvedMethods(ref uint phEnum, uint[] rMethods, uint cMax) { throw new NotImplementedException(); } public uint GetUserString(uint stk, StringBuilder szString, uint cchString) { throw new NotImplementedException(); } public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName) { throw new NotImplementedException(); } public uint EnumSignatures(ref uint phEnum, uint[] rSignatures, uint cmax) { throw new NotImplementedException(); } public uint EnumTypeSpecs(ref uint phEnum, uint[] rTypeSpecs, uint cmax) { throw new NotImplementedException(); } public uint EnumUserStrings(ref uint phEnum, uint[] rStrings, uint cmax) { throw new NotImplementedException(); } public int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam) { throw new NotImplementedException(); } public uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, uint[] rCustomAttributes, uint cMax) { throw new NotImplementedException(); } public uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob) { throw new NotImplementedException(); } public uint FindTypeRef(uint tkResolutionScope, string szName) { throw new NotImplementedException(); } public uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException(); } public uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException(); } public uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, uint[] rmdOtherMethod, uint cMax) { throw new NotImplementedException(); } public uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException(); } public uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData) { throw new NotImplementedException(); } public bool IsValidToken(uint tk) { throw new NotImplementedException(); } public uint GetNestedClassProps(uint tdNestedClass) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) if (!TryGetType(tdNestedClass, out var type)) { return 0u; } if (!((TypeReference)type).IsNested) { return 0u; } MetadataToken metadataToken = ((MemberReference)type.DeclaringType).MetadataToken; return ((MetadataToken)(ref metadataToken)).ToUInt32(); } public uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig) { throw new NotImplementedException(); } public int IsGlobal(uint pd) { throw new NotImplementedException(); } } public class NativePdbReader : ISymbolReader, IDisposable { private int age; private Guid guid; private readonly Disposable<Stream> pdb_file; private readonly Dictionary<string, Document> documents = new Dictionary<string, Document>(); private readonly Dictionary<uint, PdbFunction> functions = new Dictionary<uint, PdbFunction>(); private readonly Dictionary<PdbScope, ImportDebugInformation> imports = new Dictionary<PdbScope, ImportDebugInformation>(); internal NativePdbReader(Disposable<Stream> file) { //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) pdb_file = file; } public ISymbolWriterProvider GetWriterProvider() { return (ISymbolWriterProvider)(object)new NativePdbWriterProvider(); } public bool ProcessDebugHeader(ImageDebugHeader header) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 if (!header.HasEntries) { return false; } ImageDebugHeaderEntry codeViewEntry = Mixin.GetCodeViewEntry(header); if (codeViewEntry == null) { return false; } if ((int)codeViewEntry.Directory.Type != 2) { return false; } byte[] data = codeViewEntry.Data; if (data.Length < 24) { return false; } if (ReadInt32(data, 0) != 1396986706) { return false; } byte[] array = new byte[16]; Buffer.BlockCopy(data, 4, array, 0, 16); guid = new Guid(array); age = ReadInt32(data, 20); return PopulateFunctions(); } private static int ReadInt32(byte[] bytes, int start) { return bytes[start] | (bytes[start + 1] << 8) | (bytes[start + 2] << 16) | (bytes[start + 3] << 24); } private bool PopulateFunctions() { //IL_0001: 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_0008: Unknown result type (might be due to invalid IL or missing references) Disposable<Stream> val = pdb_file; try { Dictionary<uint, PdbTokenLine> tokenToSourceMapping; string sourceServerData; int num; Guid guid; PdbFunction[] array = PdbFile.LoadFunctions(pdb_file.value, out tokenToSourceMapping, out sourceServerData, out num, out guid); if (this.guid != guid) { return false; } PdbFunction[] array2 = array; foreach (PdbFunction pdbFunction in array2) { functions.Add(pdbFunction.token, pdbFunction); } } finally { ((IDisposable)val).Dispose(); } return true; } public MethodDebugInformation Read(MethodDefinition method) { //IL_0001: 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_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Expected O, but got Unknown //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Expected O, but got Unknown //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Expected O, but got Unknown MetadataToken metadataToken = ((MemberReference)method).MetadataToken; if (!functions.TryGetValue(((MetadataToken)(ref metadataToken)).ToUInt32(), out var value)) { return null; } MethodDebugInformation val = new MethodDebugInformation(method); ReadSequencePoints(value, val); val.scope = (ScopeDebugInformation)((!Mixin.IsNullOrEmpty<PdbScope>(value.scopes)) ? ((object)ReadScopeAndLocals(value.scopes[0], val)) : ((object)new ScopeDebugInformation { Start = new InstructionOffset(0), End = new InstructionOffset((int)value.length) })); uint tokenOfMethodWhoseUsingInfoAppliesToThisMethod = value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod; MetadataToken metadataToken2 = ((MemberReference)method).MetadataToken; if (tokenOfMethodWhoseUsingInfoAppliesToThisMethod != ((MetadataToken)(ref metadataToken2)).ToUInt32() && value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod != 0) { val.scope.import = GetImport(value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod, ((MemberReference)method).Module); } if (value.scopes.Length > 1) { for (int i = 1; i < value.scopes.Length; i++) { ScopeDebugInformation val2 = ReadScopeAndLocals(value.scopes[i], val); if (!AddScope(val.scope.Scopes, val2)) { val.scope.Scopes.Add(val2); } } } if (value.iteratorScopes != null) { StateMachineScopeDebugInformation val3 = new StateMachineScopeDebugInformation(); foreach (ILocalScope iteratorScope in value.iteratorScopes) { val3.Scopes.Add(new StateMachineScope((int)iteratorScope.Offset, (int)(iteratorScope.Offset + iteratorScope.Length + 1))); } ((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val3); } if (value.synchronizationInformation != null) { AsyncMethodBodyDebugInformation val4 = new AsyncMethodBodyDebugInformation((int)value.synchronizationInformation.GeneratedCatchHandlerOffset); PdbSynchronizationPoint[] synchronizationPoints = value.synchronizationInformation.synchronizationPoints; foreach (PdbSynchronizationPoint pdbSynchronizationPoint in synchronizationPoints) { val4.Yields.Add(new InstructionOffset((int)pdbSynchronizationPoint.SynchronizeOffset)); val4.Resumes.Add(new InstructionOffset((int)pdbSynchronizationPoint.ContinuationOffset)); val4.ResumeMethods.Add(method); } ((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val4); val.StateMachineKickOffMethod = (MethodDefinition)((MemberReference)method).Module.LookupToken((int)value.synchronizationInformation.kickoffMethodToken); } return val; } private Collection<ScopeDebugInformation> ReadScopeAndLocals(PdbScope[] scopes, MethodDebugInformation info) { Collection<ScopeDebugInformation> val = new Collection<ScopeDebugInformation>(scopes.Length); foreach (PdbScope pdbScope in scopes) { if (pdbScope != null) { val.Add(ReadScopeAndLocals(pdbScope, info)); } } return val; } private ScopeDebugInformation ReadScopeAndLocals(PdbScope scope, MethodDebugInformation info) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Expected O, but got Unknown ScopeDebugInformation val = new ScopeDebugInformation(); val.Start = new InstructionOffset((int)scope.offset); val.End = new InstructionOffset((int)(scope.offset + scope.length)); if (!Mixin.IsNullOrEmpty<PdbSlot>(scope.slots)) { val.variables = new Collection<VariableDebugInformation>(scope.slots.Length); PdbSlot[] slots = scope.slots; foreach (PdbSlot pdbSlot in slots) { if ((pdbSlot.flags & 1) == 0) { VariableDebugInformation val2 = new VariableDebugInformation((int)pdbSlot.slot, pdbSlot.name); if ((pdbSlot.flags & 4u) != 0) { val2.IsDebuggerHidden = true; } val.variables.Add(val2); } } } if (!Mixin.IsNullOrEmpty<PdbConstant>(scope.constants)) { val.constants = new Collection<ConstantDebugInformation>(scope.constants.Length); PdbConstant[] constants = scope.constants; foreach (PdbConstant pdbConstant in constants) { TypeReference val3 = ((MemberReference)info.Method).Module.Read<PdbConstant, TypeReference>(pdbConstant, (Func<PdbConstant, MetadataReader, TypeReference>)((PdbConstant c, MetadataReader r) => r.ReadConstantSignature(new MetadataToken(c.token)))); object obj = pdbConstant.value; if (val3 != null && !val3.IsValueType && obj is int && (int)obj == 0) { obj = null; } val.constants.Add(new ConstantDebugInformation(pdbConstant.name, val3, obj)); } } if (!Mixin.IsNullOrEmpty<string>(scope.usedNamespaces)) { if (imports.TryGetValue(scope, out var value)) { val.import = value; } else { value = GetImport(scope, ((MemberReference)info.Method).Module); imports.Add(scope, value); val.import = value; } } val.scopes = ReadScopeAndLocals(scope.scopes, info); return val; } private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope) { //IL_0001: 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_002c: 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) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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) //IL_005d: Unknown result type (might be due to invalid IL or missing references) Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator(); try { while (enumerator.MoveNext()) { ScopeDebugInformation current = enumerator.Current; if (current.HasScopes && AddScope(current.Scopes, scope)) { return true; } InstructionOffset val = scope.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = current.Start; if (offset >= ((InstructionOffset)(ref val)).Offset) { val = scope.End; int offset2 = ((InstructionOffset)(ref val)).Offset; val = current.End; if (offset2 <= ((InstructionOffset)(ref val)).Offset) { current.Scopes.Add(scope); return true; } } } } finally { ((IDisposable)enumerator).Dispose(); } return false; } private ImportDebugInformation GetImport(uint token, ModuleDefinition module) { if (!functions.TryGetValue(token, out var value)) { return null; } if (value.scopes.Length != 1) { return null; } PdbScope pdbScope = value.scopes[0]; if (imports.TryGetValue(pdbScope, out var value2)) { return value2; } value2 = GetImport(pdbScope, module); imports.Add(pdbScope, value2); return value2; } private static ImportDebugInformation GetImport(PdbScope scope, ModuleDefinition module) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown //IL_00a1: 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) //IL_00b0: Expected O, but got Unknown //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Expected O, but got Unknown //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Expected O, but got Unknown //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown if (Mixin.IsNullOrEmpty<string>(scope.usedNamespaces)) { return null; } ImportDebugInformation val = new ImportDebugInformation(); string[] usedNamespaces = scope.usedNamespaces; foreach (string text in usedNamespaces) { if (string.IsNullOrEmpty(text)) { continue; } ImportTarget val2 = null; string text2 = text.Substring(1); switch (text[0]) { case 'U': val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text2 }; break; case 'T': { TypeReference val4 = TypeParser.ParseType(module, text2, false); if (val4 != null) { val2 = new ImportTarget((ImportTargetKind)3) { type = val4 }; } break; } case 'A': { int num = text.IndexOf(' '); if (num < 0) { val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text }; break; } string alias = text.Substring(1, num - 1); string text3 = text.Substring(num + 2); switch (text[num + 1]) { case 'U': val2 = new ImportTarget((ImportTargetKind)7) { alias = alias, @namespace = text3 }; break; case 'T': { TypeReference val3 = TypeParser.ParseType(module, text3, false); if (val3 != null) { val2 = new ImportTarget((ImportTargetKind)9) { alias = alias, type = val3 }; } break; } } break; } case '*': val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text2 }; break; case '@': if (!text2.StartsWith("P:")) { continue; } val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text2.Substring(2) }; break; } if (val2 != null) { val.Targets.Add(val2); } } return val; } private void ReadSequencePoints(PdbFunction function, MethodDebugInformation info) { if (function.lines != null) { info.sequence_points = new Collection<SequencePoint>(); PdbLines[] lines = function.lines; foreach (PdbLines lines2 in lines) { ReadLines(lines2, info); } } } private void ReadLines(PdbLines lines, MethodDebugInformation info) { Document document = GetDocument(lines.file); PdbLine[] lines2 = lines.lines; for (int i = 0; i < lines2.Length; i++) { ReadLine(lines2[i], document, info); } } private static void ReadLine(PdbLine line, Document document, MethodDebugInformation info) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown SequencePoint val = new SequencePoint((int)line.offset, document); val.StartLine = (int)line.lineBegin; val.StartColumn = line.colBegin; val.EndLine = (int)line.lineEnd; val.EndColumn = line.colEnd; info.sequence_points.Add(val); } private Document GetDocument(PdbSource source) { //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_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown string name = source.name; if (documents.TryGetValue(name, out var value)) { return value; } value = new Document(name) { Language = PdbGuidMapping.ToLanguage(source.language), LanguageVendor = PdbGuidMapping.ToVendor(source.vendor), Type = PdbGuidMapping.ToType(source.doctype) }; documents.Add(name, value); return value; } public void Dispose() { //IL_0001: 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) pdb_file.Dispose(); } } public class NativePdbWriter : ISymbolWriter, IDisposable { private readonly ModuleDefinition module; private readonly MetadataBuilder metadata; private readonly SymWriter writer; private readonly Dictionary<string, SymDocumentWriter> documents; private readonly Dictionary<ImportDebugInformation, MetadataToken> import_info_to_parent; internal NativePdbWriter(ModuleDefinition module, SymWriter writer) { this.module = module; metadata = module.metadata_builder; this.writer = writer; documents = new Dictionary<string, SymDocumentWriter>(); import_info_to_parent = new Dictionary<ImportDebugInformation, MetadataToken>(); } public ISymbolReaderProvider GetReaderProvider() { return (ISymbolReaderProvider)(object)new NativePdbReaderProvider(); } public ImageDebugHeader GetDebugHeader() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown ImageDebugDirectory idd; byte[] debugInfo = writer.GetDebugInfo(out idd); idd.TimeDateStamp = (int)module.timestamp; return new ImageDebugHeader(new ImageDebugHeaderEntry(idd, debugInfo)); } public void Write(MethodDebugInformation info) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: 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_007b: Unknown result type (might be due to invalid IL or missing references) MetadataToken metadataToken = ((MemberReference)info.method).MetadataToken; int methodToken = ((MetadataToken)(ref metadataToken)).ToInt32(); if (info.HasSequencePoints || info.scope != null || ((DebugInformation)info).HasCustomDebugInformations || info.StateMachineKickOffMethod != null) { writer.OpenMethod(methodToken); if (!Mixin.IsNullOrEmpty<SequencePoint>(info.sequence_points)) { DefineSequencePoints(info.sequence_points); } MetadataToken import_parent = default(MetadataToken); if (info.scope != null) { DefineScope(info.scope, info, out import_parent); } DefineCustomMetadata(info, import_parent); writer.CloseMethod(); } } private void DefineCustomMetadata(MethodDebugInformation info, MetadataToken import_parent) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) CustomMetadataWriter customMetadataWriter = new CustomMetadataWriter(writer); if (((MetadataToken)(ref import_parent)).RID != 0) { customMetadataWriter.WriteForwardInfo(import_parent); } else if (info.scope != null && info.scope.Import != null && info.scope.Import.HasTargets) { customMetadataWriter.WriteUsingInfo(info.scope.Import); } if (info.Method.HasCustomAttributes) { Enumerator<CustomAttribute> enumerator = info.Method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; TypeReference attributeType = current.AttributeType; if (Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "IteratorStateMachineAttribute") || Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute")) { CustomAttributeArgument val = current.ConstructorArguments[0]; object value = ((CustomAttributeArgument)(ref val)).Value; TypeReference val2 = (TypeReference)((value is TypeReference) ? value : null); if (val2 != null) { customMetadataWriter.WriteForwardIterator(val2); } } } } finally { ((IDisposable)enumerator).Dispose(); } } if (((DebugInformation)info).HasCustomDebugInformations) { CustomDebugInformation? obj = ((IEnumerable<CustomDebugInformation>)((DebugInformation)info).CustomDebugInformations).FirstOrDefault((Func<CustomDebugInformation, bool>)((CustomDebugInformation cdi) => (int)cdi.Kind == 1)); StateMachineScopeDebugInformation val3 = (StateMachineScopeDebugInformation)(object)((obj is StateMachineScopeDebugInformation) ? obj : null); if (val3 != null) { customMetadataWriter.WriteIteratorScopes(val3, info); } } customMetadataWriter.WriteCustomMetadata(); DefineAsyncCustomMetadata(info); } private void DefineAsyncCustomMetadata(MethodDebugInformation info) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: 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) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) if (!((DebugInformation)info).HasCustomDebugInformations) { return; } Enumerator<CustomDebugInformation> enumerator = ((DebugInformation)info).CustomDebugInformations.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomDebugInformation current = enumerator.Current; AsyncMethodBodyDebugInformation val = (AsyncMethodBodyDebugInformation)(object)((current is AsyncMethodBodyDebugInformation) ? current : null); if (val == null) { continue; } using MemoryStream memoryStream = new MemoryStream(); BinaryStreamWriter val2 = new BinaryStreamWriter((Stream)memoryStream); int num; MetadataToken metadataToken; if (info.StateMachineKickOffMethod == null) { num = 0; } else { metadataToken = ((MemberReference)info.StateMachineKickOffMethod).MetadataToken; num = (int)((MetadataToken)(ref metadataToken)).ToUInt32(); } val2.WriteUInt32((uint)num); InstructionOffset val3 = val.CatchHandler; val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset); val2.WriteUInt32((uint)val.Resumes.Count); for (int i = 0; i < val.Resumes.Count; i++) { val3 = val.Yields[i]; val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset); metadataToken = ((MemberReference)val.resume_methods[i]).MetadataToken; val2.WriteUInt32(((MetadataToken)(ref metadataToken)).ToUInt32()); val3 = val.Resumes[i]; val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset); } writer.DefineCustomMetadata("asyncMethodInfo", memoryStream.ToArray()); } } finally { ((IDisposable)enumerator).Dispose(); } } private void DefineScope(ScopeDebugInformation scope, MethodDebugInformation info, out MetadataToken import_parent) { //IL_0001: 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_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: 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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Invalid comparison between Unknown and I4 //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Invalid comparison between Unknown and I4 //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Invalid comparison between Unknown and I4 //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Invalid comparison between Unknown and I4 //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Invalid comparison between Unknown and I4 InstructionOffset val = scope.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = scope.End; int num; if (!((InstructionOffset)(ref val)).IsEndOfMethod) { val = scope.End; num = ((InstructionOffset)(ref val)).Offset; } else { num = info.code_size; } int num2 = num; import_parent = new MetadataToken(0u); writer.OpenScope(offset); if (scope.Import != null && scope.Import.HasTargets && !import_info_to_parent.TryGetValue(info.scope.Import, out import_parent)) { Enumerator<ImportTarget> enumerator = scope.Import.Targets.GetEnumerator(); try { while (enumerator.MoveNext()) { ImportTarget current = enumerator.Current; ImportTargetKind kind = current.Kind; if ((int)kind <= 3) { if ((int)kind != 1) { if ((int)kind == 3) { writer.UsingNamespace("T" + TypeParser.ToParseable(current.type, true)); } } else { writer.UsingNamespace("U" + current.@namespace); } } else if ((int)kind != 7) { if ((int)kind == 9) { writer.UsingNamespace("A" + current.Alias + " T" + TypeParser.ToParseable(current.type, true)); } } else { writer.UsingNamespace("A" + current.Alias + " U" + current.@namespace); } } } finally { ((IDisposable)enumerator).Dispose(); } import_info_to_parent.Add(info.scope.Import, ((MemberReference)info.method).MetadataToken); } int local_var_token = ((MetadataToken)(ref info.local_var_token)).ToInt32(); if (!Mixin.IsNullOrEmpty<VariableDebugInformation>(scope.variables)) { for (int i = 0; i < scope.variables.Count; i++) { VariableDebugInformation variable = scope.variables[i]; DefineLocalVariable(variable, local_var_token, offset, num2); } } if (!Mixin.IsNullOrEmpty<ConstantDebugInformation>(scope.constants)) { for (int j = 0; j < scope.constants.Count; j++) { ConstantDebugInformation constant = scope.constants[j]; DefineConstant(constant); } } if (!Mixin.IsNullOrEmpty<ScopeDebugInformation>(scope.scopes)) { for (int k = 0; k < scope.scopes.Count; k++) { DefineScope(scope.scopes[k], info, out var _); } } writer.CloseScope(num2); } private void DefineSequencePoints(Collection<SequencePoint> sequence_points) { for (int i = 0; i < sequence_points.Count; i++) { SequencePoint val = sequence_points[i]; writer.DefineSequencePoints(GetDocument(val.Document), new int[1] { val.Offset }, new int[1] { val.StartLine }, new int[1] { val.StartColumn }, new int[1] { val.EndLine }, new int[1] { val.EndColumn }); } } private void DefineLocalVariable(VariableDebugInformation variable, int local_var_token, int start_offset, int end_offset) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) writer.DefineLocalVariable2(variable.Name, variable.Attributes, local_var_token, variable.Index, 0, 0, start_offset, end_offset); } private void DefineConstant(ConstantDebugInformation constant) { uint num = metadata.AddStandAloneSignature(metadata.GetConstantTypeBlobIndex(constant.ConstantType)); MetadataToken val = default(MetadataToken); ((MetadataToken)(ref val))..ctor((TokenType)285212672, num); writer.DefineConstant2(constant.Name, constant.Value, ((MetadataToken)(ref val)).ToInt32()); } private SymDocumentWriter GetDocument(Document document) { if (document == null) { return null; } if (documents.TryGetValue(document.Url, out var value)) { return value; } value = writer.DefineDocument(document.Url, document.LanguageGuid, document.LanguageVendorGuid, document.TypeGuid); documents[document.Url] = value; return value; } public void Dispose() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) MethodDefinition entryPoint = module.EntryPoint; if (entryPoint != null) { SymWriter symWriter = writer; MetadataToken metadataToken = ((MemberReference)entryPoint).MetadataToken; symWriter.SetUserEntryPoint(((MetadataToken)(ref metadataToken)).ToInt32()); } writer.Close(); } } internal enum CustomMetadataType : byte { UsingInfo = 0, ForwardInfo = 1, IteratorScopes = 3, ForwardIterator = 4 } internal class CustomMetadataWriter : IDisposable { private readonly SymWriter sym_writer; private readonly MemoryStream stream; private readonly BinaryStreamWriter writer; private int count; private const byte version = 4; public CustomMetadataWriter(SymWriter sym_writer) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown this.sym_writer = sym_writer; stream = new MemoryStream(); writer = new BinaryStreamWriter((Stream)stream); writer.WriteByte((byte)4); writer.WriteByte((byte)0); writer.Align(4); } public void WriteUsingInfo(ImportDebugInformation import_info) { Write(CustomMetadataType.UsingInfo, delegate { writer.WriteUInt16((ushort)1); writer.WriteUInt16((ushort)import_info.Targets.Count); }); } public void WriteForwardInfo(MetadataToken import_parent) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) Write(CustomMetadataType.ForwardInfo, delegate { writer.WriteUInt32(((MetadataToken)(ref import_parent)).ToUInt32()); }); } public void WriteIteratorScopes(StateMachineScopeDebugInformation state_machine, MethodDebugInformation debug_info) { Write(CustomMetadataType.IteratorScopes, delegate { //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_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: 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) Collection<StateMachineScope> scopes = state_machine.Scopes; writer.WriteInt32(scopes.Count); Enumerator<StateMachineScope> enumerator = scopes.GetEnumerator(); try { while (enumerator.MoveNext()) { StateMachineScope current = enumerator.Current; InstructionOffset val = current.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = current.End; int num; if (!((InstructionOffset)(ref val)).IsEndOfMethod) { val = current.End; num = ((InstructionOffset)(ref val)).Offset; } else { num = debug_info.code_size; } int num2 = num; writer.WriteInt32(offset); writer.WriteInt32(num2 - 1); } } finally { ((IDisposable)enumerator).Dispose(); } }); } public void WriteForwardIterator(TypeReference type) { Write(CustomMetadataType.ForwardIterator, delegate { writer.WriteBytes(Encoding.Unicode.GetBytes(((MemberReference)type).Name)); }); } private void Write(CustomMetadataType type, Action write) { count++; writer.WriteByte((byte)4); writer.WriteByte((byte)type); writer.Align(4); int position = writer.Position; writer.WriteUInt32(0u); write(); writer.Align(4); int position2 = writer.Position; int num = position2 - position + 4; writer.Position = position; writer.WriteInt32(num); writer.Position = position2; } public void WriteCustomMetadata() { if (count != 0) { ((BinaryWriter)(object)writer).BaseStream.Position = 1L; writer.WriteByte((byte)count); ((BinaryWriter)(object)writer).Flush(); sym_writer.DefineCustomMetadata("MD2", stream.ToArray()); } } public void Dispose() { stream.Dispose(); } } public sealed class NativePdbReaderProvider : ISymbolReaderProvider { public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolReader)(object)new NativePdbReader(Disposable.Owned<Stream>((Stream)File.OpenRead(Mixin.GetPdbFileName(fileName)))); } public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); return (ISymbolReader)(object)new NativePdbReader(Disposable.NotOwned<Stream>(symbolStream)); } } public sealed class PdbReaderProvider : ISymbolReaderProvider { public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { //IL_0048: 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) Mixin.CheckModule(module); Mixin.CheckFileName(fileName); if (module.HasDebugHeader && Mixin.GetEmbeddedPortablePdbEntry(module.GetDebugHeader()) != null) { return new EmbeddedPortablePdbReaderProvider().GetSymbolReader(module, fileName); } if (!Mixin.IsPortablePdb(Mixin.GetPdbFileName(fileName))) { return new NativePdbReaderProvider().GetSymbolReader(module, fileName); } return new PortablePdbReaderProvider().GetSymbolReader(module, fileName); } public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); Mixin.CheckReadSeek(symbolStream); if (!Mixin.IsPortablePdb(symbolStream)) { return new NativePdbReaderProvider().GetSymbolReader(module, symbolStream); } return new PortablePdbReaderProvider().GetSymbolReader(module, symbolStream); } } public sealed class NativePdbWriterProvider : ISymbolWriterProvider { public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName) { Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolWriter)(object)new NativePdbWriter(module, CreateWriter(module, Mixin.GetPdbFileName(fileName))); } private static SymWriter CreateWriter(ModuleDefinition module, string pdb) { SymWriter symWriter = new SymWriter(); if (File.Exists(pdb)) { File.Delete(pdb); } symWriter.Initialize(new ModuleMetadata(module), pdb, fFullBuild: true); return symWriter; } public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream) { throw new NotImplementedException(); } } public sealed class PdbWriterProvider : ISymbolWriterProvider { public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckFileName(fileName); if (HasPortablePdbSymbols(module)) { return new PortablePdbWriterProvider().GetSymbolWriter(module, fileName); } return new NativePdbWriterProvider().GetSymbolWriter(module, fileName); } private static bool HasPortablePdbSymbols(ModuleDefinition module) { if (module.symbol_reader != null) { return module.symbol_reader is PortablePdbReader; } return false; } public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); Mixin.CheckReadSeek(symbolStream); if (HasPortablePdbSymbols(module)) { return new PortablePdbWriterProvider().GetSymbolWriter(module, symbolStream); } return new NativePdbWriterProvider().GetSymbolWriter(module, symbolStream); } } internal class SymDocumentWriter { private readonly ISymUnmanagedDocumentWriter m_unmanagedDocumentWriter; public SymDocumentWriter(ISymUnmanagedDocumentWriter unmanagedDocumentWriter) { m_unmanagedDocumentWriter = unmanagedDocumentWriter; } public ISymUnmanagedDocumentWriter GetUnmanaged() { return m_unmanagedDocumentWriter; } } internal class SymWriter { private static Guid s_symUnmangedWriterIID = new Guid("0b97726e-9e6d-4f05-9a26-424022093caa"); private static Guid s_CorSymWriter_SxS_ClassID = new Guid("108296c1-281e-11d3-bd22-0000f80849bd"); private readonly ISymUnmanagedWriter2 m_writer; private readonly Collection<ISymUnmanagedDocumentWriter> documents; [DllImport("ole32.dll")] private static extern int CoCreateInstance([In] ref Guid rclsid, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] uint dwClsContext, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppv); public SymWriter() { CoCreateInstance(ref s_CorSymWriter_SxS_ClassID, null, 1u, ref s_symUnmangedWriterIID, out var ppv); m_writer = (ISymUnmanagedWriter2)ppv; documents = new Collection<ISymUnmanagedDocumentWriter>(); } public byte[] GetDebugInfo(out ImageDebugDirectory idd) { m_writer.GetDebugInfo(out idd, 0, out var pcData, null); byte[] array = new byte[pcData]; m_writer.GetDebugInfo(out idd, pcData, out pcData, array); return array; } public void DefineLocalVariable2(string name, VariableAttributes attributes, int sigToken, int addr1, int addr2, int addr3, int startOffset, int endOffset) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected I4, but got Unknown m_writer.DefineLocalVariable2(name, (int)attributes, sigToken, 1, addr1, addr2, addr3, startOffset, endOffset); } public void DefineConstant2(string name, object value, int sigToken) { if (value == null) { m_writer.DefineConstant2(name, 0, sigToken); } else { m_writer.DefineConstant2(name, value, sigToken); } } public void Close() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) m_writer.Close(); Marshal.ReleaseComObject(m_writer); Enumerator<ISymUnmanagedDocumentWriter> enumerator = documents.GetEnumerator(); try { while (enumerator.MoveNext()) { Marshal.ReleaseComObject(enumerator.Current); } } finally { ((IDisposable)enumerator).Dispose(); } } public void CloseMethod() { m_writer.CloseMethod(); } public void CloseNamespace() { m_writer.CloseNamespace(); } public void CloseScope(int endOffset) { m_writer.CloseScope(endOffset); } public SymDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) { m_writer.DefineDocument(url, ref language, ref languageVendor, ref documentType, out var pRetVal); documents.Add(pRetVal); return new SymDocumentWriter(pRetVal); } public void DefineSequencePoints(SymDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) { m_writer.DefineSequencePoints(document.GetUnmanaged(), offsets.Length, offsets, lines, columns, endLines, endColumns); } public void Initialize(object emitter, string filename, bool fFullBuild) { m_writer.Initialize(emitter, filename, null, fFullBuild); } public void SetUserEntryPoint(int methodToken) { m_writer.SetUserEntryPoint(methodToken); } public void OpenMethod(int methodToken) { m_writer.OpenMethod(methodToken); } public void OpenNamespace(string name) { m_writer.OpenNamespace(name); } public int OpenScope(int startOffset) { m_writer.OpenScope(startOffset, out var pRetVal); return pRetVal; } public void UsingNamespace(string fullName) { m_writer.UsingNamespace(fullName); } public void DefineCustomMetadata(string name, byte[] metadata) { GCHandle gCHandle = GCHandle.Alloc(metadata, GCHandleType.Pinned); m_writer.SetSymAttribute(0u, name, (uint)metadata.Length, gCHandle.AddrOfPinnedObject()); gCHandle.Free(); } } } namespace Microsoft.Cci { public interface ILocalScope { uint Offset { get; } uint Length { get; } } public interface INamespaceScope { IEnumerable<IUsedNamespace> UsedNamespaces { get; } } public interface IUsedNamespace { IName Alias { get; } IName NamespaceName { get; } } public interface IName { int UniqueKey { get; } int UniqueKeyIgnoringCase { get; } string Value { get; } } internal sealed class PdbIteratorScope : ILocalScope { private uint offset; private uint length; public uint Offset => offset; public uint Length => length; internal PdbIteratorScope(uint offset, uint length) { this.offset = offset; this.length = length; } } } namespace Microsoft.Cci.Pdb { internal class BitAccess { private byte[] buffer; private int offset; internal byte[] Buffer => buffer; internal int Position { get { return offset; } set { offset = value; } } internal BitAccess(int capacity) { buffer = new byte[capacity]; } internal void FillBuffer(Stream stream, int capacity) { MinCapacity(capacity); stream.Read(buffer, 0, capacity); offset = 0; } internal void Append(Stream stream, int count) { int num = offset + count; if (buffer.Length < num) { byte[] destinationArray = new byte[num]; Array.Copy(buffer, destinationArray, buffer.Length); buffer = destinationArray; } stream.Read(buffer, offset, count); offset += count; } internal void MinCapacity(int capacity) { if (buffer.Length < capacity) { buffer = new byte[capacity]; } offset = 0; } internal void Align(int alignment) { while (offset % alignment != 0) { offset++; } } internal void ReadInt16(out short value) { value = (short)((buffer[offset] & 0xFF) | (buffer[offset + 1] << 8)); offset += 2; } internal void ReadInt8(out sbyte value) { value = (sbyte)buffer[offset]; offset++; } internal void ReadInt32(out int value) { value = (buffer[offset] & 0xFF) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24); offset += 4; } internal void ReadInt64(out long value) { value = ((long)buffer[offset] & 0xFFL) | (long)((ulong)buffer[offset + 1] << 8) | (long)((ulong)buffer[offset + 2] << 16) | (long)((ulong)buffer[offset + 3] << 24) | (long)((ulong)buffer[offset + 4] << 32) | (long)((ulong)buffer[offset + 5] << 40) | (long)((ulong)buffer[offset + 6] << 48) | (long)((ulong)buffer[offset + 7] << 56); offset += 8; } internal void ReadUInt16(out ushort value) { value = (ushort)((buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8)); offset += 2; } internal void ReadUInt8(out byte value) { value = (byte)(buffer[offset] & 0xFFu); offset++; } internal void ReadUInt32(out uint value) { value = (buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8) | (uint)(buffer[offset + 2] << 16) | (uint)(buffer[offset + 3] << 24); offset += 4; } internal void ReadUInt64(out ulong value) { value = ((ulong)buffer[offset] & 0xFFuL) | ((ulong)buffer[offset + 1] << 8) | ((ulong)buffer[offset + 2] << 16) | ((ulong)buffer[offset + 3] << 24) | ((ulong)buffer[offset + 4] << 32) | ((ulong)buffer[offset + 5] << 40) | ((ulong)buffer[offset + 6] << 48) | ((ulong)buffer[offset + 7] << 56); offset += 8; } internal void ReadInt32(int[] values) { for (int i = 0; i < values.Length; i++) { ReadInt32(out values[i]); } } internal void ReadUInt32(uint[] values) { for (int i = 0; i < values.Length; i++) { ReadUInt32(out values[i]); } } internal void ReadBytes(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { bytes[i] = buffer[offset++]; } } internal float ReadFloat() { float result = BitConverter.ToSingle(buffer, offset); offset += 4; return result; } internal double ReadDouble() { double result = BitConverter.ToDouble(buffer, offset); offset += 8; return result; } internal decimal ReadDecimal() { int[] array = new int[4]; ReadInt32(array); return new decimal(array[2], array[3], array[1], array[0] < 0, (byte)((array[0] & 0xFF0000) >> 16)); } internal void ReadBString(out string value) { ReadUInt16(out var value2); value = Encoding.UTF8.GetString(buffer, offset, value2); offset += value2; } internal string ReadBString(int len) { string @string = Encoding.UTF8.GetString(buffer, offset, len); offset += len; return @string; } internal void ReadCString(out string value) { int i; for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++) { } value = Encoding.UTF8.GetString(buffer, offset, i); offset += i + 1; } internal void SkipCString(out string value) { int i; for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++) { } offset += i + 1; value = null; } internal void ReadGuid(out Guid guid) { ReadUInt32(out var value); ReadUInt16(out var value2); ReadUInt16(out var value3); ReadUInt8(out var value4); ReadUInt8(out var value5); ReadUInt8(out var value6); ReadUInt8(out var value7); ReadUInt8(out var value8); ReadUInt8(out var value9); ReadUInt8(out var value10); ReadUInt8(out var value11); guid = new Guid(value, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11); } internal string ReadString() { int i; for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i += 2) { } string @string = Encoding.Unicode.GetString(buffer, offset, i); offset += i + 2; return @string; } } internal struct BitSet { private int size; private uint[] words; internal bool IsEmpty => size == 0; internal BitSet(BitAccess bits) { bits.ReadInt32(out size); words = new uint[size]; bits.ReadUInt32(words); } internal bool IsSet(int index) { int num = index / 32; if (num >= size) { return false; } return (words[num] & GetBit(index)) != 0; } private static uint GetBit(int index) { return (uint)(1 << index % 32); } } internal struct FLOAT10 { internal byte Data_0; internal byte Data_1; internal byte Data_2; internal byte Data_3; internal byte Data_4; internal byte Data_5; internal byte Data_6; internal byte Data_7; internal byte Data_8; internal byte Data_9; } internal enum CV_SIGNATURE { C6 = 0, C7 = 1, C11 = 2, C13 = 4, RESERVERD = 5 } internal enum CV_prmode { CV_TM_DIRECT = 0, CV_TM_NPTR32 = 4, CV_TM_NPTR64 = 6, CV_TM_NPTR128 = 7 } internal enum CV_type { CV_SPECIAL = 0, CV_SIGNED = 1, CV_UNSIGNED = 2, CV_BOOLEAN = 3, CV_REAL = 4, CV_COMPLEX = 5, CV_SPECIAL2 = 6, CV_INT = 7, CV_CVRESERVED = 15 } internal enum CV_special { CV_SP_NOTYPE, CV_SP_ABS, CV_SP_SEGMENT, CV_SP_VOID, CV_SP_CURRENCY, CV_SP_NBASICSTR, CV_SP_FBASICSTR, CV_SP_NOTTRANS, CV_SP_HRESULT } internal enum CV_special2 { CV_S2_BIT, CV_S2_PASCHAR } internal enum CV_integral { CV_IN_1BYTE, CV_IN_2BYTE, CV_IN_4BYTE, CV_IN_8BYTE, CV_IN_16BYTE } internal enum CV_real { CV_RC_REAL32, CV_RC_REAL64, CV_RC_REAL80, CV_RC_REAL128 } internal enum CV_int { CV_RI_CHAR = 0, CV_RI_INT1 = 0, CV_RI_WCHAR = 1, CV_RI_UINT1 = 1, CV_RI_INT2 = 2, CV_RI_UINT2 = 3, CV_RI_INT4 = 4, CV_RI_UINT4 = 5, CV_RI_INT8 = 6, CV_RI_UINT8 = 7, CV_RI_INT16 = 8, CV_RI_UINT16 = 9 } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct CV_PRIMITIVE_TYPE { private const uint CV_MMASK = 1792u; private const uint CV_TMASK = 240u; private const uint CV_SMASK = 15u; private const int CV_MSHIFT = 8; private const int CV_TSHIFT = 4; private const int CV_SSHIFT = 0; private const uint CV_FIRST_NONPRIM = 4096u; } internal enum TYPE_ENUM { T_NOTYPE = 0, T_ABS = 1, T_SEGMENT = 2, T_VOID = 3, T_HRESULT = 8, T_32PHRESULT = 1032, T_64PHRESULT = 1544, T_PVOID = 259, T_PFVOID = 515, T_PHVOID = 771, T_32PVOID = 1027, T_64PVOID = 1539, T_CURRENCY = 4, T_NOTTRANS = 7, T_BIT = 96, T_PASCHAR = 97, T_CHAR = 16, T_32PCHAR = 1040, T_64PCHAR = 1552, T_UCHAR = 32, T_32PUCHAR = 1056, T_64PUCHAR = 1568, T_RCHAR = 112, T_32PRCHAR = 1136, T_64PRCHAR = 1648, T_WCHAR = 113, T_32PWCHAR = 1137, T_64PWCHAR = 1649, T_INT1 = 104, T_32PINT1 = 1128, T_64PINT1 = 1640, T_UINT1 = 105, T_32PUINT1 = 1129, T_64PUINT1 = 1641, T_SHORT = 17, T_32PSHORT = 1041, T_64PSHORT = 1553, T_USHORT = 33, T_32PUSHORT = 1057, T_64PUSHORT = 1569, T_INT2 = 114, T_32PINT2 = 1138, T_64PINT2 = 1650, T_UINT2 = 115, T_32PUINT2 = 1139, T_64PUINT2 = 1651, T_LONG = 18, T_ULONG = 34, T_32PLONG = 1042, T_32PULONG = 1058, T_64PLONG = 1554, T_64PULONG = 1570, T_INT4 = 116, T_32PINT4 = 1140, T_64PINT4 = 1652, T_UINT4 = 117, T_32PUINT4 = 1141, T_64PUINT4 = 1653, T_QUAD = 19, T_32PQUAD = 1043, T_64PQUAD = 1555, T_UQUAD = 35, T_32PUQUAD = 1059, T_64PUQUAD = 1571, T_INT8 = 118, T_32PINT8 = 1142, T_64PINT8 = 1654, T_UINT8 = 119, T_32PUINT8 = 1143, T_64PUINT8 = 1655, T_OCT = 20, T_32POCT = 1044, T_64POCT = 1556, T_UOCT = 36, T_32PUOCT = 1060, T_64PUOCT = 1572, T_INT16 = 120, T_32PINT16 = 1144, T_64PINT16 = 1656, T_UINT16 = 121, T_32PUINT16 = 1145, T_64PUINT16 = 1657, T_REAL32 = 64, T_32PREAL32 = 1088, T_64PREAL32 = 1600, T_REAL64 = 65, T_32PREAL64 = 1089, T_64PREAL64 = 1601, T_REAL80 = 66, T_32PREAL80 = 1090, T_64PREAL80 = 1602, T_REAL128 = 67, T_32PREAL128 = 1091, T_64PREAL128 = 1603, T_CPLX32 = 80, T_32PCPLX32 = 1104, T_64PCPLX32 = 1616, T_CPLX64 = 81, T_32PCPLX64 = 1105, T_64PCPLX64 = 1617, T_CPLX80 = 82, T_32PCPLX80 = 1106, T_64PCPLX80 = 1618, T_CPLX128 = 83, T_32PCPLX128 = 1107, T_64PCPLX128 = 1619, T_BOOL08 = 48, T_32PBOOL08 = 1072, T_64PBOOL08 = 1584, T_BOOL16 = 49, T_32PBOOL16 = 1073, T_64PBOOL16 = 1585, T_BOOL32 = 50, T_32PBOOL32 = 1074, T_64PBOOL32 = 1586, T_BOOL64 = 51, T_32PBOOL64 = 1075, T_64PBOOL64 = 1587 } internal enum LEAF { LF_VTSHAPE = 10, LF_COBOL1 = 12, LF_LABEL = 14, LF_NULL = 15, LF_NOTTRAN = 16, LF_ENDPRECOMP = 20, LF_TYPESERVER_ST = 22, LF_LIST = 515, LF_REFSYM = 524, LF_ENUMERATE_ST = 1027, LF_TI16_MAX = 4096, LF_MODIFIER = 4097, LF_POINTER = 4098, LF_ARRAY_ST = 4099, LF_CLASS_ST = 4100, LF_STRUCTURE_ST = 4101, LF_UNION_ST = 4102, LF_ENUM_ST = 4103, LF_PROCEDURE = 4104, LF_MFUNCTION = 4105, LF_COBOL0 = 4106, LF_BARRAY = 4107, LF_DIMARRAY_ST = 4108, LF_VFTPATH = 4109, LF_PRECOMP_ST = 4110, LF_OEM = 4111, LF_ALIAS_ST = 4112, LF_OEM2 = 4113, LF_SKIP = 4608, LF_ARGLIST = 4609, LF_DEFARG_ST = 4610, LF_FIELDLIST = 4611, LF_DERIVED = 4612, LF_BITFIELD = 4613, LF_METHODLIST = 4614, LF_DIMCONU = 4615, LF_DIMCONLU = 4616, LF_DIMVARU = 4617, LF_DIMVARLU = 4618, LF_BCLASS = 5120, LF_VBCLASS = 5121, LF_IVBCLASS = 5122, LF_FRIENDFCN_ST = 5123, LF_INDEX = 5124, LF_MEMBER_ST = 5125, LF_STMEMBER_ST = 5126, LF_METHOD_ST = 5127, LF_NESTTYPE_ST = 5128, LF_VFUNCTAB = 5129, LF_FRIENDCLS = 5130, LF_ONEMETHOD_ST = 5131, LF_VFUNCOFF = 5132, LF_NESTTYPEEX_ST = 5133, LF_MEMBERMODIFY_ST = 5134, LF_MANAGED_ST = 5135, LF_ST_MAX = 5376, LF_TYPESERVER = 5377, LF_ENUMERATE = 5378, LF_ARRAY = 5379, LF_CLASS = 5380, LF_STRUCTURE = 5381, LF_UNION = 5382, LF_ENUM = 5383, LF_DIMARRAY = 5384, LF_PRECOMP = 5385, LF_ALIAS = 5386, LF_DEFARG = 5387, LF_FRIENDFCN = 5388, LF_MEMBER = 5389, LF_STMEMBER = 5390, LF_METHOD = 5391, LF_NESTTYPE = 5392, LF_ONEMETHOD = 5393, LF_NESTTYPEEX = 5394, LF_MEMBERMODIFY = 5395, LF_MANAGED = 5396, LF_TYPESERVER2 = 5397, LF_NUMERIC = 32768, LF_CHAR = 32768, LF_SHORT = 32769, LF_USHORT = 32770, LF_LONG = 32771, LF_ULONG = 32772, LF_REAL32 = 32773, LF_REAL64 = 32774, LF_REAL80 = 32775, LF_REAL128 = 32776, LF_QUADWORD = 32777, LF_UQUADWORD = 32778, LF_COMPLEX32 = 32780, LF_COMPLEX64 = 32781, LF_COMPLEX80 = 32782, LF_COMPLEX128 = 32783, LF_VARSTRING = 32784, LF_OCTWORD = 32791, LF_UOCTWORD = 32792, LF_DECIMAL = 32793, LF_DATE = 32794, LF_UTF8STRING = 32795, LF_PAD0 = 240, LF_PAD1 = 241, LF_PAD2 = 242, LF_PAD3 = 243, LF_PAD4 = 244, LF_PAD5 = 245, LF_PAD6 = 246, LF_PAD7 = 247, LF_PAD8 = 248, LF_PAD9 = 249, LF_PAD10 = 250, LF_PAD11 = 251, LF_PAD12 = 252, LF_PAD13 = 253, LF_PAD14 = 254, LF_PAD15 = 255 } internal enum CV_ptrtype { CV_PTR_BASE_SEG = 3, CV_PTR_BASE_VAL = 4, CV_PTR_BASE_SEGVAL = 5, CV_PTR_BASE_ADDR = 6, CV_PTR_BASE_SEGADDR = 7, CV_PTR_BASE_TYPE = 8, CV_PTR_BASE_SELF = 9, CV_PTR_NEAR32 = 10, CV_PTR_64 = 12, CV_PTR_UNUSEDPTR = 13 } internal enum CV_ptrmode { CV_PTR_MODE_PTR, CV_PTR_MODE_REF, CV_PTR_MODE_PMEM, CV_PTR_MODE_PMFUNC, CV_PTR_MODE_RESERVED } internal enum CV_pmtype { CV_PMTYPE_Undef, CV_PMTYPE_D_Single, CV_PMTYPE_D_Multiple, CV_PMTYPE_D_Virtual, CV_PMTYPE_D_General, CV_PMTYPE_F_Single, CV_PMTYPE_F_Multiple, CV_PMTYPE_F_Virtual, CV_PMTYPE_F_General } internal enum CV_methodprop { CV_MTvanilla, CV_MTvirtual, CV_MTstatic, CV_MTfriend, CV_MTintro, CV_MTpurevirt, CV_MTpureintro } internal enum CV_VTS_desc { CV_VTS_near, CV_VTS_far, CV_VTS_thin, CV_VTS_outer, CV_VTS_meta, CV_VTS_near32, CV_VTS_far32, CV_VTS_unused } internal enum CV_LABEL_TYPE { CV_LABEL_NEAR = 0, CV_LABEL_FAR = 4 } [Flags] internal enum CV_modifier : ushort { MOD_const = 1, MOD_volatile = 2, MOD_unaligned = 4 } [Flags] internal enum CV_prop : ushort { packed = 1, ctor = 2, ovlops = 4, isnested = 8, cnested = 0x10, opassign = 0x20, opcast = 0x40, fwdref = 0x80, scoped = 0x100 } [Flags] internal enum CV_fldattr { access = 3, mprop = 0x1C, pseudo = 0x20, noinherit = 0x40, noconstruct = 0x80, compgenx = 0x100 } internal struct TYPTYPE { internal ushort len; internal ushort leaf; } internal struct CV_PDMR32_NVVFCN { internal int mdisp; } internal struct CV_PDMR32_VBASE { internal int mdisp; internal int pdisp; internal int vdisp; } internal struct CV_PMFR32_NVSA { internal uint off; } internal struct CV_PMFR32_NVMA { internal uint off; internal int disp; } internal struct CV_PMFR32_VBASE { internal uint off; internal int mdisp; internal int pdisp; internal int vdisp; } internal struct LeafModifier { internal uint type; internal CV_modifier attr; } [Flags] internal enum LeafPointerAttr : uint { ptrtype = 0x1Fu, ptrmode = 0xE0u, isflat32 = 0x100u, isvolatile = 0x200u, isconst = 0x400u, isunaligned = 0x800u, isrestrict = 0x1000u } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct LeafPointer { internal struct LeafPointerBody { internal uint utype; internal LeafPointerAttr attr; } } internal struct LeafArray { internal uint elemtype; internal uint idxtype; internal byte[] data; internal string name; } internal struct LeafClass { internal ushort count; internal ushort property; internal uint field; internal uint derived; internal uint vshape; internal byte[] data; internal string name; } internal struct LeafUnion { internal ushort count; internal ushort property; internal uint field; internal byte[] data; internal string name; } internal struct LeafAlias { internal uint utype; internal string name; } internal struct LeafManaged { internal string name; } internal struct LeafEnum { internal ushort count; internal ushort property; internal uint utype; internal uint field; internal string name; } internal struct LeafProc { internal uint rvtype; internal byte calltype; internal byte reserved; internal ushort parmcount; internal uint arglist; } internal struct LeafMFunc { internal uint rvtype; internal uint classtype; internal uint thistype; internal byte calltype; internal byte reserved; internal ushort parmcount; internal uint arglist; internal int thisadjust; } internal struct LeafVTShape { internal ushort count; internal byte[] desc; } internal struct LeafCobol0 { internal uint type; internal byte[] data; } internal struct LeafCobol1 { internal byte[] data; } internal struct LeafBArray { internal uint utype; } internal struct LeafLabel { internal ushort mode; } internal struct LeafDimArray { internal uint utype; internal uint diminfo; internal string name; } internal struct LeafVFTPath { internal uint count; internal uint[] bases; } internal struct LeafPreComp { internal uint start; internal uint count; internal uint signature; internal string name; } internal struct LeafEndPreComp { internal uint signature; } internal struct LeafOEM { internal ushort cvOEM; internal ushort recOEM; internal uint count; internal uint[] index; } internal enum OEM_ID { OEM_MS_FORTRAN90 = 61584, OEM_ODI = 16, OEM_THOMSON_SOFTWARE = 21587, OEM_ODI_REC_BASELIST = 0 } internal struct LeafOEM2 { internal Guid idOem; internal uint count; internal uint[] index; } internal struct LeafTypeServer { internal uint signature; internal uint age; internal string name; } internal struct LeafTypeServer2 { internal Guid sig70; internal uint age; internal string name; } internal struct LeafSkip { internal uint type; internal byte[] data; } internal struct LeafArgList { internal uint count; internal uint[] arg; } internal struct LeafDerived { internal uint count; internal uint[] drvdcls; } internal struct LeafDefArg { internal uint type; internal byte[] expr; } internal struct LeafList { internal byte[] data; } internal struct LeafFieldList { internal char[] data; } internal struct mlMethod { internal ushort attr; internal ushort pad0; internal uint index; internal uint[] vbaseoff; } internal struct LeafMethodList { internal byte[] mList; } internal struct LeafBitfield { internal uint type; internal byte length; internal byte position; } internal struct LeafDimCon { internal uint typ; internal ushort rank; internal byte[] dim; } internal struct LeafDimVar { internal uint rank; internal uint typ; internal uint[] dim; } internal struct LeafRefSym { internal byte[] Sym; } internal struct LeafChar { internal sbyte val; } internal struct LeafShort { internal short val; } internal struct LeafUShort { internal ushort val; } internal struct LeafLong { internal int val; } internal struct LeafULong { internal uint val; } internal struct LeafQuad { internal long val; } internal struct LeafUQuad { internal ulong val; } internal struct LeafOct { internal ulong val0; internal ulong val1; } internal struct LeafUOct { internal ulong val0; internal ulong val1; } internal struct LeafReal32 { internal float val; } internal struct LeafReal64 { internal double val; } internal struct LeafReal80 { internal FLOAT10 val; } internal struct LeafReal128 { internal ulong val0; internal ulong val1; } internal struct LeafCmplx32 { internal float val_real; internal float val_imag; } internal struct LeafCmplx64 { internal double val_real; internal double val_imag; } internal struct LeafCmplx80 { internal FLOAT10 val_real; internal FLOAT10 val_imag; } internal struct LeafCmplx128 { internal ulong val0_real; internal ulong val1_real; internal ulong val0_imag; internal ulong val1_imag; } internal struct LeafVarString { internal ushort len; internal byte[] value; } internal struct LeafIndex { internal ushort pad0; internal uint index; } internal struct LeafBClass { internal ushort attr; internal uint index; internal byte[] offset; } internal struct LeafVBClass { internal ushort attr; internal uint index; internal uint vbptr; internal byte[] vbpoff; } internal struct LeafFriendCls { internal ushort pad0; internal uint index; } internal struct LeafFriendFcn { internal ushort pad0; internal uint index; internal string name; } internal struct LeafMember { internal ushort attr; internal uint index; internal byte[] offset; internal string name; } internal struct LeafSTMember { internal ushort attr; internal uint index; internal string name; } internal struct LeafVFuncTab { internal ushort pad0; internal uint type; } internal struct LeafVFuncOff { internal ushort pad0; internal uint type; internal int offset; } internal struct LeafMethod { internal ushort count; internal uint mList; internal string name; } internal struct LeafOneMethod { internal ushort attr; internal uint index; internal uint[] vbaseoff; internal string name; } internal struct LeafEnumerate { internal ushort attr; internal byte[] value; internal string name; } internal struct LeafNestType { internal ushort pad0; internal uint index; internal string name; } internal struct LeafNestTypeEx { internal ushort attr; internal uint index; internal string name; } internal struct LeafMemberModify { internal ushort
UMM/Mods/Runtime Unity Editor/Mono.Cecil.Rocks.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using Mono.Cecil.Cil; using Mono.Cecil.PE; using Mono.Collections.Generic; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.10.4.0")] [assembly: AssemblyInformationalVersion("0.10.4.0")] [assembly: AssemblyTitle("Mono.Cecil.Rocks")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("0.10.4.0")] namespace Mono.Cecil.Rocks; public class DocCommentId { private StringBuilder id; private DocCommentId() { id = new StringBuilder(); } private void WriteField(FieldDefinition field) { WriteDefinition('F', (IMemberDefinition)(object)field); } private void WriteEvent(EventDefinition @event) { WriteDefinition('E', (IMemberDefinition)(object)@event); } private void WriteType(TypeDefinition type) { id.Append('T').Append(':'); WriteTypeFullName((TypeReference)(object)type); } private void WriteMethod(MethodDefinition method) { WriteDefinition('M', (IMemberDefinition)(object)method); if (((MethodReference)method).HasGenericParameters) { id.Append('`').Append('`'); id.Append(((MethodReference)method).GenericParameters.Count); } if (((MethodReference)method).HasParameters) { WriteParameters((IList<ParameterDefinition>)((MethodReference)method).Parameters); } if (IsConversionOperator(method)) { WriteReturnType(method); } } private static bool IsConversionOperator(MethodDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (self.IsSpecialName) { if (!(((MemberReference)self).Name == "op_Explicit")) { return ((MemberReference)self).Name == "op_Implicit"; } return true; } return false; } private void WriteReturnType(MethodDefinition method) { id.Append('~'); WriteTypeSignature(((MethodReference)method).ReturnType); } private void WriteProperty(PropertyDefinition property) { WriteDefinition('P', (IMemberDefinition)(object)property); if (property.HasParameters) { WriteParameters((IList<ParameterDefinition>)((PropertyReference)property).Parameters); } } private void WriteParameters(IList<ParameterDefinition> parameters) { id.Append('('); WriteList(parameters, delegate(ParameterDefinition p) { WriteTypeSignature(((ParameterReference)p).ParameterType); }); id.Append(')'); } private void WriteTypeSignature(TypeReference type) { //IL_0001: 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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected I4, but got Unknown //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_002c: 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_004d: Expected I4, but got Unknown //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Expected O, but got Unknown //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Expected O, but got Unknown MetadataType metadataType = type.MetadataType; switch (metadataType - 15) { default: switch (metadataType - 27) { case 0: WriteFunctionPointerTypeSignature((FunctionPointerType)type); return; case 3: id.Append('`').Append('`'); id.Append(((GenericParameter)type).Position); return; case 5: WriteModiferTypeSignature((IModifierType)(OptionalModifierType)type, '!'); return; case 4: WriteModiferTypeSignature((IModifierType)(RequiredModifierType)type, '|'); return; } break; case 5: WriteArrayTypeSignature((ArrayType)type); return; case 1: WriteTypeSignature(((TypeSpecification)(ByReferenceType)type).ElementType); id.Append('@'); return; case 6: WriteGenericInstanceTypeSignature((GenericInstanceType)type); return; case 4: id.Append('`'); id.Append(((GenericParameter)type).Position); return; case 0: WriteTypeSignature(((TypeSpecification)(PointerType)type).ElementType); id.Append('*'); return; case 2: case 3: break; } WriteTypeFullName(type); } private void WriteGenericInstanceTypeSignature(GenericInstanceType type) { if (Mixin.IsTypeSpecification(((TypeSpecification)type).ElementType)) { throw new NotSupportedException(); } WriteTypeFullName(((TypeSpecification)type).ElementType, stripGenericArity: true); id.Append('{'); WriteList((IList<TypeReference>)type.GenericArguments, WriteTypeSignature); id.Append('}'); } private void WriteList<T>(IList<T> list, Action<T> action) { for (int i = 0; i < list.Count; i++) { if (i > 0) { id.Append(','); } action(list[i]); } } private void WriteModiferTypeSignature(IModifierType type, char id) { WriteTypeSignature(type.ElementType); this.id.Append(id); WriteTypeSignature(type.ModifierType); } private void WriteFunctionPointerTypeSignature(FunctionPointerType type) { id.Append("=FUNC:"); WriteTypeSignature(type.ReturnType); if (type.HasParameters) { WriteParameters((IList<ParameterDefinition>)type.Parameters); } } private void WriteArrayTypeSignature(ArrayType type) { WriteTypeSignature(((TypeSpecification)type).ElementType); if (type.IsVector) { id.Append("[]"); return; } id.Append("["); WriteList((IList<ArrayDimension>)type.Dimensions, delegate(ArrayDimension dimension) { if (((ArrayDimension)(ref dimension)).LowerBound.HasValue) { id.Append(((ArrayDimension)(ref dimension)).LowerBound.Value); } id.Append(':'); if (((ArrayDimension)(ref dimension)).UpperBound.HasValue) { id.Append(((ArrayDimension)(ref dimension)).UpperBound.Value - (((ArrayDimension)(ref dimension)).LowerBound.GetValueOrDefault() + 1)); } }); id.Append("]"); } private void WriteDefinition(char id, IMemberDefinition member) { this.id.Append(id).Append(':'); WriteTypeFullName((TypeReference)(object)member.DeclaringType); this.id.Append('.'); WriteItemName(member.Name); } private void WriteTypeFullName(TypeReference type, bool stripGenericArity = false) { if (((MemberReference)type).DeclaringType != null) { WriteTypeFullName(((MemberReference)type).DeclaringType); id.Append('.'); } if (!string.IsNullOrEmpty(type.Namespace)) { id.Append(type.Namespace); id.Append('.'); } string text = ((MemberReference)type).Name; if (stripGenericArity) { int num = text.LastIndexOf('`'); if (num > 0) { text = text.Substring(0, num); } } id.Append(text); } private void WriteItemName(string name) { id.Append(name.Replace('.', '#').Replace('<', '{').Replace('>', '}')); } public override string ToString() { return id.ToString(); } public static string GetDocCommentId(IMemberDefinition member) { //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) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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: Invalid comparison between Unknown and I4 //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Invalid comparison between Unknown and I4 //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Invalid comparison between Unknown and I4 //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown if (member == null) { throw new ArgumentNullException("member"); } DocCommentId docCommentId = new DocCommentId(); MetadataToken metadataToken = ((IMetadataTokenProvider)member).MetadataToken; TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType; if ((int)tokenType <= 67108864) { if ((int)tokenType != 33554432) { if ((int)tokenType != 67108864) { goto IL_009d; } docCommentId.WriteField((FieldDefinition)member); } else { docCommentId.WriteType((TypeDefinition)member); } } else if ((int)tokenType != 100663296) { if ((int)tokenType != 335544320) { if ((int)tokenType != 385875968) { goto IL_009d; } docCommentId.WriteProperty((PropertyDefinition)member); } else { docCommentId.WriteEvent((EventDefinition)member); } } else { docCommentId.WriteMethod((MethodDefinition)member); } return docCommentId.ToString(); IL_009d: throw new NotSupportedException(member.FullName); } } internal static class Functional { public static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f) { Func<A, R> g = null; g = f((A a) => g(a)); return g; } public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource element) { if (source == null) { throw new ArgumentNullException("source"); } return PrependIterator(source, element); } private static IEnumerable<TSource> PrependIterator<TSource>(IEnumerable<TSource> source, TSource element) { yield return element; foreach (TSource item in source) { yield return item; } } } public interface IILVisitor { void OnInlineNone(OpCode opcode); void OnInlineSByte(OpCode opcode, sbyte value); void OnInlineByte(OpCode opcode, byte value); void OnInlineInt32(OpCode opcode, int value); void OnInlineInt64(OpCode opcode, long value); void OnInlineSingle(OpCode opcode, float value); void OnInlineDouble(OpCode opcode, double value); void OnInlineString(OpCode opcode, string value); void OnInlineBranch(OpCode opcode, int offset); void OnInlineSwitch(OpCode opcode, int[] offsets); void OnInlineVariable(OpCode opcode, VariableDefinition variable); void OnInlineArgument(OpCode opcode, ParameterDefinition parameter); void OnInlineSignature(OpCode opcode, CallSite callSite); void OnInlineType(OpCode opcode, TypeReference type); void OnInlineField(OpCode opcode, FieldReference field); void OnInlineMethod(OpCode opcode, MethodReference method); } public static class ILParser { private class ParseContext { public CodeReader Code { get; set; } public int Position { get; set; } public MetadataReader Metadata { get; set; } public Collection<VariableDefinition> Variables { get; set; } public IILVisitor Visitor { get; set; } } public static void Parse(MethodDefinition method, IILVisitor visitor) { if (method == null) { throw new ArgumentNullException("method"); } if (visitor == null) { throw new ArgumentNullException("visitor"); } if (!method.HasBody || !((MemberReference)method).HasImage) { throw new ArgumentException(); } ((MemberReference)method).Module.Read<MethodDefinition, bool>(method, (Func<MethodDefinition, MetadataReader, bool>)delegate(MethodDefinition m, MetadataReader _) { ParseMethod(m, visitor); return true; }); } private static void ParseMethod(MethodDefinition method, IILVisitor visitor) { ParseContext parseContext = CreateContext(method, visitor); CodeReader code = parseContext.Code; byte b = ((BinaryReader)(object)code).ReadByte(); switch (b & 3) { case 2: ParseCode(b >> 2, parseContext); break; case 3: ((BinaryStreamReader)code).Advance(-1); ParseFatMethod(parseContext); break; default: throw new NotSupportedException(); } code.MoveBackTo(parseContext.Position); } private static ParseContext CreateContext(MethodDefinition method, IILVisitor visitor) { CodeReader val = ((MemberReference)method).Module.Read<MethodDefinition, CodeReader>(method, (Func<MethodDefinition, MetadataReader, CodeReader>)((MethodDefinition _, MetadataReader reader) => reader.code)); int position = val.MoveTo(method); return new ParseContext { Code = val, Position = position, Metadata = val.reader, Visitor = visitor }; } private static void ParseFatMethod(ParseContext context) { //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) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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) CodeReader code = context.Code; ((BinaryStreamReader)code).Advance(4); int code_size = ((BinaryReader)(object)code).ReadInt32(); MetadataToken val = code.ReadToken(); if (val != MetadataToken.Zero) { context.Variables = (Collection<VariableDefinition>)(object)code.ReadVariables(val); } ParseCode(code_size, context); } private static void ParseCode(int code_size, ParseContext context) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Expected I4, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Invalid comparison between Unknown and I4 //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Invalid comparison between Unknown and I4 //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Invalid comparison between Unknown and I4 //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_02a4: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Invalid comparison between Unknown and I4 //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Invalid comparison between Unknown and I4 //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Expected O, but got Unknown //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Invalid comparison between Unknown and I4 //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Invalid comparison between Unknown and I4 //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Expected O, but got Unknown //IL_0299: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Invalid comparison between Unknown and I4 //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_0280: Invalid comparison between Unknown and I4 //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Expected O, but got Unknown //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_0312: Unknown result type (might be due to invalid IL or missing references) CodeReader code = context.Code; MetadataReader metadata = context.Metadata; IILVisitor visitor = context.Visitor; int num = ((BinaryStreamReader)code).Position + code_size; while (((BinaryStreamReader)code).Position < num) { byte b = ((BinaryReader)(object)code).ReadByte(); OpCode val = ((b != 254) ? OpCodes.OneByteOpCode[b] : OpCodes.TwoBytesOpCode[((BinaryReader)(object)code).ReadByte()]); OperandType operandType = ((OpCode)(ref val)).OperandType; IMetadataTokenProvider val2; switch ((int)operandType) { case 5: visitor.OnInlineNone(val); break; case 10: { int num2 = ((BinaryReader)(object)code).ReadInt32(); int[] array = new int[num2]; for (int i = 0; i < num2; i++) { array[i] = ((BinaryReader)(object)code).ReadInt32(); } visitor.OnInlineSwitch(val, array); break; } case 15: visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadSByte()); break; case 0: visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadInt32()); break; case 16: if (val == OpCodes.Ldc_I4_S) { visitor.OnInlineSByte(val, ((BinaryReader)(object)code).ReadSByte()); } else { visitor.OnInlineByte(val, ((BinaryReader)(object)code).ReadByte()); } break; case 2: visitor.OnInlineInt32(val, ((BinaryReader)(object)code).ReadInt32()); break; case 3: visitor.OnInlineInt64(val, ((BinaryReader)(object)code).ReadInt64()); break; case 17: visitor.OnInlineSingle(val, ((BinaryReader)(object)code).ReadSingle()); break; case 7: visitor.OnInlineDouble(val, ((BinaryReader)(object)code).ReadDouble()); break; case 8: visitor.OnInlineSignature(val, code.GetCallSite(code.ReadToken())); break; case 9: visitor.OnInlineString(val, code.GetString(code.ReadToken())); break; case 19: visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadByte())); break; case 14: visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadInt16())); break; case 18: visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadByte())); break; case 13: visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadInt16())); break; case 1: case 4: case 11: case 12: { val2 = metadata.LookupToken(code.ReadToken()); MetadataToken metadataToken = val2.MetadataToken; TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType; if ((int)tokenType <= 67108864) { if ((int)tokenType != 16777216 && (int)tokenType != 33554432) { if ((int)tokenType == 67108864) { visitor.OnInlineField(val, (FieldReference)val2); } break; } goto IL_02b8; } if ((int)tokenType <= 167772160) { if ((int)tokenType != 100663296) { if ((int)tokenType != 167772160) { break; } FieldReference val3 = (FieldReference)(object)((val2 is FieldReference) ? val2 : null); if (val3 != null) { visitor.OnInlineField(val, val3); break; } MethodReference val4 = (MethodReference)(object)((val2 is MethodReference) ? val2 : null); if (val4 != null) { visitor.OnInlineMethod(val, val4); break; } throw new InvalidOperationException(); } } else { if ((int)tokenType == 452984832) { goto IL_02b8; } if ((int)tokenType != 721420288) { break; } } visitor.OnInlineMethod(val, (MethodReference)val2); break; } IL_02b8: visitor.OnInlineType(val, (TypeReference)val2); break; } } } private static VariableDefinition GetVariable(ParseContext context, int index) { return context.Variables[index]; } } public static class MethodBodyRocks { public static void SimplifyMacros(this MethodBody self) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Expected I4, but got Unknown //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Unknown result type (might be due to invalid IL or missing references) //IL_0357: Unknown result type (might be due to invalid IL or missing references) //IL_036d: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) //IL_0399: Unknown result type (might be due to invalid IL or missing references) //IL_03af: Unknown result type (might be due to invalid IL or missing references) //IL_03cf: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_03ff: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_041c: Unknown result type (might be due to invalid IL or missing references) //IL_0429: Unknown result type (might be due to invalid IL or missing references) //IL_0436: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0450: Unknown result type (might be due to invalid IL or missing references) //IL_045d: Unknown result type (might be due to invalid IL or missing references) //IL_046a: Unknown result type (might be due to invalid IL or missing references) //IL_0477: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Invalid comparison between Unknown and I4 //IL_0484: Unknown result type (might be due to invalid IL or missing references) if (self == null) { throw new ArgumentNullException("self"); } Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; OpCode opCode = current.OpCode; if ((int)((OpCode)(ref opCode)).OpCodeType != 1) { continue; } opCode = current.OpCode; Code code = ((OpCode)(ref opCode)).Code; switch (code - 2) { case 0: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 0)); continue; case 1: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 1)); continue; case 2: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 2)); continue; case 3: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 3)); continue; case 4: ExpandMacro(current, OpCodes.Ldloc, self.Variables[0]); continue; case 5: ExpandMacro(current, OpCodes.Ldloc, self.Variables[1]); continue; case 6: ExpandMacro(current, OpCodes.Ldloc, self.Variables[2]); continue; case 7: ExpandMacro(current, OpCodes.Ldloc, self.Variables[3]); continue; case 8: ExpandMacro(current, OpCodes.Stloc, self.Variables[0]); continue; case 9: ExpandMacro(current, OpCodes.Stloc, self.Variables[1]); continue; case 10: ExpandMacro(current, OpCodes.Stloc, self.Variables[2]); continue; case 11: ExpandMacro(current, OpCodes.Stloc, self.Variables[3]); continue; case 12: current.OpCode = OpCodes.Ldarg; continue; case 13: current.OpCode = OpCodes.Ldarga; continue; case 14: current.OpCode = OpCodes.Starg; continue; case 15: current.OpCode = OpCodes.Ldloc; continue; case 16: current.OpCode = OpCodes.Ldloca; continue; case 17: current.OpCode = OpCodes.Stloc; continue; case 19: ExpandMacro(current, OpCodes.Ldc_I4, -1); continue; case 20: ExpandMacro(current, OpCodes.Ldc_I4, 0); continue; case 21: ExpandMacro(current, OpCodes.Ldc_I4, 1); continue; case 22: ExpandMacro(current, OpCodes.Ldc_I4, 2); continue; case 23: ExpandMacro(current, OpCodes.Ldc_I4, 3); continue; case 24: ExpandMacro(current, OpCodes.Ldc_I4, 4); continue; case 25: ExpandMacro(current, OpCodes.Ldc_I4, 5); continue; case 26: ExpandMacro(current, OpCodes.Ldc_I4, 6); continue; case 27: ExpandMacro(current, OpCodes.Ldc_I4, 7); continue; case 28: ExpandMacro(current, OpCodes.Ldc_I4, 8); continue; case 29: ExpandMacro(current, OpCodes.Ldc_I4, (int)(sbyte)current.Operand); continue; case 40: current.OpCode = OpCodes.Br; continue; case 41: current.OpCode = OpCodes.Brfalse; continue; case 42: current.OpCode = OpCodes.Brtrue; continue; case 43: current.OpCode = OpCodes.Beq; continue; case 44: current.OpCode = OpCodes.Bge; continue; case 45: current.OpCode = OpCodes.Bgt; continue; case 46: current.OpCode = OpCodes.Ble; continue; case 47: current.OpCode = OpCodes.Blt; continue; case 48: current.OpCode = OpCodes.Bne_Un; continue; case 49: current.OpCode = OpCodes.Bge_Un; continue; case 50: current.OpCode = OpCodes.Bgt_Un; continue; case 51: current.OpCode = OpCodes.Ble_Un; continue; case 52: current.OpCode = OpCodes.Blt_Un; continue; case 18: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: continue; } if ((int)code == 188) { current.OpCode = OpCodes.Leave; } } } finally { ((IDisposable)enumerator).Dispose(); } } private static void ExpandMacro(Instruction instruction, OpCode opcode, object operand) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) instruction.OpCode = opcode; instruction.Operand = operand; } private static void MakeMacro(Instruction instruction, OpCode opcode) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) instruction.OpCode = opcode; instruction.Operand = null; } public static void Optimize(this MethodBody self) { if (self == null) { throw new ArgumentNullException("self"); } self.OptimizeLongs(); self.OptimizeMacros(); } private static void OptimizeLongs(this MethodBody self) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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) //IL_0021: Invalid comparison between Unknown and I4 //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < self.Instructions.Count; i++) { Instruction val = self.Instructions[i]; OpCode opCode = val.OpCode; if ((int)((OpCode)(ref opCode)).Code == 33) { long num = (long)val.Operand; if (num < int.MaxValue && num > int.MinValue) { ExpandMacro(val, OpCodes.Ldc_I4, (int)num); self.Instructions.Insert(++i, Instruction.Create(OpCodes.Conv_I8)); } } } } public static void OptimizeMacros(this MethodBody self) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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_0034: 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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected I4, but got Unknown //IL_02fa: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Unknown result type (might be due to invalid IL or missing references) //IL_0327: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_0368: Unknown result type (might be due to invalid IL or missing references) //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_028c: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_0391: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) if (self == null) { throw new ArgumentNullException("self"); } MethodDefinition method = self.Method; Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; OpCode opCode = current.OpCode; Code code = ((OpCode)(ref opCode)).Code; if ((int)code != 32) { switch (code - 199) { case 0: { int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index; if (index == -1 && current.Operand == self.ThisParameter) { index = 0; } else if (((MethodReference)method).HasThis) { index++; } switch (index) { case 0: MakeMacro(current, OpCodes.Ldarg_0); break; case 1: MakeMacro(current, OpCodes.Ldarg_1); break; case 2: MakeMacro(current, OpCodes.Ldarg_2); break; case 3: MakeMacro(current, OpCodes.Ldarg_3); break; default: if (index < 256) { ExpandMacro(current, OpCodes.Ldarg_S, current.Operand); } break; } break; } case 3: { int index = ((VariableReference)(VariableDefinition)current.Operand).Index; switch (index) { case 0: MakeMacro(current, OpCodes.Ldloc_0); break; case 1: MakeMacro(current, OpCodes.Ldloc_1); break; case 2: MakeMacro(current, OpCodes.Ldloc_2); break; case 3: MakeMacro(current, OpCodes.Ldloc_3); break; default: if (index < 256) { ExpandMacro(current, OpCodes.Ldloc_S, current.Operand); } break; } break; } case 5: { int index = ((VariableReference)(VariableDefinition)current.Operand).Index; switch (index) { case 0: MakeMacro(current, OpCodes.Stloc_0); break; case 1: MakeMacro(current, OpCodes.Stloc_1); break; case 2: MakeMacro(current, OpCodes.Stloc_2); break; case 3: MakeMacro(current, OpCodes.Stloc_3); break; default: if (index < 256) { ExpandMacro(current, OpCodes.Stloc_S, current.Operand); } break; } break; } case 1: { int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index; if (index == -1 && current.Operand == self.ThisParameter) { index = 0; } else if (((MethodReference)method).HasThis) { index++; } if (index < 256) { ExpandMacro(current, OpCodes.Ldarga_S, current.Operand); } break; } case 4: if (((VariableReference)(VariableDefinition)current.Operand).Index < 256) { ExpandMacro(current, OpCodes.Ldloca_S, current.Operand); } break; } continue; } int num = (int)current.Operand; switch (num) { case -1: MakeMacro(current, OpCodes.Ldc_I4_M1); continue; case 0: MakeMacro(current, OpCodes.Ldc_I4_0); continue; case 1: MakeMacro(current, OpCodes.Ldc_I4_1); continue; case 2: MakeMacro(current, OpCodes.Ldc_I4_2); continue; case 3: MakeMacro(current, OpCodes.Ldc_I4_3); continue; case 4: MakeMacro(current, OpCodes.Ldc_I4_4); continue; case 5: MakeMacro(current, OpCodes.Ldc_I4_5); continue; case 6: MakeMacro(current, OpCodes.Ldc_I4_6); continue; case 7: MakeMacro(current, OpCodes.Ldc_I4_7); continue; case 8: MakeMacro(current, OpCodes.Ldc_I4_8); continue; } if (num >= -128 && num < 128) { ExpandMacro(current, OpCodes.Ldc_I4_S, (sbyte)num); } } } finally { ((IDisposable)enumerator).Dispose(); } OptimizeBranches(self); } private static void OptimizeBranches(MethodBody body) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) ComputeOffsets(body); Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; OpCode opCode = current.OpCode; if ((int)((OpCode)(ref opCode)).OperandType == 0 && OptimizeBranch(current)) { ComputeOffsets(body); } } } finally { ((IDisposable)enumerator).Dispose(); } } private static bool OptimizeBranch(Instruction instruction) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected I4, but got Unknown //IL_0092: 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_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Invalid comparison between Unknown and I4 //IL_0147: Unknown result type (might be due to invalid IL or missing references) int offset = ((Instruction)instruction.Operand).Offset; int offset2 = instruction.Offset; OpCode opCode = instruction.OpCode; int num = offset - (offset2 + ((OpCode)(ref opCode)).Size + 4); if (num < -128 || num > 127) { return false; } opCode = instruction.OpCode; Code code = ((OpCode)(ref opCode)).Code; switch (code - 55) { default: if ((int)code == 187) { instruction.OpCode = OpCodes.Leave_S; } break; case 0: instruction.OpCode = OpCodes.Br_S; break; case 1: instruction.OpCode = OpCodes.Brfalse_S; break; case 2: instruction.OpCode = OpCodes.Brtrue_S; break; case 3: instruction.OpCode = OpCodes.Beq_S; break; case 4: instruction.OpCode = OpCodes.Bge_S; break; case 5: instruction.OpCode = OpCodes.Bgt_S; break; case 6: instruction.OpCode = OpCodes.Ble_S; break; case 7: instruction.OpCode = OpCodes.Blt_S; break; case 8: instruction.OpCode = OpCodes.Bne_Un_S; break; case 9: instruction.OpCode = OpCodes.Bge_Un_S; break; case 10: instruction.OpCode = OpCodes.Bgt_Un_S; break; case 11: instruction.OpCode = OpCodes.Ble_Un_S; break; case 12: instruction.OpCode = OpCodes.Blt_Un_S; break; } return true; } private static void ComputeOffsets(MethodBody body) { //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) int num = 0; Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; current.Offset = num; num += current.GetSize(); } } finally { ((IDisposable)enumerator).Dispose(); } } } public static class MethodDefinitionRocks { public static MethodDefinition GetBaseMethod(this MethodDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.IsVirtual) { return self; } if (self.IsNewSlot) { return self; } for (TypeDefinition val = ResolveBaseType(self.DeclaringType); val != null; val = ResolveBaseType(val)) { MethodDefinition matchingMethod = GetMatchingMethod(val, self); if (matchingMethod != null) { return matchingMethod; } } return self; } public static MethodDefinition GetOriginalBaseMethod(this MethodDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } while (true) { MethodDefinition baseMethod = self.GetBaseMethod(); if (baseMethod == self) { break; } self = baseMethod; } return self; } private static TypeDefinition ResolveBaseType(TypeDefinition type) { if (type == null) { return null; } TypeReference baseType = type.BaseType; if (baseType == null) { return null; } return baseType.Resolve(); } private static MethodDefinition GetMatchingMethod(TypeDefinition type, MethodDefinition method) { return MetadataResolver.GetMethod(type.Methods, (MethodReference)(object)method); } } public static class ModuleDefinitionRocks { public static IEnumerable<TypeDefinition> GetAllTypes(this ModuleDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } return ((IEnumerable<TypeDefinition>)self.Types).SelectMany(Functional.Y((Func<TypeDefinition, IEnumerable<TypeDefinition>> f) => (TypeDefinition type) => ((IEnumerable<TypeDefinition>)type.NestedTypes).SelectMany(f).Prepend(type))); } } public static class ParameterReferenceRocks { public static int GetSequence(this ParameterReference self) { return self.Index + 1; } } public static class SecurityDeclarationRocks { public static PermissionSet ToPermissionSet(this SecurityDeclaration self) { if (self == null) { throw new ArgumentNullException("self"); } if (TryProcessPermissionSetAttribute(self, out var set)) { return set; } return CreatePermissionSet(self); } private static bool TryProcessPermissionSetAttribute(SecurityDeclaration declaration, out PermissionSet set) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected I4, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_0061: Unknown result type (might be due to invalid IL or missing references) set = null; if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1) { return false; } SecurityAttribute val = declaration.SecurityAttributes[0]; if (!Mixin.IsTypeOf(val.AttributeType, "System.Security.Permissions", "PermissionSetAttribute")) { return false; } PermissionSetAttribute val2 = new PermissionSetAttribute((SecurityAction)declaration.Action); CustomAttributeNamedArgument val3 = val.Properties[0]; CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref val3)).Argument; string text = (string)((CustomAttributeArgument)(ref argument)).Value; string name = ((CustomAttributeNamedArgument)(ref val3)).Name; if (!(name == "XML")) { if (!(name == "Name")) { throw new NotImplementedException(((CustomAttributeNamedArgument)(ref val3)).Name); } val2.Name = text; } else { val2.XML = text; } set = val2.CreatePermissionSet(); return true; } private static PermissionSet CreatePermissionSet(SecurityDeclaration declaration) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) PermissionSet permissionSet = new PermissionSet(PermissionState.None); Enumerator<SecurityAttribute> enumerator = declaration.SecurityAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { SecurityAttribute current = enumerator.Current; IPermission perm = CreatePermission(declaration, current); permissionSet.AddPermission(perm); } return permissionSet; } finally { ((IDisposable)enumerator).Dispose(); } } private static IPermission CreatePermission(SecurityDeclaration declaration, SecurityAttribute attribute) { SecurityAttribute obj = CreateSecurityAttribute(Type.GetType(((MemberReference)attribute.AttributeType).FullName) ?? throw new ArgumentException("attribute"), declaration) ?? throw new InvalidOperationException(); CompleteSecurityAttribute(obj, attribute); return obj.CreatePermission(); } private static void CompleteSecurityAttribute(SecurityAttribute security_attribute, SecurityAttribute attribute) { if (attribute.HasFields) { CompleteSecurityAttributeFields(security_attribute, attribute); } if (attribute.HasProperties) { CompleteSecurityAttributeProperties(security_attribute, attribute); } } private static void CompleteSecurityAttributeFields(SecurityAttribute security_attribute, SecurityAttribute attribute) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) Type type = security_attribute.GetType(); Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Fields.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttributeNamedArgument current = enumerator.Current; FieldInfo? field = type.GetField(((CustomAttributeNamedArgument)(ref current)).Name); CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument; field.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value); } } finally { ((IDisposable)enumerator).Dispose(); } } private static void CompleteSecurityAttributeProperties(SecurityAttribute security_attribute, SecurityAttribute attribute) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) Type type = security_attribute.GetType(); Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Properties.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttributeNamedArgument current = enumerator.Current; PropertyInfo? property = type.GetProperty(((CustomAttributeNamedArgument)(ref current)).Name); CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument; property.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value, null); } } finally { ((IDisposable)enumerator).Dispose(); } } private static SecurityAttribute CreateSecurityAttribute(Type attribute_type, SecurityDeclaration declaration) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected I4, but got Unknown try { return (SecurityAttribute)Activator.CreateInstance(attribute_type, (SecurityAction)declaration.Action); } catch (MissingMethodException) { return (SecurityAttribute)Activator.CreateInstance(attribute_type, new object[0]); } } public static SecurityDeclaration ToSecurityDeclaration(this PermissionSet self, SecurityAction action, ModuleDefinition module) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: 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_003d: Expected O, but got Unknown //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: 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_007a: Expected O, but got Unknown if (self == null) { throw new ArgumentNullException("self"); } if (module == null) { throw new ArgumentNullException("module"); } SecurityDeclaration val = new SecurityDeclaration(action); SecurityAttribute val2 = new SecurityAttribute(module.TypeSystem.LookupType("System.Security.Permissions", "PermissionSetAttribute")); val2.Properties.Add(new CustomAttributeNamedArgument("XML", new CustomAttributeArgument(module.TypeSystem.String, (object)self.ToXml().ToString()))); val.SecurityAttributes.Add(val2); return val; } } public static class TypeDefinitionRocks { public static IEnumerable<MethodDefinition> GetConstructors(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.HasMethods) { return Empty<MethodDefinition>.Array; } return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => method.IsConstructor); } public static MethodDefinition GetStaticConstructor(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.HasMethods) { return null; } return self.GetConstructors().FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition ctor) => ctor.IsStatic)); } public static IEnumerable<MethodDefinition> GetMethods(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.HasMethods) { return Empty<MethodDefinition>.Array; } return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => !method.IsConstructor); } public static TypeReference GetEnumUnderlyingType(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.IsEnum) { throw new ArgumentException(); } return Mixin.GetEnumUnderlyingType(self); } } public static class TypeReferenceRocks { public static ArrayType MakeArrayType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new ArrayType(self); } public static ArrayType MakeArrayType(this TypeReference self, int rank) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (rank == 0) { throw new ArgumentOutOfRangeException("rank"); } ArrayType val = new ArrayType(self); for (int i = 1; i < rank; i++) { val.Dimensions.Add(default(ArrayDimension)); } return val; } public static PointerType MakePointerType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new PointerType(self); } public static ByReferenceType MakeByReferenceType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new ByReferenceType(self); } public static OptionalModifierType MakeOptionalModifierType(this TypeReference self, TypeReference modifierType) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return new OptionalModifierType(modifierType, self); } public static RequiredModifierType MakeRequiredModifierType(this TypeReference self, TypeReference modifierType) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return new RequiredModifierType(modifierType, self); } public static GenericInstanceType MakeGenericInstanceType(this TypeReference self, params TypeReference[] arguments) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown if (self == null) { throw new ArgumentNullException("self"); } if (arguments == null) { throw new ArgumentNullException("arguments"); } if (arguments.Length == 0) { throw new ArgumentException(); } if (self.GenericParameters.Count != arguments.Length) { throw new ArgumentException(); } GenericInstanceType val = new GenericInstanceType(self); foreach (TypeReference val2 in arguments) { val.GenericArguments.Add(val2); } return val; } public static PinnedType MakePinnedType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new PinnedType(self); } public static SentinelType MakeSentinelType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new SentinelType(self); } }
UMM/Mods/Runtime Unity Editor/MonoMod.RuntimeDetour.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Cil; using MonoMod.RuntimeDetour.HookGen; using MonoMod.RuntimeDetour.Platforms; using MonoMod.Utils; using MonoMod.Utils.Cil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021 0x0ade")] [assembly: AssemblyDescription("Flexible and easily extensible runtime detouring library. Wrap, replace and manipulate (Mono.Cecil) methods at runtime.")] [assembly: AssemblyFileVersion("21.11.1.1")] [assembly: AssemblyInformationalVersion("21.11.01.01")] [assembly: AssemblyProduct("MonoMod.RuntimeDetour")] [assembly: AssemblyTitle("MonoMod.RuntimeDetour")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("21.11.1.1")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } } internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison) { return self.Replace(oldValue, newValue); } public static bool Contains(this string self, string value, StringComparison comparison) { return self.Contains(value); } public static int GetHashCode(this string self, StringComparison comparison) { return self.GetHashCode(); } public static int IndexOf(this string self, char value, StringComparison comparison) { return self.IndexOf(value); } public static int IndexOf(this string self, string value, StringComparison comparison) { return self.IndexOf(value); } public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace MonoMod { internal static class MMDbgLog { public static readonly string Tag; public static TextWriter Writer; public static bool Debugging; static MMDbgLog() { Tag = typeof(MMDbgLog).Assembly.GetName().Name; if (!(Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1")) { string? environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG"); bool? obj; if (environmentVariable == null) { obj = null; } else { string text = environmentVariable.ToLower(CultureInfo.InvariantCulture); obj = ((text != null) ? new bool?(MultiTargetShims.Contains(text, Tag.ToLower(CultureInfo.InvariantCulture), StringComparison.Ordinal)) : null); } bool? flag = obj; if (!flag.GetValueOrDefault()) { return; } } Start(); } public static void WaitForDebugger() { if (!Debugging) { Debugging = true; Debugger.Launch(); Thread.Sleep(6000); Debugger.Break(); } } public static void Start() { if (Writer != null) { return; } string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH"); if (text == "-") { Writer = Console.Out; return; } if (string.IsNullOrEmpty(text)) { text = "mmdbglog.txt"; } text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text)); try { if (File.Exists(text)) { File.Delete(text); } } catch { } try { string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8); } catch { } } public static void Log(string str) { TextWriter writer = Writer; if (writer != null) { writer.WriteLine(str); writer.Flush(); } } public static T Log<T>(string str, T value) { TextWriter writer = Writer; if (writer == null) { return value; } writer.WriteLine(string.Format(CultureInfo.InvariantCulture, str, new object[1] { value })); writer.Flush(); return value; } } } namespace MonoMod.RuntimeDetour { public struct DetourConfig { public bool ManualApply; public int Priority; public string ID; public IEnumerable<string> Before; public IEnumerable<string> After; } public class Detour : ISortableDetour, IDetour, IDisposable { private static Dictionary<MethodBase, List<Detour>> _DetourMap = new Dictionary<MethodBase, List<Detour>>((IEqualityComparer<MethodBase>?)new GenericMethodInstantiationComparer()); private static Dictionary<MethodBase, MethodInfo> _BackupMethods = new Dictionary<MethodBase, MethodInfo>(); private static uint _GlobalIndexNext = 0u; public static Func<Detour, MethodBase, MethodBase, bool> OnDetour; public static Func<Detour, bool> OnUndo; public static Func<Detour, MethodBase, MethodBase> OnGenerateTrampoline; private readonly uint _GlobalIndex; private int _Priority; private string _ID; private List<string> _Before = new List<string>(); private ReadOnlyCollection<string> _BeforeRO; private List<string> _After = new List<string>(); private ReadOnlyCollection<string> _AfterRO; public readonly MethodBase Method; public readonly MethodBase Target; public readonly MethodBase TargetReal; private NativeDetour _TopDetour; private MethodInfo _ChainedTrampoline; private static int compileMethodSubscribed = 0; private List<Detour> _DetourChain { get { if (!_DetourMap.TryGetValue(Method, out var value)) { return null; } return value; } } public bool IsValid => Index != -1; public bool IsApplied { get; private set; } private bool IsTop => _TopDetour != null; public int Index => _DetourChain?.IndexOf(this) ?? (-1); public int MaxIndex => _DetourChain?.Count ?? (-1); public uint GlobalIndex => _GlobalIndex; public int Priority { get { return _Priority; } set { if (_Priority != value) { _Priority = value; _RefreshChain(Method); } } } public string ID { get { return _ID; } set { if (string.IsNullOrEmpty(value)) { value = Extensions.GetID(Target, (string)null, (string)null, true, false, true); } if (!(_ID == value)) { _ID = value; _RefreshChain(Method); } } } public IEnumerable<string> Before { get { return _BeforeRO ?? (_BeforeRO = _Before.AsReadOnly()); } set { lock (_Before) { _Before.Clear(); if (value != null) { foreach (string item in value) { _Before.Add(item); } } _RefreshChain(Method); } } } public IEnumerable<string> After { get { return _AfterRO ?? (_AfterRO = _After.AsReadOnly()); } set { lock (_After) { _After.Clear(); if (value != null) { foreach (string item in value) { _After.Add(item); } } _RefreshChain(Method); } } } public Detour(MethodBase from, MethodBase to, ref DetourConfig config) { //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Expected O, but got Unknown from = from.GetIdentifiable(); if (from.Equals(to)) { throw new ArgumentException("Cannot detour a method to itself!"); } MMDbgLog.Log("detour from " + Extensions.GetID(from, (string)null, (string)null, true, false, false) + " to " + Extensions.GetID(to, (string)null, (string)null, true, false, false)); Method = from; Target = to.Pin(); TargetReal = DetourHelper.Runtime.GetDetourTarget(from, to); _GlobalIndex = _GlobalIndexNext++; _Priority = config.Priority; _ID = config.ID; if (config.Before != null) { foreach (string item in config.Before) { _Before.Add(item); } } if (config.After != null) { foreach (string item2 in config.After) { _After.Add(item2); } } lock (_BackupMethods) { if ((!_BackupMethods.TryGetValue(Method, out var value) || (object)value == null) && (object)(value = Method.CreateILCopy()) != null) { _BackupMethods[Method] = value.Pin(); } } ParameterInfo[] parameters = Method.GetParameters(); Type[] array; if (!Method.IsStatic) { array = new Type[parameters.Length + 1]; array[0] = Extensions.GetThisParamType(Method); for (int i = 0; i < parameters.Length; i++) { array[i + 1] = parameters[i].ParameterType; } } else { array = new Type[parameters.Length]; for (int j = 0; j < parameters.Length; j++) { array[j] = parameters[j].ParameterType; } } DynamicMethodDefinition val = new DynamicMethodDefinition($"Chain<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", (Method as MethodInfo)?.ReturnType ?? typeof(void), array); try { _ChainedTrampoline = val.StubCriticalDetour().Generate().Pin(); } finally { ((IDisposable)val)?.Dispose(); } List<Detour> value2; lock (_DetourMap) { if (!_DetourMap.TryGetValue(Method, out value2)) { value2 = (_DetourMap[Method] = new List<Detour>()); } } lock (value2) { value2.Add(this); } if (!config.ManualApply) { Apply(); } } public Detour(MethodBase from, MethodBase to, DetourConfig config) : this(from, to, ref config) { } public Detour(MethodBase from, MethodBase to) : this(from, to, DetourContext.Current?.DetourConfig ?? default(DetourConfig)) { } public Detour(MethodBase method, IntPtr to, ref DetourConfig config) : this(method, DetourHelper.GenerateNativeProxy(to, method), ref config) { } public Detour(MethodBase method, IntPtr to, DetourConfig config) : this(method, DetourHelper.GenerateNativeProxy(to, method), ref config) { } public Detour(MethodBase method, IntPtr to) : this(method, DetourHelper.GenerateNativeProxy(to, method)) { } public Detour(Delegate from, IntPtr to, ref DetourConfig config) : this(from.Method, to, ref config) { } public Detour(Delegate from, IntPtr to, DetourConfig config) : this(from.Method, to, ref config) { } public Detour(Delegate from, IntPtr to) : this(from.Method, to) { } public Detour(Delegate from, Delegate to, ref DetourConfig config) : this(from.Method, to.Method, ref config) { } public Detour(Delegate from, Delegate to, DetourConfig config) : this(from.Method, to.Method, ref config) { } public Detour(Delegate from, Delegate to) : this(from.Method, to.Method) { } public Detour(Expression from, IntPtr to, ref DetourConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Detour(Expression from, IntPtr to, DetourConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Detour(Expression from, IntPtr to) : this(((MethodCallExpression)from).Method, to) { } public Detour(Expression from, Expression to, ref DetourConfig config) : this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method, ref config) { } public Detour(Expression from, Expression to, DetourConfig config) : this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method, ref config) { } public Detour(Expression from, Expression to) : this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method) { } public Detour(Expression<Action> from, IntPtr to, ref DetourConfig config) : this(from.Body, to, ref config) { } public Detour(Expression<Action> from, IntPtr to, DetourConfig config) : this(from.Body, to, ref config) { } public Detour(Expression<Action> from, IntPtr to) : this(from.Body, to) { } public Detour(Expression<Action> from, Expression<Action> to, ref DetourConfig config) : this(from.Body, to.Body, ref config) { } public Detour(Expression<Action> from, Expression<Action> to, DetourConfig config) : this(from.Body, to.Body, ref config) { } public Detour(Expression<Action> from, Expression<Action> to) : this(from.Body, to.Body) { } public void Apply() { if (!IsValid) { throw new ObjectDisposedException("Detour"); } if (!IsApplied) { Func<Detour, MethodBase, MethodBase, bool> onDetour = OnDetour; if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[3] { this, Method, Target })) { IsApplied = true; _RefreshChain(Method); } } } public void Undo() { if (!IsValid) { throw new ObjectDisposedException("Detour"); } if (IsApplied) { Func<Detour, bool> onUndo = OnUndo; if (onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) { IsApplied = false; _RefreshChain(Method); } } } public void Free() { if (!IsValid) { return; } Undo(); List<Detour> detourChain = _DetourChain; lock (detourChain) { detourChain.Remove(this); if (detourChain.Count == 0) { lock (_BackupMethods) { if (_BackupMethods.TryGetValue(Method, out var value)) { value.Unpin(); _BackupMethods.Remove(Method); } } lock (_DetourMap) { _DetourMap.Remove(Method); } } } _ChainedTrampoline.Unpin(); Target.Unpin(); } public void Dispose() { if (IsValid) { Undo(); Free(); } } public MethodBase GenerateTrampoline(MethodBase signature = null) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) Func<Detour, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline; MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null); if ((object)methodBase != null) { return methodBase; } if ((object)signature == null) { signature = Target; } Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void); ParameterInfo[] parameters = signature.GetParameters(); Type[] array = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].ParameterType; } DynamicMethodDefinition val = new DynamicMethodDefinition($"Trampoline<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", type, array); try { ILProcessor iLProcessor = val.GetILProcessor(); for (int j = 0; j < 32; j++) { iLProcessor.Emit(OpCodes.Nop); } for (int k = 0; k < array.Length; k++) { iLProcessor.Emit(OpCodes.Ldarg, k); } Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)_ChainedTrampoline); iLProcessor.Emit(OpCodes.Ret); return val.Generate(); } finally { ((IDisposable)val)?.Dispose(); } } public T GenerateTrampoline<T>() where T : Delegate { if (!typeof(Delegate).IsAssignableFrom(typeof(T))) { throw new InvalidOperationException($"Type {typeof(T)} not a delegate type."); } return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T; } private void _TopUndo() { if (_TopDetour != null) { _TopDetour.Undo(); _TopDetour.Free(); _TopDetour = null; Method.Unpin(); TargetReal.Unpin(); } } private void _TopApply() { if (_TopDetour == null) { _TopDetour = new NativeDetour(Method.Pin().GetNativeStart(), TargetReal.Pin().GetNativeStart()); } } private static void _OnCompileMethod(MethodBase method, IntPtr codeStart, ulong codeLen) { if ((object)method == null) { return; } MMDbgLog.Log("compiling: " + Extensions.GetID(method, (string)null, (string)null, true, false, false)); if (_DetourMap.TryGetValue(method, out var value)) { value.FindLast((Detour d) => d.IsTop)?._TopDetour?.ChangeSource(codeStart); } } private static void _RefreshChain(MethodBase method) { if (Interlocked.CompareExchange(ref compileMethodSubscribed, 1, 0) == 0) { DetourHelper.Runtime.OnMethodCompiled += _OnCompileMethod; } MMDbgLog.Log("detours applying for " + Extensions.GetID(method, (string)null, (string)null, true, false, false)); List<Detour> list = _DetourMap[method]; lock (list) { DetourSorter<Detour>.Sort(list); Detour detour = list.FindLast((Detour d) => d.IsTop); Detour detour2 = list.FindLast((Detour d) => d.IsApplied); if (detour != detour2) { detour?._TopUndo(); } if (list.Count == 0) { return; } MethodBase method2 = _BackupMethods[method]; foreach (Detour item in list) { if (item.IsApplied) { _ = item._ChainedTrampoline; using (NativeDetour nativeDetour = new NativeDetour(item._ChainedTrampoline.GetNativeStart(), method2.GetNativeStart())) { nativeDetour.Free(); } method2 = item.Target; } } if (detour != detour2) { detour2?._TopApply(); } } } } public class Detour<T> : Detour where T : Delegate { public Detour(T from, IntPtr to, ref DetourConfig config) : base(from, to, ref config) { } public Detour(T from, IntPtr to, DetourConfig config) : base(from, to, ref config) { } public Detour(T from, IntPtr to) : base(from, to) { } public Detour(T from, T to, ref DetourConfig config) : base(from, to, ref config) { } public Detour(T from, T to, DetourConfig config) : base(from, to, ref config) { } public Detour(T from, T to) : base(from, to) { } } public sealed class DetourContext : IDisposable { [ThreadStatic] private static List<DetourContext> _Contexts; [ThreadStatic] private static DetourContext Last; private MethodBase Creator; public int Priority; private readonly string _FallbackID; private string _ID; public List<string> Before = new List<string>(); public List<string> After = new List<string>(); private bool IsDisposed; private static List<DetourContext> Contexts => _Contexts ?? (_Contexts = new List<DetourContext>()); internal static DetourContext Current { get { DetourContext last = Last; if (last != null && last.IsValid) { return Last; } List<DetourContext> contexts = Contexts; int num = contexts.Count - 1; while (num > -1) { DetourContext detourContext = contexts[num]; if (!detourContext.IsValid) { contexts.RemoveAt(num); num--; continue; } return Last = detourContext; } return null; } } public string ID { get { return _ID ?? _FallbackID; } set { _ID = (string.IsNullOrEmpty(value) ? null : value); } } public DetourConfig DetourConfig { get { DetourConfig result = default(DetourConfig); result.Priority = Priority; result.ID = ID; result.Before = Before; result.After = After; return result; } } public HookConfig HookConfig { get { HookConfig result = default(HookConfig); result.Priority = Priority; result.ID = ID; result.Before = Before; result.After = After; return result; } } public ILHookConfig ILHookConfig { get { ILHookConfig result = default(ILHookConfig); result.Priority = Priority; result.ID = ID; result.Before = Before; result.After = After; return result; } } internal bool IsValid { get { if (IsDisposed) { return false; } if ((object)Creator == null) { return true; } StackTrace stackTrace = new StackTrace(); int frameCount = stackTrace.FrameCount; for (int i = 0; i < frameCount; i++) { if ((object)stackTrace.GetFrame(i).GetMethod() == Creator) { return true; } } return false; } } public DetourContext(int priority, string id) { StackTrace stackTrace = new StackTrace(); int frameCount = stackTrace.FrameCount; for (int i = 0; i < frameCount; i++) { MethodBase method = stackTrace.GetFrame(i).GetMethod(); if ((object)method?.DeclaringType != typeof(DetourContext)) { Creator = method; break; } } object obj = Creator?.DeclaringType?.Assembly?.GetName().Name; if (obj == null) { MethodBase creator = Creator; obj = (((object)creator != null) ? Extensions.GetID(creator, (string)null, (string)null, true, false, true) : null); } _FallbackID = (string)obj; Last = this; Contexts.Add(this); Priority = priority; ID = id; } public DetourContext(string id) : this(0, id) { } public DetourContext(int priority) : this(priority, null) { } public DetourContext() : this(0, null) { } public void Dispose() { if (IsDisposed) { IsDisposed = true; Last = null; Contexts.Remove(this); } } } public sealed class DetourModManager : IDisposable { private readonly Dictionary<IDetour, Assembly> DetourOwners = new Dictionary<IDetour, Assembly>(); private readonly Dictionary<Assembly, List<IDetour>> OwnedDetourLists = new Dictionary<Assembly, List<IDetour>>(); public HashSet<Assembly> Ignored = new HashSet<Assembly>(); private bool Disposed; private static readonly string[] HookTypeNames = new string[4] { "MonoMod.RuntimeDetour.NativeDetour", "MonoMod.RuntimeDetour.Detour", "MonoMod.RuntimeDetour.Hook", "MonoMod.RuntimeDetour.ILHook" }; public event Action<Assembly, MethodBase, Manipulator> OnILHook; public event Action<Assembly, MethodBase, MethodBase, object> OnHook; public event Action<Assembly, MethodBase, MethodBase> OnDetour; public event Action<Assembly, MethodBase, IntPtr, IntPtr> OnNativeDetour; public DetourModManager() { Ignored.Add(typeof(DetourModManager).Assembly); ILHook.OnDetour = (Func<ILHook, MethodBase, Manipulator, bool>)Delegate.Combine(ILHook.OnDetour, new Func<ILHook, MethodBase, Manipulator, bool>(RegisterILHook)); ILHook.OnUndo = (Func<ILHook, bool>)Delegate.Combine(ILHook.OnUndo, new Func<ILHook, bool>(UnregisterDetour)); Hook.OnDetour = (Func<Hook, MethodBase, MethodBase, object, bool>)Delegate.Combine(Hook.OnDetour, new Func<Hook, MethodBase, MethodBase, object, bool>(RegisterHook)); Hook.OnUndo = (Func<Hook, bool>)Delegate.Combine(Hook.OnUndo, new Func<Hook, bool>(UnregisterDetour)); Detour.OnDetour = (Func<Detour, MethodBase, MethodBase, bool>)Delegate.Combine(Detour.OnDetour, new Func<Detour, MethodBase, MethodBase, bool>(RegisterDetour)); Detour.OnUndo = (Func<Detour, bool>)Delegate.Combine(Detour.OnUndo, new Func<Detour, bool>(UnregisterDetour)); NativeDetour.OnDetour = (Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>)Delegate.Combine(NativeDetour.OnDetour, new Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>(RegisterNativeDetour)); NativeDetour.OnUndo = (Func<NativeDetour, bool>)Delegate.Combine(NativeDetour.OnUndo, new Func<NativeDetour, bool>(UnregisterDetour)); } public void Dispose() { if (!Disposed) { Disposed = true; OwnedDetourLists.Clear(); ILHook.OnDetour = (Func<ILHook, MethodBase, Manipulator, bool>)Delegate.Remove(ILHook.OnDetour, new Func<ILHook, MethodBase, Manipulator, bool>(RegisterILHook)); ILHook.OnUndo = (Func<ILHook, bool>)Delegate.Remove(ILHook.OnUndo, new Func<ILHook, bool>(UnregisterDetour)); Hook.OnDetour = (Func<Hook, MethodBase, MethodBase, object, bool>)Delegate.Remove(Hook.OnDetour, new Func<Hook, MethodBase, MethodBase, object, bool>(RegisterHook)); Hook.OnUndo = (Func<Hook, bool>)Delegate.Remove(Hook.OnUndo, new Func<Hook, bool>(UnregisterDetour)); Detour.OnDetour = (Func<Detour, MethodBase, MethodBase, bool>)Delegate.Remove(Detour.OnDetour, new Func<Detour, MethodBase, MethodBase, bool>(RegisterDetour)); Detour.OnUndo = (Func<Detour, bool>)Delegate.Remove(Detour.OnUndo, new Func<Detour, bool>(UnregisterDetour)); NativeDetour.OnDetour = (Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>)Delegate.Remove(NativeDetour.OnDetour, new Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>(RegisterNativeDetour)); NativeDetour.OnUndo = (Func<NativeDetour, bool>)Delegate.Remove(NativeDetour.OnUndo, new Func<NativeDetour, bool>(UnregisterDetour)); } } public void Unload(Assembly asm) { if ((object)asm == null || Ignored.Contains(asm)) { return; } HookEndpointManager.RemoveAllOwnedBy(asm); if (OwnedDetourLists.TryGetValue(asm, out var value)) { IDetour[] array = value.ToArray(); for (int i = 0; i < array.Length; i++) { array[i].Dispose(); } if (value.Count > 0) { throw new Exception("Some detours failed to unregister in " + asm.FullName); } OwnedDetourLists.Remove(asm); } } internal Assembly GetHookOwner(StackTrace stack = null) { if (stack == null) { stack = new StackTrace(); } Assembly assembly = null; int frameCount = stack.FrameCount; string text = null; for (int i = 0; i < frameCount; i++) { MethodBase method = stack.GetFrame(i).GetMethod(); if ((object)method?.DeclaringType == null) { continue; } string fullName = method.DeclaringType.FullName; if (text == null) { if (HookTypeNames.Contains(fullName)) { text = method.DeclaringType.FullName; } } else if (!(fullName == text)) { assembly = method?.DeclaringType.Assembly; break; } } if (Ignored.Contains(assembly)) { return null; } return assembly; } internal void TrackDetour(Assembly owner, IDetour detour) { if (!OwnedDetourLists.TryGetValue(owner, out var value)) { value = (OwnedDetourLists[owner] = new List<IDetour>()); } value.Add(detour); DetourOwners[detour] = owner; } internal bool RegisterILHook(ILHook _detour, MethodBase from, Manipulator manipulator) { Assembly hookOwner = GetHookOwner(); if ((object)hookOwner == null) { return true; } this.OnILHook?.Invoke(hookOwner, from, manipulator); TrackDetour(hookOwner, _detour); return true; } internal bool RegisterHook(Hook _detour, MethodBase from, MethodBase to, object target) { Assembly hookOwner = GetHookOwner(); if ((object)hookOwner == null) { return true; } this.OnHook?.Invoke(hookOwner, from, to, target); TrackDetour(hookOwner, _detour); return true; } internal bool RegisterDetour(Detour _detour, MethodBase from, MethodBase to) { Assembly hookOwner = GetHookOwner(); if ((object)hookOwner == null) { return true; } this.OnDetour?.Invoke(hookOwner, from, to); TrackDetour(hookOwner, _detour); return true; } internal bool RegisterNativeDetour(NativeDetour _detour, MethodBase method, IntPtr from, IntPtr to) { Assembly hookOwner = GetHookOwner(); if ((object)hookOwner == null) { return true; } this.OnNativeDetour?.Invoke(hookOwner, method, from, to); TrackDetour(hookOwner, _detour); return true; } internal bool UnregisterDetour(IDetour _detour) { if (DetourOwners.TryGetValue(_detour, out var value)) { DetourOwners.Remove(_detour); OwnedDetourLists[value].Remove(_detour); } return true; } } public static class HarmonyDetourBridge { public enum Type { Auto, Basic, AsOriginal, Override } private class DetourToRDAttribute : Attribute { public string Type { get; } public int SkipParams { get; } public string Name { get; } public DetourToRDAttribute(string type, int skipParams = 0, string name = null) { Type = type; SkipParams = skipParams; Name = name; } } private class DetourToHAttribute : Attribute { public string Type { get; } public int SkipParams { get; } public string Name { get; } public DetourToHAttribute(string type, int skipParams = 0, string name = null) { Type = type; SkipParams = skipParams; Name = name; } } private class TranspileAttribute : Attribute { public string Type { get; } public string Name { get; } public TranspileAttribute(string type, string name = null) { Type = type; Name = name; } } private class CriticalAttribute : Attribute { } private static Type CurrentType; private static Assembly _HarmonyASM; private static readonly HashSet<IDisposable> _Detours; private static readonly Dictionary<System.Type, MethodInfo> _Emitters; [ThreadStatic] private static DynamicMethodDefinition _LastWrapperDMD; private static Assembly _SharedStateASM; private static DetourConfig _DetourConfig; public static bool Initialized { get; private set; } static HarmonyDetourBridge() { _Detours = new HashSet<IDisposable>(); _Emitters = new Dictionary<System.Type, MethodInfo>(); System.Type typeFromHandle = typeof(OpCode); System.Type proxyType = ILGeneratorShim.GetProxyType<CecilILGenerator>(); MethodInfo[] methods = proxyType.GetMethods(); foreach (MethodInfo methodInfo in methods) { if (methodInfo.Name != "Emit") { continue; } ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 2 && (object)parameters[0].ParameterType == typeFromHandle) { System.Type parameterType = parameters[1].ParameterType; if (!_Emitters.ContainsKey(parameterType) || (object)methodInfo.DeclaringType == proxyType) { _Emitters[parameterType] = methodInfo; } } } } public static bool Init(bool forceLoad = true, Type type = Type.Auto) { //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Expected O, but got Unknown //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Expected O, but got Unknown if ((object)_HarmonyASM == null) { _HarmonyASM = _FindHarmony(); } if ((object)_HarmonyASM == null && forceLoad) { _HarmonyASM = Assembly.Load(new AssemblyName { Name = "0Harmony" }); } if ((object)_HarmonyASM == null) { return false; } if (Initialized) { return true; } Initialized = true; if (type == Type.Auto) { type = Type.AsOriginal; } DetourConfig detourConfig = default(DetourConfig); detourConfig.Priority = type switch { Type.Override => 536870911, Type.AsOriginal => -536870912, _ => 0, }; _DetourConfig = detourConfig; CurrentType = type; try { MethodInfo[] methods = typeof(HarmonyDetourBridge).GetMethods(BindingFlags.Static | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { bool flag = methodInfo.GetCustomAttributes(typeof(CriticalAttribute), inherit: false).Any(); object[] customAttributes = methodInfo.GetCustomAttributes(typeof(DetourToRDAttribute), inherit: false); for (int j = 0; j < customAttributes.Length; j++) { DetourToRDAttribute detourToRDAttribute = (DetourToRDAttribute)customAttributes[j]; foreach (MethodInfo item in GetHarmonyMethod(methodInfo, detourToRDAttribute.Type, detourToRDAttribute.SkipParams, detourToRDAttribute.Name)) { flag = false; _Detours.Add(new Hook(item, methodInfo)); } } customAttributes = methodInfo.GetCustomAttributes(typeof(DetourToHAttribute), inherit: false); for (int j = 0; j < customAttributes.Length; j++) { DetourToHAttribute detourToHAttribute = (DetourToHAttribute)customAttributes[j]; foreach (MethodInfo item2 in GetHarmonyMethod(methodInfo, detourToHAttribute.Type, detourToHAttribute.SkipParams, detourToHAttribute.Name)) { flag = false; _Detours.Add(new Detour(methodInfo, item2)); } } customAttributes = methodInfo.GetCustomAttributes(typeof(TranspileAttribute), inherit: false); for (int j = 0; j < customAttributes.Length; j++) { TranspileAttribute transpileAttribute = (TranspileAttribute)customAttributes[j]; foreach (MethodInfo item3 in GetHarmonyMethod(methodInfo, transpileAttribute.Type, -1, transpileAttribute.Name)) { DynamicMethodDefinition val = new DynamicMethodDefinition((MethodBase)item3); try { flag = false; ILContext val2 = new ILContext(val.Definition) { ReferenceBag = (IILReferenceBag)(object)RuntimeILReferenceBag.Instance }; _Detours.Add((IDisposable)val2); val2.Invoke(Extensions.CreateDelegate<Manipulator>((MethodBase)methodInfo)); if (val2.IsReadOnly) { val2.Dispose(); _Detours.Remove((IDisposable)val2); } else { _Detours.Add(new Detour(item3, val.Generate())); } } finally { ((IDisposable)val)?.Dispose(); } } } if (flag) { throw new Exception("Cannot apply HarmonyDetourBridge rule " + methodInfo.Name); } } } catch { _EarlyReset(); throw; } return true; } private static bool _EarlyReset() { foreach (IDisposable detour in _Detours) { detour.Dispose(); } _Detours.Clear(); return false; } public static void Reset() { if (Initialized) { Initialized = false; _EarlyReset(); } } private static System.Type GetHarmonyType(string typeName) { return _HarmonyASM.GetType(typeName) ?? _HarmonyASM.GetType("HarmonyLib." + typeName) ?? _HarmonyASM.GetType("Harmony." + typeName) ?? _HarmonyASM.GetType("Harmony.ILCopying." + typeName); } private static IEnumerable<MethodInfo> GetHarmonyMethod(MethodInfo ctx, string typeName, int skipParams, string name) { System.Type harmonyType = GetHarmonyType(typeName); if ((object)harmonyType == null) { return null; } if (string.IsNullOrEmpty(name)) { name = ctx.Name; } if (skipParams < 0) { return from method in harmonyType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where method.Name == name select method; } return new MethodInfo[1] { harmonyType.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, (from p in ctx.GetParameters().Skip(skipParams) select p.ParameterType).ToArray(), null) }; } private static DynamicMethodDefinition CreateDMD(MethodBase original, string suffix) { //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown if ((object)original == null) { throw new ArgumentNullException("original"); } ParameterInfo[] parameters = original.GetParameters(); System.Type[] array; if (!original.IsStatic) { array = new System.Type[parameters.Length + 1]; array[0] = Extensions.GetThisParamType(original); for (int i = 0; i < parameters.Length; i++) { array[i + 1] = parameters[i].ParameterType; } } else { array = new System.Type[parameters.Length]; for (int j = 0; j < parameters.Length; j++) { array[j] = parameters[j].ParameterType; } } return new DynamicMethodDefinition(MultiTargetShims.Replace(original.Name + suffix, "<>", "", StringComparison.Ordinal), (original as MethodInfo)?.ReturnType ?? typeof(void), array); } [DetourToRD("Memory", 0, null)] private static long GetMethodStart(MethodBase method, out Exception exception) { exception = null; try { _Detours.Add((IDisposable)new LazyDisposable<MethodBase>(method, (Action<MethodBase>)delegate(MethodBase m) { m.Unpin(); })); return (long)method.Pin().GetNativeStart(); } catch (Exception ex) { exception = ex; return 0L; } } [DetourToRD("Memory", 0, null)] [Critical] private static string WriteJump(long memory, long destination) { _Detours.Add(new NativeDetour((IntPtr)memory, (IntPtr)destination)); return null; } [DetourToRD("Memory", 0, null)] [Critical] private static string DetourMethod(MethodBase original, MethodBase replacement) { if ((object)replacement == null) { replacement = _LastWrapperDMD.Generate(); _LastWrapperDMD.Dispose(); _LastWrapperDMD = null; } _Detours.Add(new Detour(original, replacement, ref _DetourConfig)); return null; } [DetourToRD("MethodBodyReader", 1, null)] private static MethodInfo EmitMethodForType(object self, System.Type type) { foreach (KeyValuePair<System.Type, MethodInfo> emitter in _Emitters) { if ((object)emitter.Key == type) { return emitter.Value; } } foreach (KeyValuePair<System.Type, MethodInfo> emitter2 in _Emitters) { if (emitter2.Key.IsAssignableFrom(type)) { return emitter2.Value; } } return null; } [DetourToRD("PatchProcessor", 2, null)] [Critical] private static List<DynamicMethod> Patch(Func<object, List<DynamicMethod>> orig, object self) { orig(self); return new List<DynamicMethod>(); } [Transpile("PatchFunctions", null)] [Critical] private static void UpdateWrapper(ILContext il) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) ILCursor val = new ILCursor(il); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchThrow(i) }); val.Next.OpCode = OpCodes.Pop; } [Transpile("MethodPatcher", null)] [Critical] private static void CreatePatchedMethod(ILContext il) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) ILCursor val = new ILCursor(il); System.Type t_DynamicTools = GetHarmonyType("DynamicTools"); if (!val.TryGotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchCall(i, t_DynamicTools, "CreateDynamicMethod") })) { il.MakeReadOnly(); return; } val.Next.OpCode = OpCodes.Call; val.Next.Operand = il.Import((MethodBase)typeof(HarmonyDetourBridge).GetMethod("CreateDMD", BindingFlags.Static | BindingFlags.NonPublic)); int varDMDi = -1; val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchStloc(i, ref varDMDi) }); ((VariableReference)il.Body.Variables[varDMDi]).VariableType = il.Import(typeof(DynamicMethodDefinition)); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchCallvirt<DynamicMethod>(i, "GetILGenerator") }); val.Next.OpCode = OpCodes.Call; val.Next.Operand = il.Import((MethodBase)typeof(DynamicMethodDefinition).GetMethod("GetILGenerator", BindingFlags.Instance | BindingFlags.Public)); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchCall(i, t_DynamicTools, "PrepareDynamicMethod") }); val.Next.OpCode = OpCodes.Pop; val.Next.Operand = null; val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchLdloc(i, varDMDi) }); int index = val.Index; val.Index = index + 1; val.EmitDelegate<Func<DynamicMethodDefinition, DynamicMethod>>((Func<DynamicMethodDefinition, DynamicMethod>)delegate(DynamicMethodDefinition dmd) { _LastWrapperDMD = dmd; return null; }); } [DetourToRD("HarmonySharedState", 1, null)] private static Assembly SharedStateAssembly(Func<Assembly> orig) { //IL_0046: 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) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_006e: 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_0085: Expected O, but got Unknown //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown Assembly assembly = orig(); if ((object)assembly != null) { return assembly; } if ((object)_SharedStateASM != null) { return _SharedStateASM; } string text = (string)GetHarmonyType("HarmonySharedState").GetField("name", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); ModuleDefinition val = ModuleDefinition.CreateModule("MonoMod.RuntimeDetour." + text, new ModuleParameters { Kind = (ModuleKind)0, ReflectionImporterProvider = MMReflectionImporter.Provider }); try { TypeDefinition val2 = new TypeDefinition("", text, (TypeAttributes)385) { BaseType = val.TypeSystem.Object }; val.Types.Add(val2); val2.Fields.Add(new FieldDefinition("state", (FieldAttributes)22, val.ImportReference(typeof(Dictionary<MethodBase, byte[]>)))); val2.Fields.Add(new FieldDefinition("version", (FieldAttributes)22, val.ImportReference(typeof(int)))); return _SharedStateASM = ReflectionHelper.Load(val); } finally { ((IDisposable)val)?.Dispose(); } } private static Assembly _FindHarmony() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (assembly.GetName().Name == "0Harmony" || assembly.GetName().Name == "Harmony" || (object)assembly.GetType("Harmony.HarmonyInstance") != null || (object)assembly.GetType("HarmonyLib.Harmony") != null) { return assembly; } } object obj = System.Type.GetType("Harmony.HarmonyInstance", throwOnError: false, ignoreCase: false)?.Assembly; if (obj == null) { System.Type? type = System.Type.GetType("HarmonyLib.Harmony", throwOnError: false, ignoreCase: false); if ((object)type == null) { return null; } obj = type.Assembly; } return (Assembly)obj; } } public struct HookConfig { public bool ManualApply; public int Priority; public string ID; public IEnumerable<string> Before; public IEnumerable<string> After; } public class Hook : IDetour, IDisposable { public static Func<Hook, MethodBase, MethodBase, object, bool> OnDetour; public static Func<Hook, bool> OnUndo; public static Func<Hook, MethodBase, MethodBase> OnGenerateTrampoline; public readonly MethodBase Method; public readonly MethodBase Target; public readonly MethodBase TargetReal; public readonly object DelegateTarget; private Detour _Detour; private readonly Type _OrigDelegateType; private readonly MethodInfo _OrigDelegateInvoke; private int? _RefTarget; private int? _RefTrampoline; private int? _RefTrampolineTmp; public bool IsValid => _Detour.IsValid; public bool IsApplied => _Detour.IsApplied; public Detour Detour => _Detour; public Hook(MethodBase from, MethodInfo to, object target, ref HookConfig config) { //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Expected O, but got Unknown //IL_025b: Expected O, but got Unknown //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Expected O, but got Unknown //IL_0379: Expected O, but got Unknown //IL_0397: Unknown result type (might be due to invalid IL or missing references) //IL_03cd: Unknown result type (might be due to invalid IL or missing references) //IL_03e8: Unknown result type (might be due to invalid IL or missing references) //IL_03f6: Unknown result type (might be due to invalid IL or missing references) from = from.GetIdentifiable(); Method = from; Target = to; DelegateTarget = target; Type type = (from as MethodInfo)?.ReturnType ?? typeof(void); if ((object)to.ReturnType != type && !Extensions.IsCompatible(to.ReturnType, type)) { throw new InvalidOperationException($"Return type of hook for {from} doesn't match, must be {((from as MethodInfo)?.ReturnType ?? typeof(void)).FullName}"); } if (target == null && !to.IsStatic) { throw new InvalidOperationException($"Hook for method {from} must be static, or you must pass a target instance."); } ParameterInfo[] parameters = Target.GetParameters(); ParameterInfo[] parameters2 = Method.GetParameters(); Type[] array; if (!Method.IsStatic) { array = new Type[parameters2.Length + 1]; array[0] = Extensions.GetThisParamType(Method); for (int i = 0; i < parameters2.Length; i++) { array[i + 1] = parameters2[i].ParameterType; } } else { array = new Type[parameters2.Length]; for (int j = 0; j < parameters2.Length; j++) { array[j] = parameters2[j].ParameterType; } } Type type2 = null; if (parameters.Length == array.Length + 1 && typeof(Delegate).IsAssignableFrom(parameters[0].ParameterType)) { type2 = (_OrigDelegateType = parameters[0].ParameterType); } else if (parameters.Length != array.Length) { throw new InvalidOperationException($"Parameter count of hook for {from} doesn't match, must be {array.Length}"); } for (int k = 0; k < array.Length; k++) { Type type3 = array[k]; Type parameterType = parameters[k + (((object)type2 != null) ? 1 : 0)].ParameterType; if (!Extensions.IsCompatible(type3, parameterType)) { throw new InvalidOperationException($"Parameter #{k} of hook for {from} doesn't match, must be {type3.FullName} or related"); } } MethodInfo methodInfo = (_OrigDelegateInvoke = type2?.GetMethod("Invoke")); DynamicMethodDefinition val = new DynamicMethodDefinition($"Hook<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", (Method as MethodInfo)?.ReturnType ?? typeof(void), array); DynamicMethodDefinition val2 = val; DynamicMethodDefinition val3 = val; try { ILProcessor iLProcessor = val2.GetILProcessor(); if (target != null) { _RefTarget = DynamicMethodHelper.EmitReference<object>(iLProcessor, target); } if ((object)type2 != null) { _RefTrampoline = DynamicMethodHelper.EmitReference<Delegate>(iLProcessor, (Delegate)null); } for (int l = 0; l < array.Length; l++) { iLProcessor.Emit(OpCodes.Ldarg, l); } Extensions.Emit(iLProcessor, OpCodes.Call, Target); iLProcessor.Emit(OpCodes.Ret); TargetReal = val2.Generate().Pin(); } finally { ((IDisposable)val3)?.Dispose(); } if ((object)type2 != null) { ParameterInfo[] parameters3 = methodInfo.GetParameters(); Type[] array2 = new Type[parameters3.Length]; for (int m = 0; m < parameters3.Length; m++) { array2[m] = parameters3[m].ParameterType; } DynamicMethodDefinition val4 = new DynamicMethodDefinition($"Chain:TMP<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", methodInfo?.ReturnType ?? typeof(void), array2); val2 = val4; val3 = val4; try { ILProcessor iLProcessor = val2.GetILProcessor(); _RefTrampolineTmp = DynamicMethodHelper.EmitReference<Delegate>(iLProcessor, (Delegate)null); iLProcessor.Emit(OpCodes.Brfalse, iLProcessor.Body.Instructions[0]); DynamicMethodHelper.EmitGetReference<Delegate>(iLProcessor, _RefTrampolineTmp.Value); for (int n = 0; n < array.Length; n++) { iLProcessor.Emit(OpCodes.Ldarg, n); } Extensions.Emit(iLProcessor, OpCodes.Callvirt, (MethodBase)methodInfo); iLProcessor.Emit(OpCodes.Ret); DynamicMethodHelper.SetReference(_RefTrampoline.Value, (object)Extensions.CreateDelegate((MethodBase)val2.Generate(), type2)); } finally { ((IDisposable)val3)?.Dispose(); } } _Detour = new Detour(Method, TargetReal, new DetourConfig { ManualApply = true, Priority = config.Priority, ID = config.ID, Before = config.Before, After = config.After }); _UpdateOrig(null); if (!config.ManualApply) { Apply(); } } public Hook(MethodBase from, MethodInfo to, object target, HookConfig config) : this(from, to, target, ref config) { } public Hook(MethodBase from, MethodInfo to, object target) : this(from, to, target, DetourContext.Current?.HookConfig ?? default(HookConfig)) { } public Hook(MethodBase from, MethodInfo to, ref HookConfig config) : this(from, to, null, ref config) { } public Hook(MethodBase from, MethodInfo to, HookConfig config) : this(from, to, null, ref config) { } public Hook(MethodBase from, MethodInfo to) : this(from, to, null) { } public Hook(MethodBase method, IntPtr to, ref HookConfig config) : this(method, DetourHelper.GenerateNativeProxy(to, method), null, ref config) { } public Hook(MethodBase method, IntPtr to, HookConfig config) : this(method, DetourHelper.GenerateNativeProxy(to, method), null, ref config) { } public Hook(MethodBase method, IntPtr to) : this(method, DetourHelper.GenerateNativeProxy(to, method), null) { } public Hook(MethodBase method, Delegate to, ref HookConfig config) : this(method, to.Method, to.Target, ref config) { } public Hook(MethodBase method, Delegate to, HookConfig config) : this(method, to.Method, to.Target, ref config) { } public Hook(MethodBase method, Delegate to) : this(method, to.Method, to.Target) { } public Hook(Delegate from, IntPtr to, ref HookConfig config) : this(from.Method, to, ref config) { } public Hook(Delegate from, IntPtr to, HookConfig config) : this(from.Method, to, ref config) { } public Hook(Delegate from, IntPtr to) : this(from.Method, to) { } public Hook(Delegate from, Delegate to, ref HookConfig config) : this(from.Method, to, ref config) { } public Hook(Delegate from, Delegate to, HookConfig config) : this(from.Method, to, ref config) { } public Hook(Delegate from, Delegate to) : this(from.Method, to) { } public Hook(Expression from, IntPtr to, ref HookConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Hook(Expression from, IntPtr to, HookConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Hook(Expression from, IntPtr to) : this(((MethodCallExpression)from).Method, to) { } public Hook(Expression from, Delegate to, ref HookConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Hook(Expression from, Delegate to, HookConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Hook(Expression from, Delegate to) : this(((MethodCallExpression)from).Method, to) { } public Hook(Expression<Action> from, IntPtr to, ref HookConfig config) : this(from.Body, to, ref config) { } public Hook(Expression<Action> from, IntPtr to, HookConfig config) : this(from.Body, to, ref config) { } public Hook(Expression<Action> from, IntPtr to) : this(from.Body, to) { } public Hook(Expression<Action> from, Delegate to, ref HookConfig config) : this(from.Body, to, ref config) { } public Hook(Expression<Action> from, Delegate to, HookConfig config) : this(from.Body, to, ref config) { } public Hook(Expression<Action> from, Delegate to) : this(from.Body, to) { } public void Apply() { if (!IsValid) { throw new ObjectDisposedException("Hook"); } if (!IsApplied) { Func<Hook, MethodBase, MethodBase, object, bool> onDetour = OnDetour; if (onDetour != null && !Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[4] { this, Method, Target, DelegateTarget })) { return; } } _Detour.Apply(); } public void Undo() { if (!IsValid) { throw new ObjectDisposedException("Hook"); } if (IsApplied) { Func<Hook, bool> onUndo = OnUndo; if (onUndo != null && !Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) { return; } } _Detour.Undo(); if (!IsValid) { _Free(); } } public void Free() { if (IsValid) { _Detour.Free(); _Free(); } } public void Dispose() { if (IsValid) { Undo(); Free(); } } private void _Free() { if (_RefTarget.HasValue) { DynamicMethodHelper.FreeReference(_RefTarget.Value); } if (_RefTrampoline.HasValue) { DynamicMethodHelper.FreeReference(_RefTrampoline.Value); } if (_RefTrampolineTmp.HasValue) { DynamicMethodHelper.FreeReference(_RefTrampolineTmp.Value); } TargetReal.Unpin(); } public MethodBase GenerateTrampoline(MethodBase signature = null) { Func<Hook, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline; MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null); if ((object)methodBase != null) { return methodBase; } return _Detour.GenerateTrampoline(signature); } public T GenerateTrampoline<T>() where T : Delegate { if (!typeof(Delegate).IsAssignableFrom(typeof(T))) { throw new InvalidOperationException($"Type {typeof(T)} not a delegate type."); } return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T; } internal void _UpdateOrig(MethodBase invoke) { if ((object)_OrigDelegateType != null) { Delegate @delegate = Extensions.CreateDelegate(invoke ?? GenerateTrampoline(_OrigDelegateInvoke), _OrigDelegateType); DynamicMethodHelper.SetReference(_RefTrampoline.Value, (object)@delegate); DynamicMethodHelper.SetReference(_RefTrampolineTmp.Value, (object)@delegate); } } } public class Hook<T> : Hook { public Hook(Expression<Action> from, T to, ref HookConfig config) : base(from.Body, to as Delegate, ref config) { } public Hook(Expression<Action> from, T to, HookConfig config) : base(from.Body, to as Delegate, ref config) { } public Hook(Expression<Action> from, T to) : base(from.Body, to as Delegate) { } public Hook(Expression<Func<T>> from, IntPtr to, ref HookConfig config) : base(from.Body, to, ref config) { } public Hook(Expression<Func<T>> from, IntPtr to, HookConfig config) : base(from.Body, to, ref config) { } public Hook(Expression<Func<T>> from, IntPtr to) : base(from.Body, to) { } public Hook(Expression<Func<T>> from, Delegate to, ref HookConfig config) : base(from.Body, to, ref config) { } public Hook(Expression<Func<T>> from, Delegate to, HookConfig config) : base(from.Body, to, ref config) { } public Hook(Expression<Func<T>> from, Delegate to) : base(from.Body, to) { } public Hook(T from, IntPtr to, ref HookConfig config) : base(from as Delegate, to, ref config) { } public Hook(T from, IntPtr to, HookConfig config) : base(from as Delegate, to, ref config) { } public Hook(T from, IntPtr to) : base(from as Delegate, to) { } public Hook(T from, T to, ref HookConfig config) : base(from as Delegate, to as Delegate, ref config) { } public Hook(T from, T to, HookConfig config) : base(from as Delegate, to as Delegate, ref config) { } public Hook(T from, T to) : base(from as Delegate, to as Delegate) { } } public class Hook<TFrom, TTo> : Hook { public Hook(Expression<Func<TFrom>> from, TTo to, ref HookConfig config) : base(from.Body, to as Delegate) { } public Hook(Expression<Func<TFrom>> from, TTo to, HookConfig config) : base(from.Body, to as Delegate) { } public Hook(Expression<Func<TFrom>> from, TTo to) : base(from.Body, to as Delegate) { } public Hook(TFrom from, TTo to, ref HookConfig config) : base(from as Delegate, to as Delegate) { } public Hook(TFrom from, TTo to, HookConfig config) : base(from as Delegate, to as Delegate) { } public Hook(TFrom from, TTo to) : base(from as Delegate, to as Delegate) { } } public interface IDetour : IDisposable { bool IsValid { get; } bool IsApplied { get; } void Apply(); void Undo(); void Free(); MethodBase GenerateTrampoline(MethodBase signature = null); T GenerateTrampoline<T>() where T : Delegate; } public interface ISortableDetour : IDetour, IDisposable { uint GlobalIndex { get; } int Priority { get; set; } string ID { get; set; } IEnumerable<string> Before { get; set; } IEnumerable<string> After { get; set; } } public struct ILHookConfig { public bool ManualApply; public int Priority; public string ID; public IEnumerable<string> Before; public IEnumerable<string> After; } public class ILHook : ISortableDetour, IDetour, IDisposable { private class Context { public List<ILHook> Chain = new List<ILHook>(); public HashSet<ILContext> Active = new HashSet<ILContext>(); public MethodBase Method; public Detour Detour; public Context(MethodBase method) { Method = method; } public void Add(ILHook hook) { List<ILHook> chain = Chain; lock (chain) { chain.Add(hook); } } public void Remove(ILHook hook) { List<ILHook> chain = Chain; lock (chain) { chain.Remove(hook); if (chain.Count == 0) { Refresh(); lock (_Map) { _Map.Remove(Method); return; } } } } public void Refresh() { //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Expected O, but got Unknown List<ILHook> chain = Chain; lock (chain) { foreach (ILContext item in Active) { item.Dispose(); } Active.Clear(); Detour?.Dispose(); Detour = null; if (chain.Count == 0) { return; } bool flag = false; foreach (ILHook item2 in chain) { if (item2.IsApplied) { flag = true; break; } } if (!flag) { return; } DetourSorter<ILHook>.Sort(chain); DynamicMethodDefinition val = new DynamicMethodDefinition(Method); MethodBase to; try { MethodDefinition definition = val.Definition; foreach (ILHook item3 in chain) { if (item3.IsApplied) { InvokeManipulator(definition, item3.Manipulator); } } to = val.Generate(); } finally { ((IDisposable)val)?.Dispose(); } Detour = new Detour(Method, to, ref ILDetourConfig); } } private void InvokeManipulator(MethodDefinition def, Manipulator cb) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown ILContext val = new ILContext(def); val.ReferenceBag = (IILReferenceBag)(object)RuntimeILReferenceBag.Instance; val.Invoke(cb); if (val.IsReadOnly) { val.Dispose(); return; } val.MakeReadOnly(); Active.Add(val); } } public static Func<ILHook, MethodBase, Manipulator, bool> OnDetour; public static Func<ILHook, bool> OnUndo; private static DetourConfig ILDetourConfig = new DetourConfig { Priority = -268435456, Before = new string[1] { "*" } }; private static Dictionary<MethodBase, Context> _Map = new Dictionary<MethodBase, Context>(); private static uint _GlobalIndexNext = 0u; private readonly uint _GlobalIndex; private int _Priority; private string _ID; private List<string> _Before = new List<string>(); private ReadOnlyCollection<string> _BeforeRO; private List<string> _After = new List<string>(); private ReadOnlyCollection<string> _AfterRO; public readonly MethodBase Method; public readonly Manipulator Manipulator; private Context _Ctx { get { if (!_Map.TryGetValue(Method, out var value)) { return null; } return value; } } public bool IsValid => Index != -1; public bool IsApplied { get; private set; } public int Index => _Ctx?.Chain.IndexOf(this) ?? (-1); public int MaxIndex => _Ctx?.Chain.Count ?? (-1); public uint GlobalIndex => _GlobalIndex; public int Priority { get { return _Priority; } set { if (_Priority != value) { _Priority = value; _Ctx.Refresh(); } } } public string ID { get { return _ID; } set { if (string.IsNullOrEmpty(value)) { MethodInfo method = ((Delegate)(object)Manipulator).Method; value = (((object)method != null) ? Extensions.GetID((MethodBase)method, (string)null, (string)null, true, false, true) : null) ?? GetHashCode().ToString(CultureInfo.InvariantCulture); } if (!(_ID == value)) { _ID = value; _Ctx.Refresh(); } } } public IEnumerable<string> Before { get { return _BeforeRO ?? (_BeforeRO = _Before.AsReadOnly()); } set { lock (_Before) { _Before.Clear(); if (value != null) { foreach (string item in value) { _Before.Add(item); } } _Ctx.Refresh(); } } } public IEnumerable<string> After { get { return _AfterRO ?? (_AfterRO = _After.AsReadOnly()); } set { lock (_After) { _After.Clear(); if (value != null) { foreach (string item in value) { _After.Add(item); } } _Ctx.Refresh(); } } } public ILHook(MethodBase from, Manipulator manipulator, ref ILHookConfig config) { from = from.GetIdentifiable(); Method = from.Pin(); Manipulator = manipulator; _GlobalIndex = _GlobalIndexNext++; _Priority = config.Priority; _ID = config.ID; if (config.Before != null) { foreach (string item in config.Before) { _Before.Add(item); } } if (config.After != null) { foreach (string item2 in config.After) { _After.Add(item2); } } Context value; lock (_Map) { if (!_Map.TryGetValue(Method, out value)) { value = (_Map[Method] = new Context(Method)); } } lock (value) { value.Add(this); } if (!config.ManualApply) { Apply(); } } public ILHook(MethodBase from, Manipulator manipulator, ILHookConfig config) : this(from, manipulator, ref config) { } public ILHook(MethodBase from, Manipulator manipulator) : this(from, manipulator, DetourContext.Current?.ILHookConfig ?? default(ILHookConfig)) { } public void Apply() { if (!IsValid) { throw new ObjectDisposedException("ILHook"); } if (!IsApplied) { Func<ILHook, MethodBase, Manipulator, bool> onDetour = OnDetour; if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[3] { this, Method, Manipulator })) { IsApplied = true; _Ctx.Refresh(); } } } public void Undo() { if (!IsValid) { throw new ObjectDisposedException("ILHook"); } if (IsApplied) { Func<ILHook, bool> onUndo = OnUndo; if (onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) { IsApplied = false; _Ctx.Refresh(); } } } public void Free() { if (IsValid) { Undo(); _Ctx.Remove(this); Method.Unpin(); } } public void Dispose() { if (IsValid) { Undo(); Free(); } } public MethodBase GenerateTrampoline(MethodBase signature = null) { throw new NotSupportedException(); } public T GenerateTrampoline<T>() where T : Delegate { throw new NotSupportedException(); } } public struct NativeDetourConfig { public bool ManualApply; public bool SkipILCopy; } public class NativeDetour : IDetour, IDisposable { public static Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool> OnDetour; public static Func<NativeDetour, bool> OnUndo; public static Func<NativeDetour, MethodBase, MethodBase> OnGenerateTrampoline; private NativeDetourData _Data; public readonly MethodBase Method; private readonly MethodInfo _BackupMethod; private readonly IntPtr _BackupNative; private HashSet<MethodBase> _Pinned = new HashSet<MethodBase>(); public bool IsValid { get; private set; } public bool IsApplied { get; private set; } public NativeDetourData Data => _Data; public NativeDetour(MethodBase method, IntPtr from, IntPtr to, ref NativeDetourConfig config) { if (from == to) { throw new InvalidOperationException($"Cannot detour from a location to itself! (from: {from:X16} to: {to:X16} method: {method})"); } method = method?.GetIdentifiable(); Method = method; Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool> onDetour = OnDetour; if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[4] { this, method, from, to })) { IsValid = true; _Data = DetourHelper.Native.Create(from, to); if (!config.SkipILCopy) { method?.TryCreateILCopy(out _BackupMethod); } _BackupNative = DetourHelper.Native.MemAlloc(_Data.Size); if (!config.ManualApply) { Apply(); } } } public NativeDetour(MethodBase method, IntPtr from, IntPtr to, NativeDetourConfig config) : this(method, from, to, ref config) { } public NativeDetour(MethodBase method, IntPtr from, IntPtr to) : this(method, from, to, default(NativeDetourConfig)) { } public NativeDetour(IntPtr from, IntPtr to, ref NativeDetourConfig config) : this(null, from, to, ref config) { } public NativeDetour(IntPtr from, IntPtr to, NativeDetourConfig config) : this(null, from, to, ref config) { } public NativeDetour(IntPtr from, IntPtr to) : this(null, from, to) { } public NativeDetour(MethodBase from, IntPtr to, ref NativeDetourConfig config) : this(from, from.Pin().GetNativeStart(), to, ref config) { _Pinned.Add(from); } public NativeDetour(MethodBase from, IntPtr to, NativeDetourConfig config) : this(from, from.Pin().GetNativeStart(), to, ref config) { _Pinned.Add(from); } public NativeDetour(MethodBase from, IntPtr to) : this(from, from.Pin().GetNativeStart(), to) { _Pinned.Add(from); } public NativeDetour(IntPtr from, MethodBase to, ref NativeDetourConfig config) : this(from, to.Pin().GetNativeStart(), ref config) { _Pinned.Add(to); } public NativeDetour(IntPtr from, MethodBase to, NativeDetourConfig config) : this(from, to.Pin().GetNativeStart(), ref config) { _Pinned.Add(to); } public NativeDetour(IntPtr from, MethodBase to) : this(from, to.Pin().GetNativeStart()) { _Pinned.Add(to); } public NativeDetour(MethodBase from, MethodBase to, ref NativeDetourConfig config) : this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to), ref config) { _Pinned.Add(from); } public NativeDetour(MethodBase from, MethodBase to, NativeDetourConfig config) : this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to), ref config) { _Pinned.Add(from); } public NativeDetour(MethodBase from, MethodBase to) : this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to)) { _Pinned.Add(from); } public NativeDetour(Delegate from, IntPtr to, ref NativeDetourConfig config) : this(from.Method, to, ref config) { } public NativeDetour(Delegate from, IntPtr to, NativeDetourConfig config) : this(from.Method, to, ref config) { } public NativeDetour(Delegate from, IntPtr to) : this(from.Method, to) { } public NativeDetour(IntPtr from, Delegate to, ref NativeDetourConfig config) : this(from, to.Method, ref config) { } public NativeDetour(IntPtr from, Delegate to, NativeDetourConfig config) : this(from, to.Method, ref config) { } public NativeDetour(IntPtr from, Delegate to) : this(from, to.Method) { } public NativeDetour(Delegate from, Delegate to, ref NativeDetourConfig config) : this(from.Method, to.Method, ref config) { } public NativeDetour(Delegate from, Delegate to, NativeDetourConfig config) : this(from.Method, to.Method, ref config) { } public NativeDetour(Delegate from, Delegate to) : this(from.Method, to.Method) { } public void Apply() { if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } if (!IsApplied) { IsApplied = true; DetourHelper.Native.Copy(_Data.Method, _BackupNative, _Data.Type); DetourHelper.Native.MakeWritable(_Data); DetourHelper.Native.Apply(_Data); DetourHelper.Native.MakeExecutable(_Data); DetourHelper.Native.FlushICache(_Data); } } public void Undo() { if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } Func<NativeDetour, bool> onUndo = OnUndo; if ((onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) && IsApplied) { IsApplied = false; DetourHelper.Native.MakeWritable(_Data); DetourHelper.Native.Copy(_BackupNative, _Data.Method, _Data.Type); DetourHelper.Native.MakeExecutable(_Data); DetourHelper.Native.FlushICache(_Data); } } public void ChangeSource(IntPtr newSource) { if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } NativeDetourData data = _Data; _Data = DetourHelper.Native.Create(newSource, _Data.Target); IsApplied = false; Apply(); DetourHelper.Native.Free(data); } public void ChangeTarget(IntPtr newTarget) { if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } NativeDetourData data = _Data; _Data = DetourHelper.Native.Create(_Data.Method, newTarget); IsApplied = false; Apply(); DetourHelper.Native.Free(data); } public void Free() { if (!IsValid) { return; } IsValid = false; DetourHelper.Native.MemFree(_BackupNative); DetourHelper.Native.Free(_Data); if (IsApplied) { return; } foreach (MethodBase item in _Pinned) { item.Unpin(); } _Pinned.Clear(); } public void Dispose() { if (IsValid) { Undo(); Free(); } } public MethodBase GenerateTrampoline(MethodBase signature = null) { //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Expected O, but got Unknown //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Expected O, but got Unknown //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Expected O, but got Unknown //IL_0198: Expected O, but got Unknown //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Unknown result type (might be due to invalid IL or missing references) Func<NativeDetour, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline; MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null); if ((object)methodBase != null) { return methodBase; } if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } if ((object)_BackupMethod != null) { return _BackupMethod; } if ((object)signature == null) { throw new ArgumentNullException("A signature must be given if the NativeDetour doesn't hold a reference to a managed method."); } MethodBase methodBase2 = Method; if ((object)methodBase2 == null) { methodBase2 = DetourHelper.GenerateNativeProxy(_Data.Method, signature); } Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void); ParameterInfo[] parameters = signature.GetParameters(); Type[] array = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].ParameterType; } MethodBase method = Method; DynamicMethodDefinition val = new DynamicMethodDefinition(string.Format("Trampoline:Native<{0}>?{1}", (((object)method != null) ? Extensions.GetID(method, (string)null, (string)null, true, false, true) : null) ?? ((long)_Data.Method).ToString("X16", CultureInfo.InvariantCulture), GetHashCode()), type, array); try { ILProcessor iLProcessor = val.GetILProcessor(); ExceptionHandler val2 = new ExceptionHandler((ExceptionHandlerType)2); iLProcessor.Body.ExceptionHandlers.Add(val2); iLProcessor.EmitDetourCopy(_BackupNative, _Data.Method, _Data.Type); VariableDefinition val3 = null; if ((object)type != typeof(void)) { Collection<VariableDefinition> variables = iLProcessor.Body.Variables; VariableDefinition val4 = new VariableDefinition(Extensions.Import(iLProcessor, type)); val3 = val4; variables.Add(val4); } int count = iLProcessor.Body.Instructions.Count; for (int j = 0; j < array.Length; j++) { iLProcessor.Emit(OpCodes.Ldarg, j); } if (methodBase2 is MethodInfo) { Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)(MethodInfo)methodBase2); } else { if (!(methodBase2 is ConstructorInfo)) { throw new NotSupportedException("Method type " + methodBase2.GetType().FullName + " not supported."); } Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)(ConstructorInfo)methodBase2); } if (val3 != null) { iLProcessor.Emit(OpCodes.Stloc, val3); } Extensions.Emit(iLProcessor, OpCodes.Leave, (object)null); Instruction obj = iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1]; int count2 = iLProcessor.Body.Instructions.Count; _ = iLProcessor.Body.Instructions.Count; iLProcessor.EmitDetourApply(_Data); int count3 = iLProcessor.Body.Instructions.Count; Instruction val5 = null; if (val3 != null) { iLProcessor.Emit(OpCodes.Ldloc, val3); val5 = iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1]; } iLProcessor.Emit(OpCodes.Ret); val5 = val5 ?? iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1]; obj.Operand = val5; val2.TryStart = iLProcessor.Body.Instructions[count]; val2.TryEnd = iLProcessor.Body.Instructions[count2]; val2.HandlerStart = iLProcessor.Body.Instructions[count2]; val2.HandlerEnd = iLProcessor.Body.Instructions[count3]; return val.Generate(); } finally { ((IDisposable)val)?.Dispose(); } } public T GenerateTrampoline<T>() where T : Delegate { if (!typeof(Delegate).IsAssignableFrom(typeof(T))) { throw new InvalidOperationException($"Type {typeof(T)} not a delegate type."); } return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T; } } internal static class DetourSorter<T> where T : ISortableDetour { private sealed class Group { public readonly string StepName; public List<T> Items = new List<T>(); public List<Group> Children = new List<Group>(); public List<Group> NonMatching = new List<Group>(); public Group(string stepName) { StepName = stepName; } public Group(string stepName, List<T> items) : this(stepName) { Items.AddRange(items); } public void Step(Step step) { if (Children.Count != 0) { foreach (Group child in Children) { child.Step(step); } return; } if (Items.Count <= 1) { return; } if ((Items.Count == 2 && !((!step.IsFlat) ?? false)) || step.IsFlat.GetValueOrDefault()) { Items.Sort(step); return; } string name = step.GetType().Name; Group group = new Group(name, new List<T> { Items[0] }); Children.Add(group); for (int i = 1; i < Items.Count; i++) { T val = Items[i]; if (step.Any(group.Items, val)) { Group group2 = group; group = null; if (Children.Count > 1) { foreach (Group child2 in Children) { if (child2 != group2 && !step.Any(child2.Items, val) && !step.Any(child2.NonMatching, val)) { group = child2; break; } } } if (group == null) { group = new Group(name); Children.Add(group); group.NonMatching.Add(group2); group2.NonMatching.Add(group); } } group.Items.Add(val); } if (Children.Count == 1) { Children.Clear(); } else { Children.Sort(step.ForGroup); } } public void Flatten() { if (Children.Count != 0) { Items.Clear(); Flatten(Items); } } public void Flatten(List<T> total) { if (Children.Count == 0) { total.AddRange(Items); return; } foreach (Group child in Children) { child.Flatten(total); } } } private abstract class Step : IComparer<T> { public abstract GroupComparer ForGroup { get; } public virtual bool? IsFlat => null; public abstract int Compare(T x, T y); public bool Any(List<T> xlist, T y) { foreach (T item in xlist) { if (Compare(item, y) != 0) { return true; } } return false; } public bool Any(List<Group> groups, T y) { foreach (Group group in groups) { if (Any(group.Items, y)) { return true; } } return false; } } private sealed class GroupComparer : IComparer<Group> { public Step Step; public GroupComparer(Step step) { Step = step; } public int Compare(Group xg, Group yg) { foreach (T item in xg.Items) { foreach (T item2 in yg.Items) { int result; if ((result = Step.Compare(item, item2)) != 0) { return result; } } } return 0; } } private sealed class BeforeAfterAll : Step { public static readonly BeforeAfterAll _ = new BeforeAfterAll(); public static readonly GroupComparer Group = new GroupComparer(_); public override GroupComparer ForGroup => Group; public override bool? IsFlat => false; public override int Compare(T a, T b) { if (a.Before.Contains("*") && !b.Before.Contains("*")) { return -1; } if (!a.Before.Contains("*") && b.Before.Contains("*")) { return 1; } if (a.After.Contains("*") && !b.After.Contains("*")) { return 1; } if (!a.After.Contains("*") && b.After.Contains("*")) { return -1; } return 0; } } private sealed class BeforeAfter : Step { public static readonly BeforeAfter _ = new BeforeAfter(); public static readonly GroupComparer Group = new GroupComparer(_); public override GroupComparer ForGroup => Group; public override int Compare(T a, T b) { if (a.Before.Contains(b.ID)) { return -1; } if (a.After.Contains(b.ID)) { return 1; } if (b.Before.Contains(a.ID)) { return 1; } if (b.After.Contains(a.ID)) { return -1; } return 0; } } private sealed class Priority : Step { public static readonly Priority _ = new Priority(); public static readonly GroupComparer Group = new GroupComparer(_); public override GroupComparer ForGroup => Group; public override int Compare(T a, T b) { int num = a.Priority - b.Priority; if (num != 0) { return num; } return 0; } } private sealed class GlobalIndex : Step { public static readonly GlobalIndex _ = new GlobalIndex(); public static readonly GroupComparer Group = new GroupComparer(_); public override GroupComparer ForGroup => Group; public override int Compare(T a, T b) { return a.GlobalIndex.CompareTo(b.GlobalIndex); } } public static void Sort(List<T> detours) { lock (detours) { if (detours.Count > 1) { detours.Sort(GlobalIndex._); Group group = new Group("Init", detours); group.Step(BeforeAfterAll._); group.Step(BeforeAfter._); group.Step(Priority._); group.Step(GlobalIndex._); detours.Clear(); group.Flatten(detours); } } } } public static class DetourHelper { private static readonly object _RuntimeLock = new object(); private static bool _RuntimeInit = false; private static IDetourRuntimePlatform _Runtime; private static readonly object _NativeLock = new object(); private static bool _NativeInit = false; private static IDetourNativePlatform _Native; private static readonly FieldInfo _f_Native = typeof(DetourHelper).GetField("_Native", BindingFlags.Static | BindingFlags.NonPublic); private static readonly MethodInfo _m_ToNativeDetourData = typeof(DetourHelper).GetMethod("ToNativeDetourData", BindingFlags.Static | BindingFlags.NonPublic); private static readonly MethodInfo _m_Copy = typeof(IDetourNativePlatform).GetMethod("Copy"); private static readonly MethodInfo _m_Apply = typeof(IDetourNativePlatform).GetMethod("Apply"); private static readonly ConstructorInfo _ctor_Exception = typeof(Exception).GetConstructor(new Type[1] { typeof(string) }); public static IDetourRuntimePlatform Runtime { get { if (_Runtime != null) { return _Runtime; } lock (_RuntimeLock) { if (_Runtime != null) { return _Runtime; } if (_RuntimeInit) { return null; } _RuntimeInit = true; if ((object)Type.GetType("Mono.Runtime") != null) { _Runtime = new DetourRuntimeMonoPlatform(); } else if (typeof(object).Assembly.GetName().Name == "System.Private.CoreLib") { _Runtime = DetourRuntimeNETCorePlatform.Create(); } else { _Runtime = new DetourRuntimeNETPlatform(); } return _Runtime; } } set { _Runtime = value; } } public static IDetourNativePlatform Native { get { if (_Native != null) { return _Native; } lock (_NativeLock) { if (_Native != null) { return _Native; } if (_NativeInit) { return null; } _NativeInit = true; IDetourNativePlatform detourNativePlatform = ((!PlatformHelper.Is((Platform)65536)) ? ((IDetourNativePlatform)new DetourNativeX86Platform()) : ((IDetourNativePlatform)new DetourNativeARMPlatform())); if (PlatformHelper.Is((Platform)37)) { return _Native = new DetourNativeWindowsPlatform(detourNativePlatform); } if ((object)Type.GetType("Mono.Runtime") != null) { try { return _Native = new DetourNativeMonoPlatform(detourNativePlatform, "libmonosgen-2.0." + PlatformHelper.LibrarySuffix); } catch { } } string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_RUNTIMEDETOUR_MONOPOSIXHELPER"); if (((object)Type.GetType("Mono.Runtime") != null && environmentVariable != "0") || environmentVariable == "1") { try { return _Native = new DetourNativeMonoPosixPlatform(detourNativePlatform); } catch { } } try { return _Native = new DetourNativeLibcPlatform(detourNativePlatform); } catch { } return detourNativePlatform; } } set { _Native = value; } } public static void MakeWritable(this IDetourNativePlatform plat, NativeDetourData detour) { plat.MakeWritable(detour.Method, detour.Size); } public static void MakeExecutable(this IDetourNativePlatform plat, NativeDetourData detour) { plat.MakeExecutable(detour.Method, detour.Size); } public static void FlushICache(this IDetourNativePlatform plat, NativeDetourData detour) { plat.FlushICache(detour.Method, detour.Size); } public unsafe static void Write(this IntPtr to, ref int offs, byte value) { *(byte*)((long)to + offs) = value; offs++; } public unsafe static void Write(this IntPtr to, ref int offs, ushort value) { *(ushort*)((long)to + offs) = value; offs += 2; } public unsafe static void Write(this IntPtr to, ref int offs, uint value) { *(uint*)((long)to + offs) = value; offs += 4; } public unsafe static void Write(this IntPtr to, ref int offs, ulong value) { *(ulong*)((long)to + offs) = value; offs += 8; } public static MethodBase GetIdentifiable(this MethodBase method) { return Runtime.GetIdentifiable(method); } public static IntPtr GetNativeStart(this MethodBase method) { return Runtime.GetNativeStart(method); } public static IntPtr GetNativeStart(this Delegate method) { return method.Method.GetNativeStart(); } public static IntPtr GetNativeStart(this Expression method) { return ((MethodCallExpression)method).Method.GetNativeStart(); } public static MethodInfo CreateILCopy(this MethodBase method) { return Runtime.CreateCopy(method); } public static bool TryCreateILCopy(this MethodBase method, out MethodInfo dm) { return Runtime.TryCreateCopy(method, out dm); } public static T Pin<T>(this T method) where T : MethodBase { Runtime.Pin(method); return method; } public static T Unpin<T>(this T method) where T : MethodBase { Runtime.Unpin(method); return method; } public static MethodInfo GenerateNativeProxy(IntPtr target, MethodBase signature) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void); ParameterInfo[] parameters = signature.GetParameters(); Type[] array = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].ParameterType; } DynamicMethodDefinition val = new DynamicMethodDefinition("Native<" + ((long)target).ToString("X16", CultureInfo.InvariantCulture) + ">", type, array); MethodInfo methodInfo; try { methodInfo = val.StubCriticalDetour().Generate().Pin(); } finally { ((IDisposable)val)?.Dispose(); } NativeDetourData detour = Native.Create(methodInfo.GetNativeStart(), target); Native.MakeWritable(detour); Native.Apply(detour); Native.MakeExecutable(detour); Native.FlushICache(detour); Native.Free(detour); return methodInfo; } private static NativeDetourData ToNativeDetourData(IntPtr method, IntPtr target, uint size, byte type, IntPtr extra) { NativeDetourData result = default(NativeDetourData); result.Method = method; result.Target = target; result.Size = size; result.Type = type; result.Extra = extra; return result; } public static DynamicMethodDefinition StubCriticalDetour(this DynamicMethodDefinition dm) { //IL_001d: 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) //IL_0051: 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) ILProcessor iLProcessor = dm.GetILProcessor(); ModuleDefinition module = ((MemberReference)iLProcessor.Body.Method).Module; for (int i = 0; i < 32; i++) { iLProcessor.Emit(OpCodes.Nop); } iLProcessor.Emit(OpCodes.Ldstr, ((MemberReference)dm.Definition).Name + " should've been detoured!"); iLProcessor.Emit(OpCodes.Newobj, module.ImportReference((MethodBase)_ctor_Exception)); iLProcessor.Emit(OpCodes.Throw); return dm; } public static void EmitDetourCopy(this ILProcessor il, IntPtr src, IntPtr dst, byte type) { //IL_0012: 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_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0044: 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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) ModuleDefinition module = ((MemberReference)il.Body.Method).Module; il.Emit(OpCodes.Ldsfld, module.ImportReference(_f_Native)); il.Emit(OpCodes.Ldc_I8, (long)src); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Ldc_I8, (long)dst); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Ldc_I4, (int)type); il.Emit(OpCodes.Conv_U1); il.Emit(OpCodes.Callvirt, module.ImportReference((MethodBase)_m_Copy)); } public static void EmitDetourApply(this ILProcessor il, NativeDetourData data) { //IL_0012: 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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0049: 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_006a: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) ModuleDefinition module = ((MemberReference)il.Body.Method).Module; il.Emit(OpCodes.Ldsfld, module.ImportReference(_f_Native)); il.Emit(OpCodes.Ldc_I8, (long)data.Method); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Ldc_I8, (long)data.Target); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Ldc_I4, (int)data.Size); il.Emit(OpCodes.Ldc_I4, (int)data.Type); il.Emit(OpCodes.Conv_U1); il.Emit(OpCodes.Ldc_I8, (long)data.Extra); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Call, module.ImportReference((MethodBase)_m_ToNativeDetourData)); il.Emit(OpCodes.Callvirt, module.ImportReference((MethodBase)_m_Apply)); } } public interface IDetourNativePlatform { NativeDetourData Create(IntPtr from, IntPtr to, byte? type = null); void Free(NativeDetourData detour); void Apply(NativeDetourData detour); void Copy(IntPtr src, IntPtr dst, byte type); void MakeWritable(IntPtr src, uint size); void MakeExecutable(IntPtr src, uint size); void MakeReadWriteExecutable(IntPtr src, uint size); void FlushICache(IntPtr src, uint size); IntPtr MemAlloc(uint size); void MemFree(IntPtr ptr); } public interface IDetourRuntimePlatform { bool OnMethodCompiledWillBeCalled { get; } event OnMethodCompiledEvent OnMethodCompiled; MethodBase GetIdentifiable(MethodBase method); IntPtr GetNativeStart(MethodBase method); MethodInfo CreateCopy(MethodBase method); bool TryCreateCopy(MethodBase method, out MethodInfo dm); void Pin(MethodBase method); void Unpin(MethodBase method); MethodBase GetDetourTarget(MethodBase from, MethodBase to); uint TryMemAllocScratchCloseTo(IntPtr target, out IntPtr ptr, int size); } public delegate void OnMethodCompiledEvent(MethodBase method, IntPtr codeStart, ulong codeSize); public struct NativeDetourData { public IntPtr Method; public IntPtr Target; public byte Type; public uint Size; public IntPtr Extra; } } namespace MonoMod.RuntimeDetour.Platforms { public class DetourNativeARMPlatform : IDetourNativePlatform { public enum DetourType : byte { Thumb, ThumbBX, AArch32, AArch32BX, AArch64 } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int d_flushicache(IntPtr code, ulong size); private static readonly uint[] DetourSizes = new uint[5] { 8u, 12u, 8u, 12u, 16u }; public bool ShouldFlushICache = true; private readonly byte[] _FlushCache32 = new byte[44] { 128, 64, 45, 233, 0, 48, 160, 225, 1, 192, 128, 224, 20, 224, 159, 229, 3, 0, 160, 225, 12, 16, 160, 225, 14, 112, 160, 225, 0, 32, 160, 227, 0, 0, 0, 239, 128, 128, 189, 232, 2, 0, 15, 0 }; private readonly byte[] _FlushCache64 = new byte[76] { 1, 0, 1, 139, 0, 244, 126, 146, 63, 0, 0, 235, 201, 0, 0, 84, 226, 3, 0, 170, 34, 126, 11, 213, 66, 16, 0, 145, 63, 0, 2, 235, 168, 255, 255, 84, 159, 59, 3, 213, 63, 0, 0, 235, 169, 0, 0, 84, 32, 117, 11, 213, 0, 16, 0, 145, 63, 0, 0, 235, 168, 255, 255, 84, 159, 59, 3, 213, 223, 63, 3, 213, 192, 3, 95, 214 }; private static DetourType GetDetourType(IntPtr from, IntPtr to) { if (IntPtr.Size >= 8) { return DetourType.AArch64; } bool num = ((long)from & 1) == 1; bool flag = ((long)to & 1) == 1; if (num) { if (flag) { return DetourType.Thumb; } return DetourType.ThumbBX; } if (flag) { return DetourType.AArch32BX; } return DetourType.AArch32; } public NativeDetourData Create(IntPtr from, IntPtr to, byte? type) { NativeDetourData nativeDetourData = default(NativeDetourData); nativeDetourData.Method = (IntPtr)((long)from & -2); nativeDetourData.Target = (IntPtr)((long)to & -2); NativeDetourData result = nativeDetourData; uint[] detourSizes = DetourSizes; int num = ((int?)type) ?? ((int)GetDetourType(from, to)); byte b = (byte)num; result.Type = (byte)num; result.Size = detourSizes[b]; return result; } public void Free(NativeDetourData detour) { } public void Apply(NativeDetourData detour) { int offs = 0; switch ((DetourType)detour.Type) { case DetourType.Thumb: detour.Method.Write(ref offs, 223); detour.Method.Write(ref offs, 248); detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 240); detour.Method.Write(ref offs, (uint)(int)detour.Target | 1u); break; case DetourType.ThumbBX: detour.Method.Write(ref offs, 223); detour.Method.Write(ref offs, 248); detour.Method.Write(ref offs, 4); detour.Method.Write(ref offs, 160); detour.Method.Write(ref offs, 80); detour.Method.Write(ref offs, 71); detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 191); detour.Method.Write(ref offs, (uint)(int)detour.Target | 0u); break; case DetourType.AArch32: detour.Method.Write(ref offs, 4); detour.Method.Write(ref offs, 240); detour.Method.Write(ref offs, 31); detour.Method.Write(ref offs, 229); detour.Method.Write(ref offs, (uint)(int)detour.Target | 0u); break; case DetourType.AArch32BX: detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 128); detour.Method.Write(ref offs, 159); detour.Method.Write(ref offs, 229); detour.Method.Write(ref offs, 24); detour.Method.Write(ref offs, byte.MaxValue); detour.Method.Write(ref offs, 47); detour.Method.Write(ref offs, 225); detour.Method.Write(ref offs, (uint)(int)detour.Target | 1u); break; case DetourType.AArch64: detour.Method.Write(ref offs, 79); detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 88); detour.Method.Write(ref offs, 224); detour.Method.Write(ref offs, 1); detour.Method.Write(ref offs, 31); detour.Method.Write(ref offs, 214); detour.Method.Write(ref offs, (ulong)(long)detour.Target); break; default: throw new NotSupportedException($"Unknown detour type {detour.Type}"); } } public unsafe void Copy(IntPtr src, IntPtr dst, byte type) { switch ((DetourType)type) { case DetourType.Thumb: *(int*)(long)dst = *(int*)(long)src; *(int*)((long)dst + 4) = *(int*)((long)src + 4); break; case DetourType.ThumbBX: *(int*)(long)dst = *(int*)(long)src; *(short*)((long)dst + 4) = *(short*)((long)src + 4); *(short*)((long)dst + 6) = *(short*)((long)src + 6); *(int*)((long)dst + 8) = *(int*)((long)src + 8); break; case DetourType.AArch32: *(int*)(long)dst = *(int*)(long)src; *(int*)((long)dst + 4) = *(int*)((long)src + 4); break; case DetourType.AArch32BX: *(int*)(long)dst = *(int*)(long)src; *(int*)((long)dst + 4) = *(int*)((long)src + 4); *(int*)((long)dst + 8) = *(int*)((long)src + 8); break; case DetourType.AArch64: *(int*)(long)dst = *(int*)(long)src; *(int*)((long)dst + 4) = *(int*)((long)src + 4); *(long*)((long)dst + 8) = *(long*)((long)src + 8); break; default: throw new NotSupportedException($"Unknown detour type {type}"); } } public void MakeWritable(IntPtr src, uint size) { } public void MakeExecutable(IntPtr src, uint size) { } public void MakeReadWriteExecutable(IntPtr src, uint size) { } public unsafe void FlushICache(IntPtr src, uint size) { if (ShouldFlushICache) { byte[] array = ((IntPtr.Size >= 8) ? _FlushCache64 : _FlushCache32); fixed (byte* ptr = array) { DetourHelper.Native.MakeExecutable((IntPtr)ptr, (uint)array.Length); (Marshal.GetDelegateForFunctionPointer((IntPtr)ptr, typeof(d_flushicache)) as d_flushicache)(src, size); } } } public IntPtr MemAlloc(uint size) { return Marshal.AllocHGlobal((int)size); } public void MemFree(IntPtr ptr) { Marshal.FreeHGlobal(ptr); } } public class DetourNativeLibcPlatform : IDetourNativePlatform { [Flags] private enum MmapProts { PROT_READ = 1, PROT_WRITE = 2, PROT_EXEC = 4, PROT_NONE = 0, PROT_GROWSDOWN = 0x1000000, PROT_GROWSUP = 0x2000000 } private readonly IDetourNativePlatform Inner; private readonly long _Pagesize; public DetourNativeLibcPlatform(IDetourNativePlatform inner) { Inner = inner; PropertyInfo property = typeof(Environment).GetProperty("SystemPageSize"); if ((object)property == null) { throw new NotSupportedException("Unsupported runtime"); } _Pagesize = (int)property.GetValue(null, new object[0]); } private void SetMemPerms(IntPtr start, ulong len, MmapProts prot) { long pagesize = _Pagesize; long num = (long)start & ~(pagesize - 1); long num2 = ((long)start + (long)len + pagesize - 1) & ~(pagesize - 1); if (mprotect((IntPtr)num, (IntPtr)(num2 - num), prot) != 0) { throw new Win32Exception(); } } public void MakeWritable(IntPtr src, uint size) { SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC); } public void MakeExecutable(IntPtr src, uint size) { SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC); } public void MakeReadWriteExecutable(IntPtr
UMM/Mods/Runtime Unity Editor/MonoMod.Utils.dll
Decompiled a month 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.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.SymbolStore; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Utils; using MonoMod.Utils.Cil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("MonoMod.Utils.Cil.ILGeneratorProxy")] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021 0x0ade")] [assembly: AssemblyDescription("Utilities and smaller MonoMod \"components\" (f.e. ModInterop, DynDll, DynData). Can be used for your own mods. Required by all other MonoMod components.")] [assembly: AssemblyFileVersion("21.11.1.1")] [assembly: AssemblyInformationalVersion("21.11.01.01")] [assembly: AssemblyProduct("MonoMod.Utils")] [assembly: AssemblyTitle("MonoMod.Utils")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("21.11.1.1")] [module: UnverifiableCode] internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison) { return self.Replace(oldValue, newValue); } public static bool Contains(this string self, string value, StringComparison comparison) { return self.Contains(value); } public static int GetHashCode(this string self, StringComparison comparison) { return self.GetHashCode(); } public static int IndexOf(this string self, char value, StringComparison comparison) { return self.IndexOf(value); } public static int IndexOf(this string self, string value, StringComparison comparison) { return self.IndexOf(value); } public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class IgnoresAccessChecksToAttribute : Attribute { public string AssemblyName { get; } public IgnoresAccessChecksToAttribute(string assemblyName) { AssemblyName = assemblyName; } } } namespace MonoMod { internal static class MMDbgLog { public static readonly string Tag; public static TextWriter Writer; public static bool Debugging; static MMDbgLog() { Tag = typeof(MMDbgLog).Assembly.GetName().Name; if (!(Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1")) { string? environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG"); bool? obj; if (environmentVariable == null) { obj = null; } else { string text = environmentVariable.ToLower(CultureInfo.InvariantCulture); obj = ((text != null) ? new bool?(MultiTargetShims.Contains(text, Tag.ToLower(CultureInfo.InvariantCulture), StringComparison.Ordinal)) : null); } bool? flag = obj; if (!flag.GetValueOrDefault()) { return; } } Start(); } public static void WaitForDebugger() { if (!Debugging) { Debugging = true; Debugger.Launch(); Thread.Sleep(6000); Debugger.Break(); } } public static void Start() { if (Writer != null) { return; } string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH"); if (text == "-") { Writer = Console.Out; return; } if (string.IsNullOrEmpty(text)) { text = "mmdbglog.txt"; } text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text)); try { if (File.Exists(text)) { File.Delete(text); } } catch { } try { string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8); } catch { } } public static void Log(string str) { TextWriter writer = Writer; if (writer != null) { writer.WriteLine(str); writer.Flush(); } } public static T Log<T>(string str, T value) { TextWriter writer = Writer; if (writer == null) { return value; } writer.WriteLine(string.Format(CultureInfo.InvariantCulture, str, new object[1] { value })); writer.Flush(); return value; } } } namespace MonoMod.ModInterop { [AttributeUsage(AttributeTargets.Class)] public sealed class ModExportNameAttribute : Attribute { public string Name; public ModExportNameAttribute(string name) { Name = name; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field)] public sealed class ModImportNameAttribute : Attribute { public string Name; public ModImportNameAttribute(string name) { Name = name; } } public static class ModInteropManager { private static HashSet<Type> Registered = new HashSet<Type>(); private static Dictionary<string, List<MethodInfo>> Methods = new Dictionary<string, List<MethodInfo>>(); private static List<FieldInfo> Fields = new List<FieldInfo>(); public static void ModInterop(this Type type) { if (Registered.Contains(type)) { return; } Registered.Add(type); string name = type.Assembly.GetName().Name; object[] customAttributes = type.GetCustomAttributes(typeof(ModExportNameAttribute), inherit: false); for (int i = 0; i < customAttributes.Length; i++) { name = ((ModExportNameAttribute)customAttributes[i]).Name; } FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { if (typeof(Delegate).IsAssignableFrom(fieldInfo.FieldType)) { Fields.Add(fieldInfo); } } MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo method in methods) { method.RegisterModExport(); method.RegisterModExport(name); } foreach (FieldInfo field in Fields) { if (!Methods.TryGetValue(field.GetModImportName(), out var value)) { field.SetValue(null, null); continue; } bool flag = false; foreach (MethodInfo item in value) { try { field.SetValue(null, Delegate.CreateDelegate(field.FieldType, null, item)); flag = true; } catch { continue; } break; } if (!flag) { field.SetValue(null, null); } } } public static void RegisterModExport(this MethodInfo method, string prefix = null) { if (!method.IsPublic || !method.IsStatic) { throw new MemberAccessException("Utility must be public static"); } string text = method.Name; if (!string.IsNullOrEmpty(prefix)) { text = prefix + "." + text; } if (!Methods.TryGetValue(text, out var value)) { value = (Methods[text] = new List<MethodInfo>()); } if (!value.Contains(method)) { value.Add(method); } } private static string GetModImportName(this FieldInfo field) { object[] customAttributes = field.GetCustomAttributes(typeof(ModImportNameAttribute), inherit: false); int num = 0; if (num < customAttributes.Length) { return ((ModImportNameAttribute)customAttributes[num]).Name; } customAttributes = field.DeclaringType.GetCustomAttributes(typeof(ModImportNameAttribute), inherit: false); num = 0; if (num < customAttributes.Length) { return ((ModImportNameAttribute)customAttributes[num]).Name + "." + field.Name; } return field.Name; } } } namespace MonoMod.Utils { public sealed class DynData<TTarget> : IDisposable where TTarget : class { private class _Data_ : IDisposable { public readonly Dictionary<string, Func<TTarget, object>> Getters = new Dictionary<string, Func<TTarget, object>>(); public readonly Dictionary<string, Action<TTarget, object>> Setters = new Dictionary<string, Action<TTarget, object>>(); public readonly Dictionary<string, object> Data = new Dictionary<string, object>(); public readonly HashSet<string> Disposable = new HashSet<string>(); ~_Data_() { Dispose(); } public void Dispose() { lock (Data) { if (Data.Count == 0) { return; } foreach (string item in Disposable) { if (Data.TryGetValue(item, out var value) && value is IDisposable disposable) { disposable.Dispose(); } } Disposable.Clear(); Data.Clear(); } } } private static int CreationsInProgress; private static readonly object[] _NoArgs; private static readonly _Data_ _DataStatic; private static readonly Dictionary<WeakReference, _Data_> _DataMap; private static readonly HashSet<WeakReference> _DataMapDead; private static readonly Dictionary<string, Func<TTarget, object>> _SpecialGetters; private static readonly Dictionary<string, Action<TTarget, object>> _SpecialSetters; private readonly WeakReference Weak; private TTarget KeepAlive; private readonly _Data_ _Data; public Dictionary<string, Func<TTarget, object>> Getters => _Data.Getters; public Dictionary<string, Action<TTarget, object>> Setters => _Data.Setters; public Dictionary<string, object> Data => _Data.Data; public bool IsAlive { get { if (Weak != null) { return Weak.SafeGetIsAlive(); } return true; } } public TTarget Target => Weak?.SafeGetTarget() as TTarget; public object this[string name] { get { if (_SpecialGetters.TryGetValue(name, out var value) || Getters.TryGetValue(name, out value)) { return value(Weak?.SafeGetTarget() as TTarget); } if (Data.TryGetValue(name, out var value2)) { return value2; } return null; } set { if (_SpecialSetters.TryGetValue(name, out var value2) || Setters.TryGetValue(name, out value2)) { value2(Weak?.SafeGetTarget() as TTarget, value); return; } object obj; if (_Data.Disposable.Contains(name) && (obj = this[name]) != null && obj is IDisposable disposable) { disposable.Dispose(); } Data[name] = value; } } public static event Action<DynData<TTarget>, TTarget> OnInitialize; static DynData() { CreationsInProgress = 0; _NoArgs = new object[0]; _DataStatic = new _Data_(); _DataMap = new Dictionary<WeakReference, _Data_>(new WeakReferenceComparer()); _DataMapDead = new HashSet<WeakReference>(); _SpecialGetters = new Dictionary<string, Func<TTarget, object>>(); _SpecialSetters = new Dictionary<string, Action<TTarget, object>>(); GCListener.OnCollect += delegate { if (CreationsInProgress != 0) { return; } lock (_DataMap) { foreach (KeyValuePair<WeakReference, _Data_> item in _DataMap) { if (!item.Key.SafeGetIsAlive()) { _DataMapDead.Add(item.Key); item.Value.Dispose(); } } foreach (WeakReference item2 in _DataMapDead) { _DataMap.Remove(item2); } _DataMapDead.Clear(); } }; FieldInfo[] fields = typeof(TTarget).GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo field in fields) { string name = field.Name; _SpecialGetters[name] = (TTarget obj) => field.GetValue(obj); _SpecialSetters[name] = delegate(TTarget obj, object value) { field.SetValue(obj, value); }; } PropertyInfo[] properties = typeof(TTarget).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (PropertyInfo propertyInfo in properties) { string name2 = propertyInfo.Name; MethodInfo get = propertyInfo.GetGetMethod(nonPublic: true); if ((object)get != null) { _SpecialGetters[name2] = (TTarget obj) => get.Invoke(obj, _NoArgs); } MethodInfo set = propertyInfo.GetSetMethod(nonPublic: true); if ((object)set != null) { _SpecialSetters[name2] = delegate(TTarget obj, object value) { set.Invoke(obj, new object[1] { value }); }; } } } public DynData() : this((TTarget)null, keepAlive: false) { } public DynData(TTarget obj) : this(obj, keepAlive: true) { } public DynData(TTarget obj, bool keepAlive) { if (obj != null) { WeakReference weakReference = new WeakReference(obj); WeakReference key = weakReference; CreationsInProgress++; lock (_DataMap) { if (!_DataMap.TryGetValue(key, out _Data)) { _Data = new _Data_(); _DataMap.Add(key, _Data); } } CreationsInProgress--; Weak = weakReference; if (keepAlive) { KeepAlive = obj; } } else { _Data = _DataStatic; } DynData<TTarget>.OnInitialize?.Invoke(this, obj); } public T Get<T>(string name) { return (T)this[name]; } public void Set<T>(string name, T value) { this[name] = value; } public void RegisterProperty(string name, Func<TTarget, object> getter, Action<TTarget, object> setter) { Getters[name] = getter; Setters[name] = setter; } public void UnregisterProperty(string name) { Getters.Remove(name); Setters.Remove(name); } private void Dispose(bool disposing) { KeepAlive = null; } ~DynData() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public static class Extensions { private static readonly Type t_StateMachineAttribute = typeof(object).Assembly.GetType("System.Runtime.CompilerServices.StateMachineAttribute"); private static readonly PropertyInfo p_StateMachineType = t_StateMachineAttribute?.GetProperty("StateMachineType"); private static readonly Type t_Code = typeof(Code); private static readonly Type t_OpCodes = typeof(OpCodes); private static readonly Dictionary<int, OpCode> _ToLongOp = new Dictionary<int, OpCode>(); private static readonly Dictionary<int, OpCode> _ToShortOp = new Dictionary<int, OpCode>(); private static readonly object[] _NoArgs = new object[0]; private static readonly Dictionary<Type, FieldInfo> fmap_mono_assembly = new Dictionary<Type, FieldInfo>(); private static readonly bool _MonoAssemblyNameHasArch = new AssemblyName("Dummy, ProcessorArchitecture=MSIL").ProcessorArchitecture == ProcessorArchitecture.MSIL; private static readonly Type _RTDynamicMethod = typeof(DynamicMethod).GetNestedType("RTDynamicMethod", BindingFlags.Public | BindingFlags.NonPublic); private static readonly Type t_ParamArrayAttribute = typeof(ParamArrayAttribute); private static readonly FieldInfo f_GenericParameter_position = typeof(GenericParameter).GetField("position", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly FieldInfo f_GenericParameter_type = typeof(GenericParameter).GetField("type", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly Dictionary<Type, int> _GetManagedSizeCache = new Dictionary<Type, int> { { typeof(void), 0 } }; private static MethodInfo _GetManagedSizeHelper; private static readonly Dictionary<MethodBase, Func<IntPtr>> _GetLdftnPointerCache = new Dictionary<MethodBase, Func<IntPtr>>(); public static string ToHexadecimalString(this byte[] data) { return MultiTargetShims.Replace(BitConverter.ToString(data), "-", string.Empty, StringComparison.Ordinal); } public static T InvokePassing<T>(this MulticastDelegate md, T val, params object[] args) { if ((object)md == null) { return val; } object[] array = new object[args.Length + 1]; array[0] = val; Array.Copy(args, 0, array, 1, args.Length); Delegate[] invocationList = md.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { array[0] = invocationList[i].DynamicInvoke(array); } return (T)array[0]; } public static bool InvokeWhileTrue(this MulticastDelegate md, params object[] args) { if ((object)md == null) { return true; } Delegate[] invocationList = md.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { if (!(bool)invocationList[i].DynamicInvoke(args)) { return false; } } return true; } public static bool InvokeWhileFalse(this MulticastDelegate md, params object[] args) { if ((object)md == null) { return false; } Delegate[] invocationList = md.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { if ((bool)invocationList[i].DynamicInvoke(args)) { return true; } } return false; } public static T InvokeWhileNull<T>(this MulticastDelegate md, params object[] args) where T : class { if ((object)md == null) { return null; } Delegate[] invocationList = md.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { T val = (T)invocationList[i].DynamicInvoke(args); if (val != null) { return val; } } return null; } public static string SpacedPascalCase(this string input) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < input.Length; i++) { char c = input[i]; if (i > 0 && char.IsUpper(c)) { stringBuilder.Append(' '); } stringBuilder.Append(c); } return stringBuilder.ToString(); } public static string ReadNullTerminatedString(this BinaryReader stream) { string text = ""; char c; while ((c = stream.ReadChar()) != 0) { text += c; } return text; } public static void WriteNullTerminatedString(this BinaryWriter stream, string text) { if (text != null) { foreach (char ch in text) { stream.Write(ch); } } stream.Write('\0'); } public static T CastDelegate<T>(this Delegate source) where T : class { return source.CastDelegate(typeof(T)) as T; } public static Delegate CastDelegate(this Delegate source, Type type) { if ((object)source == null) { return null; } Delegate[] invocationList = source.GetInvocationList(); if (invocationList.Length == 1) { return CreateDelegate(invocationList[0].Method, type, invocationList[0].Target); } Delegate[] array = new Delegate[invocationList.Length]; for (int i = 0; i < invocationList.Length; i++) { array[i] = invocationList[i].CastDelegate(type); } return Delegate.Combine(array); } public static bool TryCastDelegate<T>(this Delegate source, out T result) where T : class { if (source is T val) { result = val; return true; } Delegate result2; bool result3 = source.TryCastDelegate(typeof(T), out result2); result = result2 as T; return result3; } public static bool TryCastDelegate(this Delegate source, Type type, out Delegate result) { result = null; if ((object)source == null) { return false; } try { Delegate[] invocationList = source.GetInvocationList(); if (invocationList.Length == 1) { result = CreateDelegate(invocationList[0].Method, type, invocationList[0].Target); return true; } Delegate[] array = new Delegate[invocationList.Length]; for (int i = 0; i < invocationList.Length; i++) { array[i] = invocationList[i].CastDelegate(type); } result = Delegate.Combine(array); return true; } catch { return false; } } public static void LogDetailed(this Exception e, string tag = null) { if (tag == null) { Console.WriteLine("--------------------------------"); Console.WriteLine("Detailed exception log:"); } for (Exception ex = e; ex != null; ex = ex.InnerException) { Console.WriteLine("--------------------------------"); Console.WriteLine(ex.GetType().FullName + ": " + ex.Message + "\n" + ex.StackTrace); if (ex is ReflectionTypeLoadException ex2) { for (int i = 0; i < ex2.Types.Length; i++) { Console.WriteLine("ReflectionTypeLoadException.Types[" + i + "]: " + ex2.Types[i]); } for (int j = 0; j < ex2.LoaderExceptions.Length; j++) { ex2.LoaderExceptions[j].LogDetailed(tag + ((tag == null) ? "" : ", ") + "rtle:" + j); } } if (ex is TypeLoadException) { Console.WriteLine("TypeLoadException.TypeName: " + ((TypeLoadException)ex).TypeName); } if (ex is BadImageFormatException) { Console.WriteLine("BadImageFormatException.FileName: " + ((BadImageFormatException)ex).FileName); } } } public static MethodInfo GetStateMachineTarget(this MethodInfo method) { if ((object)p_StateMachineType == null) { return null; } object[] customAttributes = method.GetCustomAttributes(inherit: false); for (int i = 0; i < customAttributes.Length; i++) { Attribute attribute = (Attribute)customAttributes[i]; if (t_StateMachineAttribute.IsCompatible(attribute.GetType())) { return (p_StateMachineType.GetValue(attribute, null) as Type)?.GetMethod("MoveNext", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } } return null; } public static MethodBase GetActualGenericMethodDefinition(this MethodInfo method) { return (method.IsGenericMethod ? method.GetGenericMethodDefinition() : method).GetUnfilledMethodOnGenericType(); } public static MethodBase GetUnfilledMethodOnGenericType(this MethodBase method) { if ((object)method.DeclaringType != null && method.DeclaringType.IsGenericType) { Type genericTypeDefinition = method.DeclaringType.GetGenericTypeDefinition(); method = MethodBase.GetMethodFromHandle(method.MethodHandle, genericTypeDefinition.TypeHandle); } return method; } public static bool Is(this MemberReference member, string fullName) { if (member == null) { return false; } return MultiTargetShims.Replace(member.FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal); } public static bool Is(this MemberReference member, string typeFullName, string name) { if (member == null) { return false; } if (MultiTargetShims.Replace(((MemberReference)member.DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal)) { return member.Name == name; } return false; } public static bool Is(this MemberReference member, Type type, string name) { if (member == null) { return false; } if (MultiTargetShims.Replace(((MemberReference)member.DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal)) { return member.Name == name; } return false; } public static bool Is(this MethodReference method, string fullName) { if (method == null) { return false; } if (MultiTargetShims.Contains(fullName, " ", StringComparison.Ordinal)) { if (MultiTargetShims.Replace(method.GetID(null, null, withType: true, simple: true), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal)) { return true; } if (MultiTargetShims.Replace(method.GetID(), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal)) { return true; } } return MultiTargetShims.Replace(((MemberReference)method).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal); } public static bool Is(this MethodReference method, string typeFullName, string name) { if (method == null) { return false; } if (MultiTargetShims.Contains(name, " ", StringComparison.Ordinal) && MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal) && MultiTargetShims.Replace(method.GetID(null, null, withType: false), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(name, "+", "/", StringComparison.Ordinal)) { return true; } if (MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal)) { return ((MemberReference)method).Name == name; } return false; } public static bool Is(this MethodReference method, Type type, string name) { if (method == null) { return false; } if (MultiTargetShims.Contains(name, " ", StringComparison.Ordinal) && MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal) && MultiTargetShims.Replace(method.GetID(null, null, withType: false), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(name, "+", "/", StringComparison.Ordinal)) { return true; } if (MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal)) { return ((MemberReference)method).Name == name; } return false; } public static void ReplaceOperands(this ILProcessor il, object from, object to) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) Enumerator<Instruction> enumerator = il.Body.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; if (current.Operand?.Equals(from) ?? (from == null)) { current.Operand = to; } } } finally { ((IDisposable)enumerator).Dispose(); } } public static FieldReference Import(this ILProcessor il, FieldInfo field) { return ((MemberReference)il.Body.Method).Module.ImportReference(field); } public static MethodReference Import(this ILProcessor il, MethodBase method) { return ((MemberReference)il.Body.Method).Module.ImportReference(method); } public static TypeReference Import(this ILProcessor il, Type type) { return ((MemberReference)il.Body.Method).Module.ImportReference(type); } public static MemberReference Import(this ILProcessor il, MemberInfo member) { if ((object)member == null) { throw new ArgumentNullException("member"); } if (!(member is FieldInfo field)) { if (!(member is MethodBase method)) { if (member is Type type) { return (MemberReference)(object)il.Import(type); } throw new NotSupportedException("Unsupported member type " + member.GetType().FullName); } return (MemberReference)(object)il.Import(method); } return (MemberReference)(object)il.Import(field); } public static Instruction Create(this ILProcessor il, OpCode opcode, FieldInfo field) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return il.Create(opcode, il.Import(field)); } public static Instruction Create(this ILProcessor il, OpCode opcode, MethodBase method) { //IL_0012: 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) if (method is DynamicMethod) { return il.Create(opcode, (object)method); } return il.Create(opcode, il.Import(method)); } public static Instruction Create(this ILProcessor il, OpCode opcode, Type type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return il.Create(opcode, il.Import(type)); } public static Instruction Create(this ILProcessor il, OpCode opcode, object operand) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) Instruction obj = il.Create(OpCodes.Nop); obj.OpCode = opcode; obj.Operand = operand; return obj; } public static Instruction Create(this ILProcessor il, OpCode opcode, MemberInfo member) { //IL_002f: 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_0041: Unknown result type (might be due to invalid IL or missing references) if ((object)member == null) { throw new ArgumentNullException("member"); } if (!(member is FieldInfo field)) { if (!(member is MethodBase method)) { if (member is Type type) { return il.Create(opcode, type); } throw new NotSupportedException("Unsupported member type " + member.GetType().FullName); } return il.Create(opcode, method); } return il.Create(opcode, field); } public static void Emit(this ILProcessor il, OpCode opcode, FieldInfo field) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) il.Emit(opcode, il.Import(field)); } public static void Emit(this ILProcessor il, OpCode opcode, MethodBase method) { //IL_0012: 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) if (method is DynamicMethod) { il.Emit(opcode, (object)method); } else { il.Emit(opcode, il.Import(method)); } } public static void Emit(this ILProcessor il, OpCode opcode, Type type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) il.Emit(opcode, il.Import(type)); } public static void Emit(this ILProcessor il, OpCode opcode, MemberInfo member) { //IL_002f: 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_0041: Unknown result type (might be due to invalid IL or missing references) if ((object)member == null) { throw new ArgumentNullException("member"); } if (!(member is FieldInfo field)) { if (!(member is MethodBase method)) { if (!(member is Type type)) { throw new NotSupportedException("Unsupported member type " + member.GetType().FullName); } il.Emit(opcode, type); } else { il.Emit(opcode, method); } } else { il.Emit(opcode, field); } } public static void Emit(this ILProcessor il, OpCode opcode, object operand) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) il.Append(il.Create(opcode, operand)); } public static TypeDefinition SafeResolve(this TypeReference r) { try { return r.Resolve(); } catch { return null; } } public static FieldDefinition SafeResolve(this FieldReference r) { try { return r.Resolve(); } catch { return null; } } public static MethodDefinition SafeResolve(this MethodReference r) { try { return r.Resolve(); } catch { return null; } } public static PropertyDefinition SafeResolve(this PropertyReference r) { try { return r.Resolve(); } catch { return null; } } public static CustomAttribute GetCustomAttribute(this ICustomAttributeProvider cap, string attribute) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (cap == null || !cap.HasCustomAttributes) { return null; } Enumerator<CustomAttribute> enumerator = cap.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (((MemberReference)current.AttributeType).FullName == attribute) { return current; } } } finally { ((IDisposable)enumerator).Dispose(); } return null; } public static bool HasCustomAttribute(this ICustomAttributeProvider cap, string attribute) { return cap.GetCustomAttribute(attribute) != null; } public static int GetInt(this Instruction instr) { //IL_0001: 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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0044: 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_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0062: 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_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008e: 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) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) OpCode opCode = instr.OpCode; if (opCode == OpCodes.Ldc_I4_M1) { return -1; } if (opCode == OpCodes.Ldc_I4_0) { return 0; } if (opCode == OpCodes.Ldc_I4_1) { return 1; } if (opCode == OpCodes.Ldc_I4_2) { return 2; } if (opCode == OpCodes.Ldc_I4_3) { return 3; } if (opCode == OpCodes.Ldc_I4_4) { return 4; } if (opCode == OpCodes.Ldc_I4_5) { return 5; } if (opCode == OpCodes.Ldc_I4_6) { return 6; } if (opCode == OpCodes.Ldc_I4_7) { return 7; } if (opCode == OpCodes.Ldc_I4_8) { return 8; } if (opCode == OpCodes.Ldc_I4_S) { return (sbyte)instr.Operand; } return (int)instr.Operand; } public static int? GetIntOrNull(this Instruction instr) { //IL_0001: 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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0044: 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_0058: 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_006c: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0080: 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) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) OpCode opCode = instr.OpCode; if (opCode == OpCodes.Ldc_I4_M1) { return -1; } if (opCode == OpCodes.Ldc_I4_0) { return 0; } if (opCode == OpCodes.Ldc_I4_1) { return 1; } if (opCode == OpCodes.Ldc_I4_2) { return 2; } if (opCode == OpCodes.Ldc_I4_3) { return 3; } if (opCode == OpCodes.Ldc_I4_4) { return 4; } if (opCode == OpCodes.Ldc_I4_5) { return 5; } if (opCode == OpCodes.Ldc_I4_6) { return 6; } if (opCode == OpCodes.Ldc_I4_7) { return 7; } if (opCode == OpCodes.Ldc_I4_8) { return 8; } if (opCode == OpCodes.Ldc_I4_S) { return (sbyte)instr.Operand; } if (opCode == OpCodes.Ldc_I4) { return (int)instr.Operand; } return null; } public static bool IsBaseMethodCall(this MethodBody body, MethodReference called) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) MethodDefinition method = body.Method; if (called == null) { return false; } TypeReference val = ((MemberReference)called).DeclaringType; while (val is TypeSpecification) { val = ((TypeSpecification)val).ElementType; } string patchFullName = ((MemberReference)(object)val).GetPatchFullName(); bool flag = false; try { TypeDefinition val2 = method.DeclaringType; while ((val2 = val2.BaseType?.SafeResolve()) != null) { if (((MemberReference)(object)val2).GetPatchFullName() == patchFullName) { flag = true; break; } } } catch { flag = ((MemberReference)(object)method.DeclaringType).GetPatchFullName() == patchFullName; } if (!flag) { return false; } return true; } public static bool IsCallvirt(this MethodReference method) { if (!method.HasThis) { return false; } if (((MemberReference)method).DeclaringType.IsValueType) { return false; } return true; } public static bool IsStruct(this TypeReference type) { if (!type.IsValueType) { return false; } if (type.IsPrimitive) { return false; } return true; } public static OpCode ToLongOp(this OpCode op) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0025: 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_0046: Expected I4, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: 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) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected I4, but got Unknown //IL_00a0: 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) string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code); if (!name.EndsWith("_S", StringComparison.Ordinal)) { return op; } lock (_ToLongOp) { if (_ToLongOp.TryGetValue((int)((OpCode)(ref op)).Code, out var value)) { return value; } return _ToLongOp[(int)((OpCode)(ref op)).Code] = (OpCode)(((??)(OpCode?)t_OpCodes.GetField(name.Substring(0, name.Length - 2))?.GetValue(null)) ?? op); } } public static OpCode ToShortOp(this OpCode op) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0025: 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_0046: Expected I4, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: 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) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected I4, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code); if (name.EndsWith("_S", StringComparison.Ordinal)) { return op; } lock (_ToShortOp) { if (_ToShortOp.TryGetValue((int)((OpCode)(ref op)).Code, out var value)) { return value; } return _ToShortOp[(int)((OpCode)(ref op)).Code] = (OpCode)(((??)(OpCode?)t_OpCodes.GetField(name + "_S")?.GetValue(null)) ?? op); } } public static void RecalculateILOffsets(this MethodDefinition method) { if (method.HasBody) { int num = 0; for (int i = 0; i < method.Body.Instructions.Count; i++) { Instruction val = method.Body.Instructions[i]; val.Offset = num; num += val.GetSize(); } } } public static void FixShortLongOps(this MethodDefinition method) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: 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_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) if (!method.HasBody) { return; } for (int i = 0; i < method.Body.Instructions.Count; i++) { Instruction val = method.Body.Instructions[i]; if (val.Operand is Instruction) { val.OpCode = val.OpCode.ToLongOp(); } } method.RecalculateILOffsets(); bool flag; do { flag = false; for (int j = 0; j < method.Body.Instructions.Count; j++) { Instruction val2 = method.Body.Instructions[j]; object operand = val2.Operand; Instruction val3 = (Instruction)((operand is Instruction) ? operand : null); if (val3 != null) { int num = val3.Offset - (val2.Offset + val2.GetSize()); if (num == (sbyte)num) { OpCode opCode = val2.OpCode; val2.OpCode = val2.OpCode.ToShortOp(); flag = opCode != val2.OpCode; } } } } while (flag); } public static bool Is(this MemberInfo minfo, MemberReference mref) { return mref.Is(minfo); } public static bool Is(this MemberReference mref, MemberInfo minfo) { if (mref == null) { return false; } TypeReference val = mref.DeclaringType; if (((val != null) ? ((MemberReference)val).FullName : null) == "<Module>") { val = null; } GenericParameter val2 = (GenericParameter)(object)((mref is GenericParameter) ? mref : null); if (val2 != null) { if (!(minfo is Type type)) { return false; } if (!type.IsGenericParameter) { IGenericParameterProvider owner = val2.Owner; IGenericInstance val3 = (IGenericInstance)(object)((owner is IGenericInstance) ? owner : null); if (val3 != null) { return ((MemberReference)(object)val3.GenericArguments[val2.Position]).Is(type); } return false; } return val2.Position == type.GenericParameterPosition; } if ((object)minfo.DeclaringType != null) { if (val == null) { return false; } Type type2 = minfo.DeclaringType; if (minfo is Type && type2.IsGenericType && !type2.IsGenericTypeDefinition) { type2 = type2.GetGenericTypeDefinition(); } if (!((MemberReference)(object)val).Is(type2)) { return false; } } else if (val != null) { return false; } if (!(mref is TypeSpecification) && mref.Name != minfo.Name) { return false; } TypeReference val4 = (TypeReference)(object)((mref is TypeReference) ? mref : null); if (val4 != null) { if (!(minfo is Type type3)) { return false; } if (type3.IsGenericParameter) { return false; } GenericInstanceType val5 = (GenericInstanceType)(object)((mref is GenericInstanceType) ? mref : null); if (val5 != null) { if (!type3.IsGenericType) { return false; } Collection<TypeReference> genericArguments = val5.GenericArguments; Type[] genericArguments2 = type3.GetGenericArguments(); if (genericArguments.Count != genericArguments2.Length) { return false; } for (int i = 0; i < genericArguments.Count; i++) { if (!((MemberReference)(object)genericArguments[i]).Is(genericArguments2[i])) { return false; } } return ((MemberReference)(object)((TypeSpecification)val5).ElementType).Is(type3.GetGenericTypeDefinition()); } if (val4.HasGenericParameters) { if (!type3.IsGenericType) { return false; } Collection<GenericParameter> genericParameters = val4.GenericParameters; Type[] genericArguments3 = type3.GetGenericArguments(); if (genericParameters.Count != genericArguments3.Length) { return false; } for (int j = 0; j < genericParameters.Count; j++) { if (!((MemberReference)(object)genericParameters[j]).Is(genericArguments3[j])) { return false; } } } else if (type3.IsGenericType) { return false; } ArrayType val6 = (ArrayType)(object)((mref is ArrayType) ? mref : null); if (val6 != null) { if (!type3.IsArray) { return false; } if (val6.Dimensions.Count == type3.GetArrayRank()) { return ((MemberReference)(object)((TypeSpecification)val6).ElementType).Is(type3.GetElementType()); } return false; } ByReferenceType val7 = (ByReferenceType)(object)((mref is ByReferenceType) ? mref : null); if (val7 != null) { if (!type3.IsByRef) { return false; } return ((MemberReference)(object)((TypeSpecification)val7).ElementType).Is(type3.GetElementType()); } PointerType val8 = (PointerType)(object)((mref is PointerType) ? mref : null); if (val8 != null) { if (!type3.IsPointer) { return false; } return ((MemberReference)(object)((TypeSpecification)val8).ElementType).Is(type3.GetElementType()); } TypeSpecification val9 = (TypeSpecification)(object)((mref is TypeSpecification) ? mref : null); if (val9 != null) { return ((MemberReference)(object)val9.ElementType).Is(type3.HasElementType ? type3.GetElementType() : type3); } if (val != null) { return mref.Name == type3.Name; } return mref.FullName == MultiTargetShims.Replace(type3.FullName, "+", "/", StringComparison.Ordinal); } if (minfo is Type) { return false; } MethodReference methodRef = (MethodReference)(object)((mref is MethodReference) ? mref : null); if (methodRef != null) { if (!(minfo is MethodBase methodBase)) { return false; } Collection<ParameterDefinition> parameters = methodRef.Parameters; ParameterInfo[] parameters2 = methodBase.GetParameters(); if (parameters.Count != parameters2.Length) { return false; } GenericInstanceMethod val10 = (GenericInstanceMethod)(object)((mref is GenericInstanceMethod) ? mref : null); if (val10 != null) { if (!methodBase.IsGenericMethod) { return false; } Collection<TypeReference> genericArguments4 = val10.GenericArguments; Type[] genericArguments5 = methodBase.GetGenericArguments(); if (genericArguments4.Count != genericArguments5.Length) { return false; } for (int k = 0; k < genericArguments4.Count; k++) { if (!((MemberReference)(object)genericArguments4[k]).Is(genericArguments5[k])) { return false; } } return ((MemberReference)(object)((MethodSpecification)val10).ElementMethod).Is((methodBase as MethodInfo)?.GetGenericMethodDefinition() ?? methodBase); } if (methodRef.HasGenericParameters) { if (!methodBase.IsGenericMethod) { return false; } Collection<GenericParameter> genericParameters2 = methodRef.GenericParameters; Type[] genericArguments6 = methodBase.GetGenericArguments(); if (genericParameters2.Count != genericArguments6.Length) { return false; } for (int l = 0; l < genericParameters2.Count; l++) { if (!((MemberReference)(object)genericParameters2[l]).Is(genericArguments6[l])) { return false; } } } else if (methodBase.IsGenericMethod) { return false; } Relinker relinker = null; relinker = delegate(IMetadataTokenProvider paramMemberRef, IGenericParameterProvider ctx) { TypeReference val15 = (TypeReference)(object)((paramMemberRef is TypeReference) ? paramMemberRef : null); return (IMetadataTokenProvider)((val15 == null) ? ((object)paramMemberRef) : ((object)ResolveParameter(val15))); }; if (!((MemberReference)(object)methodRef.ReturnType.Relink(relinker, null)).Is((methodBase as MethodInfo)?.ReturnType ?? typeof(void)) && !((MemberReference)(object)methodRef.ReturnType).Is((methodBase as MethodInfo)?.ReturnType ?? typeof(void))) { return false; } for (int m = 0; m < parameters.Count; m++) { if (!((MemberReference)(object)((ParameterReference)parameters[m]).ParameterType.Relink(relinker, null)).Is(parameters2[m].ParameterType) && !((MemberReference)(object)((ParameterReference)parameters[m]).ParameterType).Is(parameters2[m].ParameterType)) { return false; } } return true; } if (minfo is MethodInfo) { return false; } if (mref is FieldReference != minfo is FieldInfo) { return false; } if (mref is PropertyReference != minfo is PropertyInfo) { return false; } if (mref is EventReference != minfo is EventInfo) { return false; } return true; TypeReference ResolveParameter(TypeReference paramTypeRef) { GenericParameter val11 = (GenericParameter)(object)((paramTypeRef is GenericParameter) ? paramTypeRef : null); if (val11 != null) { if (val11.Owner is MethodReference) { MethodReference obj = methodRef; GenericInstanceMethod val12 = (GenericInstanceMethod)(object)((obj is GenericInstanceMethod) ? obj : null); if (val12 != null) { return val12.GenericArguments[val11.Position]; } } IGenericParameterProvider owner2 = val11.Owner; TypeReference val13 = (TypeReference)(object)((owner2 is TypeReference) ? owner2 : null); if (val13 != null) { TypeReference declaringType = ((MemberReference)methodRef).DeclaringType; GenericInstanceType val14 = (GenericInstanceType)(object)((declaringType is GenericInstanceType) ? declaringType : null); if (val14 != null && ((MemberReference)val13).FullName == ((MemberReference)((TypeSpecification)val14).ElementType).FullName) { return val14.GenericArguments[val11.Position]; } } return paramTypeRef; } if (paramTypeRef == ((MemberReference)methodRef).DeclaringType.GetElementType()) { return ((MemberReference)methodRef).DeclaringType; } return paramTypeRef; } } public static IMetadataTokenProvider ImportReference(this ModuleDefinition mod, IMetadataTokenProvider mtp) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown if (mtp is TypeReference) { return (IMetadataTokenProvider)(object)mod.ImportReference((TypeReference)mtp); } if (mtp is FieldReference) { return (IMetadataTokenProvider)(object)mod.ImportReference((FieldReference)mtp); } if (mtp is MethodReference) { return (IMetadataTokenProvider)(object)mod.ImportReference((MethodReference)mtp); } return mtp; } public static void AddRange<T>(this Collection<T> list, IEnumerable<T> other) { foreach (T item in other) { list.Add(item); } } public static void AddRange(this IDictionary dict, IDictionary other) { foreach (DictionaryEntry item in other) { dict.Add(item.Key, item.Value); } } public static void AddRange<K, V>(this IDictionary<K, V> dict, IDictionary<K, V> other) { foreach (KeyValuePair<K, V> item in other) { dict.Add(item.Key, item.Value); } } public static void AddRange<K, V>(this Dictionary<K, V> dict, Dictionary<K, V> other) { foreach (KeyValuePair<K, V> item in other) { dict.Add(item.Key, item.Value); } } public static void InsertRange<T>(this Collection<T> list, int index, IEnumerable<T> other) { foreach (T item in other) { list.Insert(index++, item); } } public static bool IsCompatible(this Type type, Type other) { if (!type._IsCompatible(other)) { return other._IsCompatible(type); } return true; } private static bool _IsCompatible(this Type type, Type other) { if ((object)type == other) { return true; } if (type.IsAssignableFrom(other)) { return true; } if (other.IsEnum && type.IsCompatible(Enum.GetUnderlyingType(other))) { return true; } return false; } public static T GetDeclaredMember<T>(this T member) where T : MemberInfo { if ((object)member.DeclaringType == member.ReflectedType) { return member; } int metadataToken = member.MetadataToken; MemberInfo[] members = member.DeclaringType.GetMembers((BindingFlags)(-1)); foreach (MemberInfo memberInfo in members) { if (memberInfo.MetadataToken == metadataToken) { return (T)memberInfo; } } return member; } public unsafe static void SetMonoCorlibInternal(this Assembly asm, bool value) { if ((object)Type.GetType("Mono.Runtime") == null) { return; } Type type = asm?.GetType(); if ((object)type == null) { return; } FieldInfo value2; lock (fmap_mono_assembly) { if (!fmap_mono_assembly.TryGetValue(type, out value2)) { value2 = type.GetField("_mono_assembly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? type.GetField("dynamic_assembly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); fmap_mono_assembly[type] = value2; } } if ((object)value2 == null) { return; } AssemblyName assemblyName = new AssemblyName(asm.FullName); lock (ReflectionHelper.AssemblyCache) { WeakReference value3 = new WeakReference(asm); ReflectionHelper.AssemblyCache[asm.GetRuntimeHashedFullName()] = value3; ReflectionHelper.AssemblyCache[assemblyName.FullName] = value3; ReflectionHelper.AssemblyCache[assemblyName.Name] = value3; } long num = 0L; object value4 = value2.GetValue(asm); if (!(value4 is IntPtr intPtr)) { if (value4 is UIntPtr uIntPtr) { num = (long)(ulong)uIntPtr; } } else { num = (long)intPtr; } int num2 = IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + 20 + 4 + 4 + 4 + (_MonoAssemblyNameHasArch ? ((!(typeof(object).Assembly.GetName().Name == "System.Private.CoreLib")) ? ((IntPtr.Size == 4) ? 12 : 16) : ((IntPtr.Size == 4) ? 20 : 24)) : ((typeof(object).Assembly.GetName().Name == "System.Private.CoreLib") ? 16 : 8)) + IntPtr.Size + IntPtr.Size + 1 + 1 + 1; byte* ptr = (byte*)(num + num2); *ptr = (byte)(value ? 1 : 0); } public static bool IsDynamicMethod(this MethodBase method) { if ((object)_RTDynamicMethod != null) { if (!(method is DynamicMethod)) { return (object)method.GetType() == _RTDynamicMethod; } return true; } if (method is DynamicMethod) { return true; } if (method.MetadataToken != 0 || !method.IsStatic || !method.IsPublic || (method.Attributes & MethodAttributes.PrivateScope) != 0) { return false; } MethodInfo[] methods = method.DeclaringType.GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { if ((object)method == methodInfo) { return false; } } return true; } public static object SafeGetTarget(this WeakReference weak) { try { return weak.Target; } catch (InvalidOperationException) { return null; } } public static bool SafeGetIsAlive(this WeakReference weak) { try { return weak.IsAlive; } catch (InvalidOperationException) { return false; } } public static T CreateDelegate<T>(this MethodBase method) where T : Delegate { return (T)method.CreateDelegate(typeof(T), null); } public static T CreateDelegate<T>(this MethodBase method, object target) where T : Delegate { return (T)method.CreateDelegate(typeof(T), target); } public static Delegate CreateDelegate(this MethodBase method, Type delegateType) { return method.CreateDelegate(delegateType, null); } public static Delegate CreateDelegate(this MethodBase method, Type delegateType, object target) { if (!typeof(Delegate).IsAssignableFrom(delegateType)) { throw new ArgumentException("Type argument must be a delegate type!"); } if (method is DynamicMethod dynamicMethod) { return dynamicMethod.CreateDelegate(delegateType, target); } RuntimeMethodHandle methodHandle = method.MethodHandle; RuntimeHelpers.PrepareMethod(methodHandle); IntPtr functionPointer = methodHandle.GetFunctionPointer(); return (Delegate)Activator.CreateInstance(delegateType, target, functionPointer); } public static MethodDefinition FindMethod(this TypeDefinition type, string id, bool simple = true) { //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) Enumerator<MethodDefinition> enumerator; if (simple && !MultiTargetShims.Contains(id, " ", StringComparison.Ordinal)) { enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; if (((MethodReference)(object)current).GetID(null, null, withType: true, simple: true) == id) { return current; } } } finally { ((IDisposable)enumerator).Dispose(); } enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current2 = enumerator.Current; if (((MethodReference)(object)current2).GetID(null, null, withType: false, simple: true) == id) { return current2; } } } finally { ((IDisposable)enumerator).Dispose(); } } enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current3 = enumerator.Current; if (((MethodReference)(object)current3).GetID() == id) { return current3; } } } finally { ((IDisposable)enumerator).Dispose(); } enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current4 = enumerator.Current; if (((MethodReference)(object)current4).GetID(null, null, withType: false) == id) { return current4; } } } finally { ((IDisposable)enumerator).Dispose(); } return null; } public static MethodDefinition FindMethodDeep(this TypeDefinition type, string id, bool simple = true) { MethodDefinition obj = type.FindMethod(id, simple); if (obj == null) { TypeReference baseType = type.BaseType; if (baseType == null) { return null; } TypeDefinition obj2 = baseType.Resolve(); if (obj2 == null) { return null; } obj = obj2.FindMethodDeep(id, simple); } return obj; } public static MethodInfo FindMethod(this Type type, string id, bool simple = true) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo[] array; if (simple && !MultiTargetShims.Contains(id, " ", StringComparison.Ordinal)) { array = methods; foreach (MethodInfo methodInfo in array) { if (methodInfo.GetID(null, null, withType: true, proxyMethod: false, simple: true) == id) { return methodInfo; } } array = methods; foreach (MethodInfo methodInfo2 in array) { if (methodInfo2.GetID(null, null, withType: false, proxyMethod: false, simple: true) == id) { return methodInfo2; } } } array = methods; foreach (MethodInfo methodInfo3 in array) { if (methodInfo3.GetID(null, null, withType: true, proxyMethod: false, simple: false) == id) { return methodInfo3; } } array = methods; foreach (MethodInfo methodInfo4 in array) { if (methodInfo4.GetID(null, null, withType: false, proxyMethod: false, simple: false) == id) { return methodInfo4; } } return null; } public static MethodInfo FindMethodDeep(this Type type, string id, bool simple = true) { MethodInfo methodInfo = type.FindMethod(id, simple); if ((object)methodInfo == null) { Type? baseType = type.BaseType; if ((object)baseType == null) { return null; } methodInfo = baseType.FindMethodDeep(id, simple); } return methodInfo; } public static PropertyDefinition FindProperty(this TypeDefinition type, string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<PropertyDefinition> enumerator = type.Properties.GetEnumerator(); try { while (enumerator.MoveNext()) { PropertyDefinition current = enumerator.Current; if (((MemberReference)current).Name == name) { return current; } } } finally { ((IDisposable)enumerator).Dispose(); } return null; } public static PropertyDefinition FindPropertyDeep(this TypeDefinition type, string name) { PropertyDefinition obj = type.FindProperty(name); if (obj == null) { TypeReference baseType = type.BaseType; if (baseType == null) { return null; } TypeDefinition obj2 = baseType.Resolve(); if (obj2 == null) { return null; } obj = obj2.FindPropertyDeep(name); } return obj; } public static FieldDefinition FindField(this TypeDefinition type, string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<FieldDefinition> enumerator = type.Fields.GetEnumerator(); try { while (enumerator.MoveNext()) { FieldDefinition current = enumerator.Current; if (((MemberReference)current).Name == name) { return current; } } } finally { ((IDisposable)enumerator).Dispose(); } return null; } public static FieldDefinition FindFieldDeep(this TypeDefinition type, string name) { FieldDefinition obj = type.FindField(name); if (obj == null) { TypeReference baseType = type.BaseType; if (baseType == null) { return null; } TypeDefinition obj2 = baseType.Resolve(); if (obj2 == null) { return null; } obj = obj2.FindFieldDeep(name); } return obj; } public static EventDefinition FindEvent(this TypeDefinition type, string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<EventDefinition> enumerator = type.Events.GetEnumerator(); try { while (enumerator.MoveNext()) { EventDefinition current = enumerator.Current; if (((MemberReference)current).Name == name) { return current; } } } finally { ((IDisposable)enumerator).Dispose(); } return null; } public static EventDefinition FindEventDeep(this TypeDefinition type, string name) { EventDefinition obj = type.FindEvent(name); if (obj == null) { TypeReference baseType = type.BaseType; if (baseType == null) { return null; } TypeDefinition obj2 = baseType.Resolve(); if (obj2 == null) { return null; } obj = obj2.FindEventDeep(name); } return obj; } public static string GetID(this MethodReference method, string name = null, string type = null, bool withType = true, bool simple = false) { StringBuilder stringBuilder = new StringBuilder(); if (simple) { if (withType && (type != null || ((MemberReference)method).DeclaringType != null)) { stringBuilder.Append(type ?? ((MemberReference)(object)((MemberReference)method).DeclaringType).GetPatchFullName()).Append("::"); } stringBuilder.Append(name ?? ((MemberReference)method).Name); return stringBuilder.ToString(); } stringBuilder.Append(((MemberReference)(object)method.ReturnType).GetPatchFullName()).Append(" "); if (withType && (type != null || ((MemberReference)method).DeclaringType != null)) { stringBuilder.Append(type ?? ((MemberReference)(object)((MemberReference)method).DeclaringType).GetPatchFullName()).Append("::"); } stringBuilder.Append(name ?? ((MemberReference)method).Name); GenericInstanceMethod val = (GenericInstanceMethod)(object)((method is GenericInstanceMethod) ? method : null); if (val != null && val.GenericArguments.Count != 0) { stringBuilder.Append("<"); Collection<TypeReference> genericArguments = val.GenericArguments; for (int i = 0; i < genericArguments.Count; i++) { if (i > 0) { stringBuilder.Append(","); } stringBuilder.Append(((MemberReference)(object)genericArguments[i]).GetPatchFullName()); } stringBuilder.Append(">"); } else if (method.GenericParameters.Count != 0) { stringBuilder.Append("<"); Collection<GenericParameter> genericParameters = method.GenericParameters; for (int j = 0; j < genericParameters.Count; j++) { if (j > 0) { stringBuilder.Append(","); } stringBuilder.Append(((MemberReference)genericParameters[j]).Name); } stringBuilder.Append(">"); } stringBuilder.Append("("); if (method.HasParameters) { Collection<ParameterDefinition> parameters = method.Parameters; for (int k = 0; k < parameters.Count; k++) { ParameterDefinition val2 = parameters[k]; if (k > 0) { stringBuilder.Append(","); } if (((ParameterReference)val2).ParameterType.IsSentinel) { stringBuilder.Append("...,"); } stringBuilder.Append(((MemberReference)(object)((ParameterReference)val2).ParameterType).GetPatchFullName()); } } stringBuilder.Append(")"); return stringBuilder.ToString(); } public static string GetID(this CallSite method) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(((MemberReference)(object)method.ReturnType).GetPatchFullName()).Append(" "); stringBuilder.Append("("); if (method.HasParameters) { Collection<ParameterDefinition> parameters = method.Parameters; for (int i = 0; i < parameters.Count; i++) { ParameterDefinition val = parameters[i]; if (i > 0) { stringBuilder.Append(","); } if (((ParameterReference)val).ParameterType.IsSentinel) { stringBuilder.Append("...,"); } stringBuilder.Append(((MemberReference)(object)((ParameterReference)val).ParameterType).GetPatchFullName()); } } stringBuilder.Append(")"); return stringBuilder.ToString(); } public static string GetID(this MethodBase method, string name = null, string type = null, bool withType = true, bool proxyMethod = false, bool simple = false) { while (method is MethodInfo && method.IsGenericMethod && !method.IsGenericMethodDefinition) { method = ((MethodInfo)method).GetGenericMethodDefinition(); } StringBuilder stringBuilder = new StringBuilder(); if (simple) { if (withType && (type != null || (object)method.DeclaringType != null)) { stringBuilder.Append(type ?? method.DeclaringType.FullName).Append("::"); } stringBuilder.Append(name ?? method.Name); return stringBuilder.ToString(); } stringBuilder.Append((method as MethodInfo)?.ReturnType?.FullName ?? "System.Void").Append(" "); if (withType && (type != null || (object)method.DeclaringType != null)) { stringBuilder.Append(type ?? MultiTargetShims.Replace(method.DeclaringType.FullName, "+", "/", StringComparison.Ordinal)).Append("::"); } stringBuilder.Append(name ?? method.Name); if (method.ContainsGenericParameters) { stringBuilder.Append("<"); Type[] genericArguments = method.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (i > 0) { stringBuilder.Append(","); } stringBuilder.Append(genericArguments[i].Name); } stringBuilder.Append(">"); } stringBuilder.Append("("); ParameterInfo[] parameters = method.GetParameters(); for (int j = (proxyMethod ? 1 : 0); j < parameters.Length; j++) { ParameterInfo parameterInfo = parameters[j]; if (j > (proxyMethod ? 1 : 0)) { stringBuilder.Append(","); } bool flag; try { flag = parameterInfo.GetCustomAttributes(t_ParamArrayAttribute, inherit: false).Length != 0; } catch (NotSupportedException) { flag = false; } if (flag) { stringBuilder.Append("...,"); } stringBuilder.Append(parameterInfo.ParameterType.FullName); } stringBuilder.Append(")"); return stringBuilder.ToString(); } public static string GetPatchName(this MemberReference mr) { MemberReference obj = ((mr is ICustomAttributeProvider) ? mr : null); return ((obj != null) ? ((ICustomAttributeProvider)(object)obj).GetPatchName() : null) ?? mr.Name; } public static string GetPatchFullName(this MemberReference mr) { MemberReference obj = ((mr is ICustomAttributeProvider) ? mr : null); return ((obj != null) ? ((ICustomAttributeProvider)(object)obj).GetPatchFullName(mr) : null) ?? mr.FullName; } private static string GetPatchName(this ICustomAttributeProvider cap) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) CustomAttribute customAttribute = cap.GetCustomAttribute("MonoMod.MonoModPatch"); string text; if (customAttribute != null) { CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; text = (string)((CustomAttributeArgument)(ref val)).Value; int num = text.LastIndexOf('.'); if (num != -1 && num != text.Length - 1) { text = text.Substring(num + 1); } return text; } text = ((MemberReference)cap).Name; if (!text.StartsWith("patch_", StringComparison.Ordinal)) { return text; } return text.Substring(6); } private static string GetPatchFullName(this ICustomAttributeProvider cap, MemberReference mr) { //IL_003a: 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_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Expected O, but got Unknown //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Expected O, but got Unknown //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Expected O, but got Unknown //IL_0323: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Expected O, but got Unknown //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) TypeReference val = (TypeReference)(object)((cap is TypeReference) ? cap : null); if (val != null) { CustomAttribute customAttribute = cap.GetCustomAttribute("MonoMod.MonoModPatch"); string text; if (customAttribute != null) { CustomAttributeArgument val2 = customAttribute.ConstructorArguments[0]; text = (string)((CustomAttributeArgument)(ref val2)).Value; } else { text = ((MemberReference)cap).Name; text = (text.StartsWith("patch_", StringComparison.Ordinal) ? text.Substring(6) : text); } if (text.StartsWith("global::", StringComparison.Ordinal)) { text = text.Substring(8); } else if (!MultiTargetShims.Contains(text, ".", StringComparison.Ordinal) && !MultiTargetShims.Contains(text, "/", StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(val.Namespace)) { text = val.Namespace + "." + text; } else if (val.IsNested) { text = ((MemberReference)(object)((MemberReference)val).DeclaringType).GetPatchFullName() + "/" + text; } } if (mr is TypeSpecification) { List<TypeSpecification> list = new List<TypeSpecification>(); TypeSpecification val3 = (TypeSpecification)mr; TypeReference elementType; do { list.Add(val3); elementType = val3.ElementType; } while ((val3 = (TypeSpecification)(object)((elementType is TypeSpecification) ? elementType : null)) != null); StringBuilder stringBuilder = new StringBuilder(text.Length + list.Count * 4); stringBuilder.Append(text); for (int num = list.Count - 1; num > -1; num--) { val3 = list[num]; if (((TypeReference)val3).IsByReference) { stringBuilder.Append("&"); } else if (((TypeReference)val3).IsPointer) { stringBuilder.Append("*"); } else if (!((TypeReference)val3).IsPinned && !((TypeReference)val3).IsSentinel) { if (((TypeReference)val3).IsArray) { ArrayType val4 = (ArrayType)val3; if (val4.IsVector) { stringBuilder.Append("[]"); } else { stringBuilder.Append("["); for (int i = 0; i < val4.Dimensions.Count; i++) { if (i > 0) { stringBuilder.Append(","); } ArrayDimension val5 = val4.Dimensions[i]; stringBuilder.Append(((object)(ArrayDimension)(ref val5)).ToString()); } stringBuilder.Append("]"); } } else if (((TypeReference)val3).IsRequiredModifier) { stringBuilder.Append("modreq(").Append(((RequiredModifierType)val3).ModifierType).Append(")"); } else if (((TypeReference)val3).IsOptionalModifier) { stringBuilder.Append("modopt(").Append(((OptionalModifierType)val3).ModifierType).Append(")"); } else if (((TypeReference)val3).IsGenericInstance) { GenericInstanceType val6 = (GenericInstanceType)val3; stringBuilder.Append("<"); for (int j = 0; j < val6.GenericArguments.Count; j++) { if (j > 0) { stringBuilder.Append(","); } stringBuilder.Append(((MemberReference)(object)val6.GenericArguments[j]).GetPatchFullName()); } stringBuilder.Append(">"); } else { if (!((TypeReference)val3).IsFunctionPointer) { throw new NotSupportedException($"MonoMod can't handle TypeSpecification: {((MemberReference)val).FullName} ({((object)val).GetType()})"); } FunctionPointerType val7 = (FunctionPointerType)val3; stringBuilder.Append(" ").Append(((MemberReference)(object)val7.ReturnType).GetPatchFullName()).Append(" *("); if (val7.HasParameters) { for (int k = 0; k < val7.Parameters.Count; k++) { ParameterDefinition val8 = val7.Parameters[k]; if (k > 0) { stringBuilder.Append(","); } if (((ParameterReference)val8).ParameterType.IsSentinel) { stringBuilder.Append("...,"); } stringBuilder.Append(((MemberReference)((ParameterReference)val8).ParameterType).FullName); } } stringBuilder.Append(")"); } } } text = stringBuilder.ToString(); } return text; } FieldReference val9 = (FieldReference)(object)((cap is FieldReference) ? cap : null); if (val9 != null) { return ((MemberReference)(object)val9.FieldType).GetPatchFullName() + " " + ((MemberReference)(object)((MemberReference)val9).DeclaringType).GetPatchFullName() + "::" + cap.GetPatchName(); } if (cap is MethodReference) { throw new InvalidOperationException("GetPatchFullName not supported on MethodReferences - use GetID instead"); } throw new InvalidOperationException($"GetPatchFullName not supported on type {((object)cap).GetType()}"); } public static MethodDefinition Clone(this MethodDefinition o, MethodDefinition c = null) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0071: 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_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_000f: 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) //IL_0021: Expected O, but got Unknown //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) if (o == null) { return null; } if (c == null) { c = new MethodDefinition(((MemberReference)o).Name, o.Attributes, ((MethodReference)o).ReturnType); } ((MemberReference)c).Name = ((MemberReference)o).Name; c.Attributes = o.Attributes; ((MethodReference)c).ReturnType = ((MethodReference)o).ReturnType; c.DeclaringType = o.DeclaringType; ((MemberReference)c).MetadataToken = ((MemberReference)c).MetadataToken; c.Body = o.Body.Clone(c); c.Attributes = o.Attributes; c.ImplAttributes = o.ImplAttributes; c.PInvokeInfo = o.PInvokeInfo; c.IsPreserveSig = o.IsPreserveSig; c.IsPInvokeImpl = o.IsPInvokeImpl; Enumerator<GenericParameter> enumerator = ((MethodReference)o).GenericParameters.GetEnumerator(); try { while (enumerator.MoveNext()) { GenericParameter current = enumerator.Current; ((MethodReference)c).GenericParameters.Add(current.Clone()); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<ParameterDefinition> enumerator2 = ((MethodReference)o).Parameters.GetEnumerator(); try { while (enumerator2.MoveNext()) { ParameterDefinition current2 = enumerator2.Current; ((MethodReference)c).Parameters.Add(current2); } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<CustomAttribute> enumerator3 = o.CustomAttributes.GetEnumerator(); try { while (enumerator3.MoveNext()) { CustomAttribute current3 = enumerator3.Current; c.CustomAttributes.Add(current3.Clone()); } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<MethodReference> enumerator4 = o.Overrides.GetEnumerator(); try { while (enumerator4.MoveNext()) { MethodReference current4 = enumerator4.Current; c.Overrides.Add(current4); } return c; } finally { ((IDisposable)enumerator4).Dispose(); } } public static MethodBody Clone(this MethodBody bo, MethodDefinition m) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) if (bo == null) { return null; } MethodBody bc = new MethodBody(m); bc.MaxStackSize = bo.MaxStackSize; bc.InitLocals = bo.InitLocals; bc.LocalVarToken = bo.LocalVarToken; bc.Instructions.AddRange(((IEnumerable<Instruction>)bo.Instructions).Select(delegate(Instruction o) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) Instruction obj = Instruction.Create(OpCodes.Nop); obj.OpCode = o.OpCode; obj.Operand = o.Operand; obj.Offset = o.Offset; return obj; })); Enumerator<Instruction> enumerator = bc.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; object operand = current.Operand; Instruction val = (Instruction)((operand is Instruction) ? operand : null); if (val != null) { current.Operand = bc.Instructions[bo.Instructions.IndexOf(val)]; } else if (current.Operand is Instruction[] source) { current.Operand = source.Select((Instruction i) => bc.Instructions[bo.Instructions.IndexOf(i)]).ToArray(); } } } finally { ((IDisposable)enumerator).Dispose(); } bc.ExceptionHandlers.AddRange(((IEnumerable<ExceptionHandler>)bo.ExceptionHandlers).Select((Func<ExceptionHandler, ExceptionHandler>)((ExceptionHandler o) => new ExceptionHandler(o.HandlerType) { TryStart = ((o.TryStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.TryStart)]), TryEnd = ((o.TryEnd == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.TryEnd)]), FilterStart = ((o.FilterStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.FilterStart)]), HandlerStart = ((o.HandlerStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.HandlerStart)]), HandlerEnd = ((o.HandlerEnd == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.HandlerEnd)]), CatchType = o.CatchType }))); bc.Variables.AddRange(((IEnumerable<VariableDefinition>)bo.Variables).Select((Func<VariableDefinition, VariableDefinition>)((VariableDefinition o) => new VariableDefinition(((VariableReference)o).VariableType)))); m.CustomDebugInformations.AddRange((IEnumerable<CustomDebugInformation>)bo.Method.CustomDebugInformations); m.DebugInformation.SequencePoints.AddRange(((IEnumerable<SequencePoint>)bo.Method.DebugInformation.SequencePoints).Select((Func<SequencePoint, SequencePoint>)((SequencePoint o) => new SequencePoint(((IEnumerable<Instruction>)bc.Instructions).FirstOrDefault((Func<Instruction, bool>)((Instruction i) => i.Offset == o.Offset)), o.Document) { StartLine = o.StartLine, StartColumn = o.StartColumn, EndLine = o.EndLine, EndColumn = o.EndColumn }))); return bc; } public static GenericParameter Update(this GenericParameter param, int position, GenericParameterType type) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) f_GenericParameter_position.SetValue(param, position); f_GenericParameter_type.SetValue(param, type); return param; } public static GenericParameter ResolveGenericParameter(this IGenericParameterProvider provider, GenericParameter orig) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Expected O, but got Unknown if (provider is GenericParameter && ((MemberReference)(GenericParameter)provider).Name == ((MemberReference)orig).Name) { return (GenericParameter)provider; } Enumerator<GenericParameter> enumerator = provider.GenericParameters.GetEnumerator(); try { while (enumerator.MoveNext()) { GenericParameter current = enumerator.Current; if (((MemberReference)current).Name == ((MemberReference)orig).Name) { return current; } } } finally { ((IDisposable)enumerator).Dispose(); } int position = orig.Position; if (provider is MethodReference && orig.DeclaringMethod != null) { if (position < provider.GenericParameters.Count) { return provider.GenericParameters[position]; } return Update(new GenericParameter(((MemberReference)orig).Name, provider), position, (GenericParameterType)1); } if (provider is TypeReference && ((MemberReference)orig).DeclaringType != null) { if (position < provider.GenericParameters.Count) { return provider.GenericParameters[position]; } return Update(new GenericParameter(((MemberReference)orig).Name, provider), position, (GenericParameterType)0); } IGenericParameterProvider obj = ((provider is TypeSpecification) ? provider : null); object obj2 = ((obj != null) ? ((IGenericParameterProvider)(object)((TypeSpecification)obj).ElementType).ResolveGenericParameter(orig) : null); if (obj2 == null) { IGenericParameterProvider obj3 = ((provider is MemberReference) ? provider : null); if (obj3 == null) { return null; } TypeReference declaringType = ((MemberReference)obj3).DeclaringType; if (declaringType == null) { return null; } obj2 = ((IGenericParameterProvider)(object)declaringType).ResolveGenericParameter(orig); } return (GenericParameter)obj2; } public static IMetadataTokenProvider Relink(this IMetadataTokenProvider mtp, Relinker relinker, IGenericParameterProvider context) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown if (mtp is TypeReference) { return (IMetadataTokenProvider)(object)Extensions.Relink((TypeReference)mtp, relinker, context); } if (mtp is MethodReference) { return Extensions.Relink((MethodReference)mtp, relinker, context); } if (mtp is FieldReference) { return Extensions.Relink((FieldReference)mtp, relinker, context); } if (mtp is ParameterDefinition) { return (IMetadataTokenProvider)(object)Extensions.Relink((ParameterDefinition)mtp, relinker, context); } if (mtp is CallSite) { return (IMetadataTokenProvider)(object)Extensions.Relink((CallSite)mtp, relinker, context); } throw new InvalidOperationException($"MonoMod can't handle metadata token providers of the type {((object)mtp).GetType()}"); } public static TypeReference Relink(this TypeReference type, Relinker relinker, IGenericParameterProvider context) { //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Expected O, but got Unknown //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0066: 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_0076: Expected O, but got Unknown //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Expected O, but got Unknown if (type == null) { return null; } TypeSpecification val = (TypeSpecification)(object)((type is TypeSpecification) ? type : null); if (val != null) { TypeReference val2 = val.ElementType.Relink(relinker, context); if (type.IsSentinel) { return (TypeReference)new SentinelType(val2); } if (type.IsByReference) { return (TypeReference)new ByReferenceType(val2); } if (type.IsPointer) { return (TypeReference)new PointerType(val2); } if (type.IsPinned) { return (TypeReference)new PinnedType(val2); } if (type.IsArray) { ArrayType val3 = new ArrayType(val2, ((ArrayType)type).Rank); for (int i = 0; i < val3.Rank; i++) { val3.Dimensions[i] = ((ArrayType)type).Dimensions[i]; } return (TypeReference)(object)val3; } if (type.IsRequiredModifier) { return (TypeReference)new RequiredModifierType(((RequiredModifierType)type).ModifierType.Relink(relinker, context), val2); } if (type.IsOptionalModifier) { return (TypeReference)new OptionalModifierType(((OptionalModifierType)type).ModifierType.Relink(relinker, context), val2); } if (type.IsGenericInstance) { GenericInstanceType val4 = new GenericInstanceType(val2); Enumerator<TypeReference> enumerator = ((GenericInstanceType)type).GenericArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current = enumerator.Current; val4.GenericArguments.Add(current?.Relink(relinker, context)); } return (TypeReference)(object)val4; } finally { ((IDisposable)enumerator).Dispose(); } } if (type.IsFunctionPointer) { FunctionPointerType val5 = (FunctionPointerType)type; val5.ReturnType = val5.ReturnType.Relink(relinker, context); for (int j = 0; j < val5.Parameters.Count; j++) { ((ParameterReference)val5.Parameters[j]).ParameterType = ((ParameterReference)val5.Parameters[j]).ParameterType.Relink(relinker, context); } return (TypeReference)(object)val5; } throw new NotSupportedException($"MonoMod can't handle TypeSpecification: {((MemberReference)type).FullName} ({((object)type).GetType()})"); } if (!type.IsGenericParameter || context == null) { return (TypeReference)relinker((IMetadataTokenProvider)(object)type, context); } GenericParameter val6 = context.ResolveGenericParameter((GenericParameter)type); if (val6 == null) { throw new RelinkTargetNotFoundException(string.Format("{0} {1} (context: {2})", "MonoMod relinker failed finding", ((MemberReference)type).FullName, context), (IMetadataTokenProvider)(object)type, (IMetadataTokenProvider)(object)context); } for (int k = 0; k < val6.Constraints.Count; k++) { if (!val6.Constraints[k].GetConstraintType().IsGenericInstance) { val6.Constraints[k] = val6.Constraints[k].Relink(relinker, context); } } return (TypeReference)(object)val6; } public static IMetadataTokenProvider Relink(this MethodReference method, Relinker relinker, IGenericParameterProvider context) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: 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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Expected O, but got Unknown if (method.IsGenericInstance) { GenericInstanceMethod val = (GenericInstanceMethod)method; GenericInstanceMethod val2 = new GenericInstanceMethod((MethodReference)((MethodSpecification)val).ElementMethod.Relink(relinker, context)); Enumerator<TypeReference> enumerator = val.GenericArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current = enumerator.Current; val2.GenericArguments.Add(current.Relink(relinker, context)); } } finally { ((IDisposable)enumerator).Dispose(); } return (IMetadataTokenProvider)(MethodReference)relinker((IMetadataTokenProvider)(object)val2, context); } MethodReference val3 = new MethodReference(((MemberReference)method).Name, method.ReturnType, ((MemberReference)method).DeclaringType.Relink(relinker, context)); val3.CallingConvention = method.CallingConvention; val3.ExplicitThis = method.ExplicitThis; val3.HasThis = method.HasThis; Enumerator<GenericParameter> enumerator2 = method.GenericParameters.GetEnumerator(); try { while (enumerator2.MoveNext()) { GenericParameter current2 = enumerator2.Current; GenericParameter val4 = Update(new GenericParameter(((MemberReference)current2).Name, current2.Owner) { Attributes = current2.Attributes }, current2.Position, current2.Type); val3.GenericParameters.Add(val4); Enumerator<TypeReference> enumerator = current2.Constraints.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current3 = enumerator.Current; val4.Constraints.Add(current3.Relink(relinker, (IGenericParameterProvider)(object)val3)); } } finally { ((IDisposable)enumerator).Dispose(); } } } finally { ((IDisposable)enumerator2).Dispose(); } val3.ReturnType = val3.ReturnType?.Relink(relinker, (IGenericParameterProvider)(object)val3); Enumerator<ParameterDefinition> enumerator3 = method.Parameters.GetEnumerator(); try { while (enumerator3.MoveNext()) { ParameterDefinition current4 = enumerator3.Current; ((ParameterReference)current4).ParameterType = ((ParameterReference)curre
UMM/Mods/Runtime Unity Editor/RuntimeUnityEditor.Core.dll
Decompiled a month 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.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Timers; using HarmonyLib; using Microsoft.CodeAnalysis; using Mono.CSharp; using RuntimeUnityEditor.Core.ChangeHistory; using RuntimeUnityEditor.Core.Clipboard; using RuntimeUnityEditor.Core.Gizmos.lib; using RuntimeUnityEditor.Core.Gizmos.lib.Drawers; using RuntimeUnityEditor.Core.Inspector; using RuntimeUnityEditor.Core.Inspector.Entries; using RuntimeUnityEditor.Core.ObjectTree; using RuntimeUnityEditor.Core.ObjectView; using RuntimeUnityEditor.Core.REPL; using RuntimeUnityEditor.Core.REPL.MCS; using RuntimeUnityEditor.Core.UI; using RuntimeUnityEditor.Core.Utils; using RuntimeUnityEditor.Core.Utils.Abstractions; using RuntimeUnityEditor.Core.Utils.ObjectDumper; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("RuntimeUnityEditor.Bepin5")] [assembly: InternalsVisibleTo("RuntimeUnityEditor.Bepin6.IL2CPP")] [assembly: InternalsVisibleTo("RuntimeUnityEditor.UMM")] [assembly: AssemblyCompany("https://github.com/ManlyMarco/RuntimeUnityEditor")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright GPL-3 © 2018")] [assembly: AssemblyFileVersion("6.3.0.0")] [assembly: AssemblyInformationalVersion("6.3+3bd95bfd1fb716fd440f3c30b4a05b364238d2fc")] [assembly: AssemblyProduct("RuntimeUnityEditor")] [assembly: AssemblyTitle("In-game inspector and debugging tools for applications made with Unity3D game engine")] [assembly: AssemblyVersion("6.3.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } } internal static class FailedToGetGenericArguments { } namespace RuntimeUnityEditor.Core { public interface IFeature { bool Enabled { get; set; } FeatureDisplayType DisplayType { get; } string DisplayName { get; } void OnInitialize(InitSettings initSettings); void OnUpdate(); void OnLateUpdate(); void OnOnGUI(); void OnEditorShownChanged(bool visible); } public enum FeatureDisplayType { Hidden, Feature, Window } public abstract class FeatureBase<T> : IFeature where T : FeatureBase<T> { private static bool _initialized; protected string SettingCategory = "Features"; private protected string _displayName; private InitSettings.Setting<bool> _enabled; private bool _initialEnabled = true; public static bool Initialized => _initialized; public static T Instance { get; private set; } public virtual string DisplayName { get { return _displayName ?? (_displayName = GetType().Name); } set { _displayName = value; } } public virtual bool Enabled { get { if (_enabled != null) { return _enabled.Value; } return _initialEnabled; } set { if (_enabled == null) { _initialEnabled = value; } else if (_enabled.Value != value) { bool visible = Visible; _enabled.Value = value; bool visible2 = Visible; if (visible != visible2) { OnVisibleChanged(visible2); } } } } public bool Visible { get { if (Enabled) { return RuntimeUnityEditorCore.Instance.Show; } return false; } } public FeatureDisplayType DisplayType { get; protected set; } protected FeatureBase() { DisplayType = FeatureDisplayType.Feature; Instance = (T)this; } void IFeature.OnInitialize(InitSettings initSettings) { if (Initialized) { throw new InvalidOperationException("The Feature is already initialized"); } Initialize(initSettings); AfterInitialized(initSettings); _initialized = true; } protected virtual void AfterInitialized(InitSettings initSettings) { _enabled = initSettings.RegisterSetting(SettingCategory, DisplayName + " enabled", _initialEnabled, string.Empty); } void IFeature.OnUpdate() { if (_initialized && Enabled) { try { Update(); } catch (Exception content) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Error, content); } } } void IFeature.OnLateUpdate() { if (_initialized && Enabled) { try { LateUpdate(); } catch (Exception content) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Error, content); } } } void IFeature.OnOnGUI() { if (_initialized && Enabled) { try { OnGUI(); } catch (Exception content) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Error, content); } } } void IFeature.OnEditorShownChanged(bool visible) { if (_initialized && Enabled) { OnVisibleChanged(visible); } } protected virtual void OnVisibleChanged(bool visible) { try { VisibleChanged(visible); } catch (Exception content) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Error, content); } } protected abstract void Initialize(InitSettings initSettings); protected virtual void Update() { } protected virtual void LateUpdate() { } protected virtual void OnGUI() { } protected virtual void VisibleChanged(bool visible) { } } public class ContextMenu : FeatureBase<ContextMenu> { private object _obj; private MemberInfo _objMemberInfo; private Func<object> _getValue; private Action<object> _setValue; private string _objName; private Rect _windowRect; private int _windowId; private List<ContextMenuEntry> _currentContents; public override bool Enabled { get { if (base.Enabled) { if (_obj == null) { return (object)_objMemberInfo != null; } return true; } return false; } set { if (value && _obj == null && (object)_objMemberInfo == null) { value = false; } base.Enabled = value; } } public static List<ContextMenuEntry> MenuContents { get; } = new List<ContextMenuEntry>(); protected override void Initialize(InitSettings initSettings) { MenuContents.Insert(0, ContextMenuEntry.Create("! Destroyed unity Object !", (Object o, MemberInfo info) => !Object.op_Implicit(o), null)); MenuContents.AddRange(new ContextMenuEntry[8] { ContextMenuEntry.Separator, new ContextMenuEntry("Export texture...", delegate(object o, MemberInfo info) { if (!(o is Texture) && !(o is Sprite)) { Material val15 = (Material)((o is Material) ? o : null); if (val15 == null || !((Object)(object)val15.mainTexture != (Object)null)) { Image val16 = (Image)((o is Image) ? o : null); if (val16 == null || !((Object)(object)((Graphic)val16).mainTexture != (Object)null)) { RawImage val17 = (RawImage)((o is RawImage) ? o : null); if (val17 == null || !((Object)(object)((Graphic)val17).mainTexture != (Object)null)) { Renderer val18 = (Renderer)((o is Renderer) ? o : null); if (val18 != null && (Object)(object)(val18.sharedMaterial ?? val18.material) != (Object)null) { return (Object)(object)(val18.sharedMaterial ?? val18.material).mainTexture != (Object)null; } return false; } } } } return true; }, delegate(object o, MemberInfo info, string name) { Texture val9 = (Texture)((o is Texture) ? o : null); if (val9 != null) { val9.SaveTextureToFileWithDialog(); } else { Sprite val10 = (Sprite)((o is Sprite) ? o : null); if (val10 != null) { ((Texture)(object)val10.texture).SaveTextureToFileWithDialog(); } else { Material val11 = (Material)((o is Material) ? o : null); if (val11 != null) { val11.mainTexture.SaveTextureToFileWithDialog(); } else { Image val12 = (Image)((o is Image) ? o : null); if (val12 != null) { ((Graphic)val12).mainTexture.SaveTextureToFileWithDialog(); } else { RawImage val13 = (RawImage)((o is RawImage) ? o : null); if (val13 != null) { ((Graphic)val13).mainTexture.SaveTextureToFileWithDialog(); } else { Renderer val14 = (Renderer)((o is Renderer) ? o : null); if (val14 != null) { (val14.sharedMaterial ?? val14.material).mainTexture.SaveTextureToFileWithDialog(); } } } } } } }), new ContextMenuEntry("Replace texture...", delegate(object o, MemberInfo info) { if (!(o is Texture2D) && (!(o is Texture) || _setValue == null) && !(o is Material) && !(o is RawImage)) { Renderer val8 = (Renderer)((o is Renderer) ? o : null); if (val8 != null) { if (!((Object)(object)val8.sharedMaterial != (Object)null)) { return (Object)(object)val8.material != (Object)null; } return true; } return false; } return true; }, delegate(object o, MemberInfo info, string name) { string filename = "null"; Texture2D newTex = TextureUtils.LoadTextureFromFileWithDialog(ref filename); Texture val2 = (Texture)((o is Texture) ? o : null); if (val2 != null) { try { if (_setValue != null) { object current = _getValue?.Invoke(); Change.Action("(ContextMenu)::" + _objName + " = Texture2D.LoadImage(File.ReadAllBytes(\"" + filename + "\"))", o, delegate { _setValue(newTex); }, (current != null) ? ((Action<object>)delegate { _setValue(current); }) : null); return; } throw new NotImplementedException(); } catch (Exception ex) { if (!(ex is NotImplementedException)) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Error, ex); } Texture2D val3 = (Texture2D)(object)((val2 is Texture2D) ? val2 : null); if (val3 != null) { try { ((Action<Texture2D, Texture2D>)delegate(Texture2D target, Texture2D source) { target.LoadRawTextureData(source.GetRawTextureData()); target.Apply(true); })(val3, newTex); Change.Report("(ContextMenu)::" + _objName + ".LoadImage(File.ReadAllBytes(\"" + filename + "\"))"); return; } catch (Exception content) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Error, content); return; } finally { Object.Destroy((Object)(object)newTex); } } return; } } Material val4 = (Material)((o is Material) ? o : null); if (val4 != null) { Change.WithUndo("(ContextMenu)::" + _objName + ".mainTexture = Texture2D.LoadImage(File.ReadAllBytes(\"" + filename + "\"))", val4, (Texture)(object)newTex, delegate(Material material, Texture texture2D) { material.mainTexture = texture2D; }, null, null, val4.mainTexture); } else { Image val5 = (Image)((o is Image) ? o : null); if (val5 != null && (Object)(object)((Graphic)val5).material != (Object)null) { Change.WithUndo("(ContextMenu)::" + _objName + ".material.mainTexture = Texture2D.LoadImage(File.ReadAllBytes(\"" + filename + "\"))", ((Graphic)val5).material, (Texture)(object)newTex, delegate(Material material, Texture texture2D) { material.mainTexture = texture2D; }, null, null, ((Graphic)val5).material.mainTexture); } else { RawImage val6 = (RawImage)((o is RawImage) ? o : null); if (val6 != null) { Change.WithUndo("(ContextMenu)::" + _objName + ".texture = Texture2D.LoadImage(File.ReadAllBytes(\"" + filename + "\"))", val6, (Texture)(object)newTex, delegate(RawImage rawImage, Texture texture2D) { rawImage.texture = texture2D; }, null, null, val6.texture); } else { Renderer val7 = (Renderer)((o is Renderer) ? o : null); if (val7 != null) { if ((Object)(object)val7.sharedMaterial != (Object)null) { Change.WithUndo("(ContextMenu)::" + _objName + ".sharedMaterial.mainTexture = Texture2D.LoadImage(File.ReadAllBytes(\"" + filename + "\"))", val7.sharedMaterial, (Texture)(object)newTex, delegate(Material material, Texture texture2D) { material.mainTexture = texture2D; }, null, null, val7.sharedMaterial.mainTexture); } else { Change.WithUndo("(ContextMenu)::" + _objName + ".material.mainTexture = Texture2D.LoadImage(File.ReadAllBytes(\"" + filename + "\"))", val7.material, (Texture)(object)newTex, delegate(Material material, Texture texture2D) { material.mainTexture = texture2D; }, null, null, val7.material.mainTexture); } } } } } }), ContextMenuEntry.Create("Export mesh to .obj", (Renderer o, MemberInfo info) => MeshExport.CanExport(o), delegate(Renderer o, MemberInfo info, string name) { MeshExport.ExportObj(o, bakedMesh: false, bakedWorldPosition: false); }), ContextMenuEntry.Create("Export mesh to .obj (Baked)", (Renderer o, MemberInfo info) => MeshExport.CanExport(o), delegate(Renderer o, MemberInfo info, string name) { MeshExport.ExportObj(o, bakedMesh: true, bakedWorldPosition: false); }), ContextMenuEntry.Create("Export mesh to .obj (World)", (Renderer o, MemberInfo info) => MeshExport.CanExport(o), delegate(Renderer o, MemberInfo info, string name) { MeshExport.ExportObj(o, bakedMesh: true, bakedWorldPosition: true); }), new ContextMenuEntry("Dump object to file...", (object o, MemberInfo _) => o != null, delegate(object o, MemberInfo info, string name) { Dumper.DumpToTempFile(o, name); }), ContextMenuEntry.Create("Destroy", (Object o, MemberInfo info) => Object.op_Implicit(o), delegate(Object o, MemberInfo info, string name) { Transform val = (Transform)(object)((o is Transform) ? o : null); Change.Action("(ContextMenu)::UnityEngine.Object.Destroy({0})", (Object)((val != null) ? ((object)((Component)val).gameObject) : ((object)o)), (Action<Object>)Object.Destroy, (Action<Object>)null); }) }); _windowId = base.GetHashCode(); Enabled = false; base.DisplayType = FeatureDisplayType.Hidden; } public void Show(object obj, ICacheEntry objEntry) { if (objEntry == null) { throw new ArgumentNullException("objEntry"); } if (obj == null && objEntry.CanEnterValue()) { obj = objEntry.GetValue(); } string memberFullName = ((objEntry is FieldCacheEntry fieldCacheEntry) ? (fieldCacheEntry.FieldInfo.DeclaringType?.Name + "." + fieldCacheEntry.FieldInfo.Name) : ((objEntry is PropertyCacheEntry propertyCacheEntry) ? (propertyCacheEntry.PropertyInfo.DeclaringType?.Name + "." + propertyCacheEntry.PropertyInfo.Name) : ((objEntry != null) ? objEntry.Name() : GeneralExtensions.FullDescription(obj.GetType())))); bool flag = objEntry.CanSetValue(); Show(obj, objEntry.MemberInfo, memberFullName, flag ? new Action<object>(objEntry.SetValue) : null, flag ? new Func<object>(objEntry.GetValue) : null); } public void Show(object obj) { Show(obj, null, (obj != null) ? GeneralExtensions.FullDescription(obj.GetType()) : null, null, null); } public void Show(object obj, MemberInfo memberInfo, string memberFullName, Action<object> setObj, Func<object> getObj) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: 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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) Vector3 mousePosition = UnityInput.Current.mousePosition; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(mousePosition.x, (float)Screen.height - mousePosition.y); _windowRect = new Rect(val.x, val.y, 100f, 100f); if (obj == null && getObj != null) { obj = getObj(); } if (obj != null || (object)memberInfo != null) { _obj = obj; _objMemberInfo = memberInfo ?? (obj as MemberInfo); _objName = memberFullName ?? (((object)_objMemberInfo != null) ? (_objMemberInfo.DeclaringType?.Name + "." + _objMemberInfo.Name) : ((obj != null) ? GeneralExtensions.FullDescription(obj.GetType()) : null)); _setValue = setObj; _getValue = getObj; _currentContents = MenuContents.Where((ContextMenuEntry x) => x.IsVisible(_obj, _objMemberInfo)).ToList(); if (_currentContents.Count > 0 && _currentContents[0].IsSeparator()) { _currentContents.RemoveAt(0); } _windowId++; Enabled = true; } else { _obj = null; Enabled = false; } } public void DrawContextButton(object obj, ICacheEntry objEntry) { if (obj != null && GUILayout.Button("...", IMGUIUtils.LayoutOptionsExpandWidthFalse)) { Show(obj, objEntry); } } public void DrawContextButton(object obj, MemberInfo memberInfo, string memberFullName, Action<object> setObj, Func<object> getObj) { if (obj != null && GUILayout.Button("...", IMGUIUtils.LayoutOptionsExpandWidthFalse)) { Show(obj, memberInfo, memberFullName, setObj, getObj); } } protected override void OnGUI() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_0047: 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) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) int num = _windowId - 10; GUILayout.Window(num, new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), new WindowFunction(DisableOnClickWindowFunc), string.Empty, GUI.skin.label, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.color = Color.white; IMGUIUtils.DrawSolidBox(_windowRect); _windowRect = GUILayout.Window(_windowId, _windowRect, new WindowFunction(DrawMenu), _objName, (GUILayoutOption[])(object)new GUILayoutOption[0]); IMGUIUtils.EatInputInRect(_windowRect); GUI.BringWindowToFront(num); GUI.BringWindowToFront(_windowId); if (((Rect)(ref _windowRect)).xMax > (float)Screen.width) { ((Rect)(ref _windowRect)).x = (float)Screen.width - ((Rect)(ref _windowRect)).width; } if (((Rect)(ref _windowRect)).yMax > (float)Screen.height) { ((Rect)(ref _windowRect)).y = (float)Screen.height - ((Rect)(ref _windowRect)).height; } } private void DisableOnClickWindowFunc(int id) { if (GUILayout.Button(GUIContent.none, GUI.skin.label, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayoutShim.ExpandWidth(expand: true), GUILayoutShim.ExpandHeight(expand: true) })) { Enabled = false; } } private void DrawMenu(int id) { if (_currentContents == null || _currentContents.Count == 0) { Enabled = false; return; } GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); for (int i = 0; i < _currentContents.Count; i++) { if (_currentContents[i].Draw(_obj, _objMemberInfo, _objName)) { Enabled = false; } } GUILayout.EndVertical(); } } public readonly struct ContextMenuEntry { public static readonly ContextMenuEntry Separator; private readonly GUIContent _name; private readonly Func<object, MemberInfo, bool> _onCheckVisible; private readonly Action<object, MemberInfo, string> _onClick; public static ContextMenuEntry Create<T>(string name, Func<T, MemberInfo, bool> onCheckVisible, Action<T, MemberInfo, string> onClick) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown return Create(new GUIContent(name), onCheckVisible, onClick); } public static ContextMenuEntry Create<T>(GUIContent name, Func<T, MemberInfo, bool> onCheckVisible, Action<T, MemberInfo, string> onClick) { return new ContextMenuEntry(name, (onCheckVisible != null) ? ((Func<object, MemberInfo, bool>)((object o, MemberInfo info) => o is T arg && onCheckVisible(arg, info))) : null, (onClick != null) ? ((Action<object, MemberInfo, string>)delegate(object o, MemberInfo info, string objName) { onClick((T)o, info, objName); }) : null); } public ContextMenuEntry(string name, Func<object, MemberInfo, bool> onCheckVisible, Action<object, MemberInfo, string> onClick) : this(new GUIContent(name), onCheckVisible, onClick) { }//IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown public ContextMenuEntry(GUIContent name, Func<object, MemberInfo, bool> onCheckVisible, Action<object, MemberInfo, string> onClick) { _name = name; _onCheckVisible = onCheckVisible; _onClick = onClick; } public bool IsSeparator() { if (_name == null) { return _onClick == null; } return false; } public bool IsVisible(object obj, MemberInfo info) { if (_onCheckVisible != null) { return _onCheckVisible(obj, info); } return true; } public bool Draw(object obj, MemberInfo info, string name) { if (_onClick != null) { if (GUILayout.Button(_name, (GUILayoutOption[])(object)new GUILayoutOption[0])) { if (IMGUIUtils.IsMouseRightClick()) { return false; } Action<object, MemberInfo, string> onClick = _onClick; object obj2 = name; if (obj2 == null) { GUIContent name2 = _name; obj2 = ((name2 != null) ? name2.text : null) ?? "<NULL>"; } onClick(obj, info, (string)obj2); return true; } } else if (_name != null) { GUILayout.Label(_name, (GUILayoutOption[])(object)new GUILayoutOption[0]); } else { GUILayout.Space(4f); } return false; } } public sealed class CursorUnlocker : FeatureBase<CursorUnlocker> { private bool _obsoleteCursor; private PropertyInfo _curLockState; private PropertyInfo _curVisible; private int _previousCursorLockState; private bool _previousCursorVisible; protected override void Initialize(InitSettings initSettings) { Type typeFromHandle = typeof(Cursor); _curLockState = typeFromHandle.GetProperty("lockState", BindingFlags.Static | BindingFlags.Public); _curVisible = typeFromHandle.GetProperty("visible", BindingFlags.Static | BindingFlags.Public); if ((object)_curLockState == null || (object)_curVisible == null) { _obsoleteCursor = true; _curLockState = typeof(Screen).GetProperty("lockCursor", BindingFlags.Static | BindingFlags.Public); _curVisible = typeof(Screen).GetProperty("showCursor", BindingFlags.Static | BindingFlags.Public); if ((object)_curLockState == null || (object)_curVisible == null) { throw new InvalidOperationException("Unsupported Cursor class"); } } DisplayName = "Unlock cursor"; Enabled = true; base.DisplayType = FeatureDisplayType.Hidden; } protected override void Update() { if (_obsoleteCursor) { _curLockState.SetValue(null, false, null); } else { _curLockState.SetValue(null, 0, null); } _curVisible.SetValue(null, true, null); } protected override void LateUpdate() { if (_obsoleteCursor) { _curLockState.SetValue(null, false, null); } else { _curLockState.SetValue(null, 0, null); } _curVisible.SetValue(null, true, null); } protected override void OnGUI() { if (_obsoleteCursor) { _curLockState.SetValue(null, false, null); } else { _curLockState.SetValue(null, 0, null); } _curVisible.SetValue(null, true, null); } protected override void VisibleChanged(bool visible) { if (visible) { _previousCursorLockState = (_obsoleteCursor ? Convert.ToInt32((bool)_curLockState.GetValue(null, null)) : ((int)_curLockState.GetValue(null, null))); _previousCursorVisible = (bool)_curVisible.GetValue(null, null); } else if (!_previousCursorVisible || _previousCursorLockState != 0) { if (_obsoleteCursor) { _curLockState.SetValue(null, Convert.ToBoolean(_previousCursorLockState), null); } else { _curLockState.SetValue(null, _previousCursorLockState, null); } _curVisible.SetValue(null, _previousCursorVisible, null); } } } public class MouseInspect : FeatureBase<MouseInspect> { private static readonly StringBuilder _hoverTextSb = new StringBuilder(100); private static string _hoverText = string.Empty; private GUIStyle _labelSkin; protected override void Initialize(InitSettings initSettings) { DisplayName = "Mouse inspect"; } protected override void Update() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) Camera main = Camera.main; Transform val = DoRaycast(main); List<RectTransform> list = DoCanvas(main); Transform selectedTransform = FeatureBase<ObjectTreeViewer>.Instance.SelectedTransform; _hoverTextSb.Length = 0; if ((Object)(object)val != (Object)null) { _hoverTextSb.AppendFormat("Raycast hit:\n{0}0: {1} pos={2}\n", ((Object)(object)selectedTransform == (Object)(object)val) ? "> " : "", ((Object)val).name, val.position); } if (list.Count > 0) { _hoverTextSb.AppendLine("Canvas hits:"); for (int i = 0; i < list.Count && i < 10; i++) { RectTransform val2 = list[i]; _hoverTextSb.AppendFormat("{0}{1}: {2} pos={3} size={4}\n", ((Object)(object)selectedTransform == (Object)(object)val2) ? "> " : "", i + 1, ((Object)val2).name, ((Transform)val2).position, val2.sizeDelta); } } if (_hoverTextSb.Length > 0) { if (FeatureBase<ObjectTreeViewer>.Initialized) { _hoverTextSb.Append("[ Press Middle Mouse Button to browse to the next object ]"); if (UnityInput.Current.GetMouseButtonDown(2)) { List<Transform> list2 = (from x in Enumerable.Repeat<Transform>(val, 1).Concat(list.Cast<Transform>()) where (Object)(object)x != (Object)null select x).ToList(); int num = list2.IndexOf(selectedTransform); Transform target = list2.Concat(list2).Skip(num + 1).First(); FeatureBase<ObjectTreeViewer>.Instance.SelectAndShowObject(target); } } _hoverText = _hoverTextSb.ToString(); } else { _hoverText = string.Empty; } } protected override void OnGUI() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0046: 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_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) if (_hoverText.Length > 0) { if (_labelSkin == null) { _labelSkin = GUI.skin.label.CreateCopy(); } _labelSkin.alignment = (TextAnchor)0; Vector3 mousePosition = UnityInput.Current.mousePosition; Rect rect = default(Rect); ((Rect)(ref rect))..ctor((float)((int)mousePosition.x + 5), (float)(Screen.height - (int)mousePosition.y + 20), (float)(Screen.width / 2), 500f); if ((int)((Rect)(ref rect)).x > Screen.width / 2) { ((Rect)(ref rect)).x = (int)(((Rect)(ref rect)).x - ((Rect)(ref rect)).width); _labelSkin.alignment = (TextAnchor)2; } if ((int)((Rect)(ref rect)).y > Screen.height / 2) { ((Rect)(ref rect)).y = (int)(((Rect)(ref rect)).y - (((Rect)(ref rect)).height + 23f)); GUIStyle labelSkin = _labelSkin; labelSkin.alignment = (TextAnchor)(labelSkin.alignment + 6); } IMGUIUtils.DrawLabelWithOutline(rect, _hoverText, _labelSkin, Color.white, Color.black, 2); } } private static Transform DoRaycast(Camera camera) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)camera == (Object)null) { return null; } Ray val = camera.ScreenPointToRay(UnityInput.Current.mousePosition); RaycastHit val2 = default(RaycastHit); if (!Physics.Raycast(val, ref val2, 1000f)) { return null; } return ((RaycastHit)(ref val2)).transform; } private static List<RectTransform> DoCanvas(Camera camera) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) Vector2 mousePosition = Vector2.op_Implicit(UnityInput.Current.mousePosition); IEnumerable<RectTransform> source = Object.FindObjectsOfType<RectTransform>().Where(delegate(RectTransform rt) { //IL_000c: 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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)rt) && rt.sizeDelta.x > 0f && rt.sizeDelta.y > 0f && ((Component)rt).gameObject.activeInHierarchy) { Canvas componentInParent = ((Component)rt).GetComponentInParent<Canvas>(); if ((Object)(object)componentInParent != (Object)null && ((Behaviour)componentInParent).enabled && ((Component)rt).GetComponentsInParent<CanvasGroup>().All((CanvasGroup x) => x.alpha > 0.1f)) { Camera val = (((int)componentInParent.renderMode == 0) ? null : (((Object)(object)componentInParent.worldCamera != (Object)null) ? componentInParent.worldCamera : camera)); return RectTransformUtility.RectangleContainsScreenPoint(rt, mousePosition, val); } } return false; }); return source.OrderBy(delegate(RectTransform x) { //IL_0001: 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) Vector2 sizeDelta = x.sizeDelta; return ((Vector2)(ref sizeDelta)).sqrMagnitude; }).ToList(); } } public sealed class WireframeFeature : FeatureBase<WireframeFeature> { [CompilerGenerated] private sealed class <UpdateCo>d__9 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public WireframeFeature <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <UpdateCo>d__9(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Expected O, but got Unknown //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Expected O, but got Unknown //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Expected O, but got Unknown //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Expected O, but got Unknown //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Expected O, but got Unknown //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Expected O, but got Unknown int num = <>1__state; WireframeFeature wireframeFeature = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; if (wireframeFeature._updateCoRunning) { return false; } wireframeFeature._updateCoRunning = true; wireframeFeature.CollectEffects(); wireframeFeature.SetEffectEnabled(enabled: false); <>2__current = null; <>1__state = 1; return true; case 1: <>1__state = -1; if (wireframeFeature.Enabled) { <>2__current = null; <>1__state = 2; return true; } goto IL_0085; case 2: <>1__state = -1; goto IL_0085; case 3: <>1__state = -1; goto IL_0107; case 4: { <>1__state = -1; goto IL_0107; } IL_0107: if (wireframeFeature.Enabled) { wireframeFeature.SetEffectEnabled(enabled: false); <>2__current = null; <>1__state = 4; return true; } Camera.onPreRender = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPreRender, (Delegate?)new CameraCallback(OnPreRender)); Camera.onPostRender = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPostRender, (Delegate?)new CameraCallback(OnPostRender)); break; IL_0085: if (wireframeFeature.Enabled) { Camera.onPreRender = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPreRender, (Delegate?)new CameraCallback(OnPreRender)); Camera.onPostRender = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPostRender, (Delegate?)new CameraCallback(OnPostRender)); <>2__current = null; <>1__state = 3; return true; } break; } wireframeFeature.SetEffectEnabled(enabled: true); wireframeFeature._updateCoRunning = false; return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static readonly string[] _disableEffectNames = new string[5] { "GlobalFog", "BloomAndFlares", "CustomRender", "AmplifyColorEffect", "PostProcessLayer" }; private MonoBehaviour _monoBehaviour; private readonly List<Behaviour> _disabledEffects = new List<Behaviour>(); private static Camera _targetCamera; private bool _updateCoRunning; public override bool Enabled { get { return base.Enabled; } set { if (base.Enabled != value) { base.Enabled = value; if (value) { _monoBehaviour.AbstractStartCoroutine(UpdateCo()); } } } } protected override void Initialize(InitSettings initSettings) { UnityFeatureHelper.EnsureCameraRenderEventsAreAvailable(); DisplayName = "Wireframe"; Enabled = false; _monoBehaviour = initSettings.PluginMonoBehaviour; } private IEnumerator UpdateCo() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <UpdateCo>d__9(0) { <>4__this = this }; } private void CollectEffects() { _disabledEffects.Clear(); _disabledEffects.AddRange(from b in Object.FindObjectsOfType<Camera>().SelectMany((Camera cam) => ((IEnumerable<string>)_disableEffectNames).Select((Func<string, Component>)((Component)cam).GetComponent)).OfType<Behaviour>() where Object.op_Implicit((Object)(object)b) && b.enabled select b); } private void SetEffectEnabled(bool enabled) { for (int i = 0; i < _disabledEffects.Count; i++) { Behaviour val = _disabledEffects[i]; if (Object.op_Implicit((Object)(object)val)) { val.enabled = enabled; } } } private static void OnPreRender(Camera cam) { if (!GL.wireframe) { _targetCamera = cam; GL.wireframe = true; } } private static void OnPostRender(Camera cam) { if ((Object)(object)_targetCamera == (Object)(object)cam) { GL.wireframe = false; _targetCamera = null; } } } public class RuntimeUnityEditorCore { public const string Version = "6.3"; public const string GUID = "RuntimeUnityEditor"; private static InitSettings _initSettings; private readonly List<IFeature> _initializedFeatures = new List<IFeature>(); private readonly InitSettings.Setting<KeyCode> _showHotkey; public static string InstalledVersion => "6.3"; public static RuntimeUnityEditorCore Instance { get; private set; } public KeyCode ShowHotkey { get { //IL_0010: Unknown result type (might be due to invalid IL or missing references) return (KeyCode)(((??)_showHotkey?.Value) ?? 293); } set { //IL_0006: Unknown result type (might be due to invalid IL or missing references) _showHotkey.Value = value; } } public bool Show { get { return Taskbar.Instance.Enabled; } set { if (Taskbar.Instance.Enabled != value) { Taskbar.Instance.Enabled = value; for (int i = 0; i < _initializedFeatures.Count; i++) { _initializedFeatures[i].OnEditorShownChanged(value); } } } } public IEnumerable<IFeature> InitializedFeatures => _initializedFeatures; internal static MonoBehaviour PluginObject => _initSettings.PluginMonoBehaviour; internal static ILoggerWrapper Logger => _initSettings.LoggerWrapper; public static bool IsInitialized() { lock ("RuntimeUnityEditor") { return Instance != null; } } public void AddFeature(IFeature feature) { AddFeatureInt(feature); Taskbar.Instance.SetFeatures(_initializedFeatures); } public bool RemoveFeature(IFeature feature) { if (_initializedFeatures.Remove(feature)) { Taskbar.Instance.SetFeatures(_initializedFeatures); return true; } return false; } internal RuntimeUnityEditorCore(InitSettings initSettings) { lock ("RuntimeUnityEditor") { if (Instance != null) { throw new InvalidOperationException("Can create only one instance of the Core object"); } _initSettings = initSettings; Instance = this; try { _showHotkey = initSettings.RegisterSetting<KeyCode>("General", "Open/close runtime editor", (KeyCode)293, ""); Type typeFromHandle = typeof(IFeature); List<IFeature> list = new List<IFeature>(); int num = 0; foreach (Type item in typeof(RuntimeUnityEditorCore).Assembly.GetTypesSafe()) { try { if (!item.IsAbstract && typeFromHandle.IsAssignableFrom(item)) { num++; try { list.Add((IFeature)Activator.CreateInstance(item)); } catch (Exception arg) { Logger.Log(LogLevel.Warning, $"Failed to create instance of {item.Name} - {arg}"); } } } catch (TypeLoadException arg2) { Logger.Log(LogLevel.Warning, $"Failed to load type information of {item.Name}, some dll is likly missing - {arg2}"); } } foreach (IFeature item2 in list) { try { AddFeatureInt(item2); } catch (Exception ex) { if (item2 is Taskbar) { throw new InvalidOperationException("WindowManager somehow failed to initialize! I am die, thank you forever.", ex); } Logger.Log(LogLevel.Warning, "Failed to initialize " + item2.GetType().Name + " - " + ((ex is NotSupportedException) ? ex.Message : ex.ToString())); } } Taskbar.Instance.SetFeatures(_initializedFeatures); Logger.Log(LogLevel.Info, string.Format("Successfully initialized {0}/{1} features: {2}", _initializedFeatures.Count, num, string.Join(", ", _initializedFeatures.Select((IFeature x) => x.GetType().Name).ToArray()))); } catch { Instance = null; throw; } } } private void AddFeatureInt(IFeature feature) { feature.OnInitialize(_initSettings); _initializedFeatures.Add(feature); } internal void OnGUI() { if (Show) { GUISkin skin = GUI.skin; GUI.skin = InterfaceMaker.CustomSkin; for (int i = 0; i < _initializedFeatures.Count; i++) { _initializedFeatures[i].OnOnGUI(); } GUI.skin = skin; } } internal void Update() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (UnityInput.Current.GetKeyDown(ShowHotkey)) { Show = !Show; } if (Show) { for (int i = 0; i < _initializedFeatures.Count; i++) { _initializedFeatures[i].OnUpdate(); } } } internal void LateUpdate() { if (Show) { for (int i = 0; i < _initializedFeatures.Count; i++) { _initializedFeatures[i].OnLateUpdate(); } } } } public enum ScreenPartition { Default = 0, Full = 5, Center = 10, CenterUpper = 11, CenterLower = 12, Left = 20, LeftUpper = 21, LeftLower = 22, Right = 30, RightUpper = 31, RightLower = 32 } internal static class IL2CppAbstractions { public static void Set(this RectOffset obj, int left, int right, int top, int bottom) { obj.left = left; obj.right = right; obj.top = top; obj.bottom = bottom; } public static Transform[] AbstractGetChildren(this Transform transform, bool castedIl2Cpp = true) { Transform[] array = (Transform[])(object)new Transform[transform.childCount]; for (int i = 0; i < transform.childCount; i++) { Transform child = transform.GetChild(i); array[i] = child; } return array; } public static Component[] AbstractGetAllComponents(this GameObject gameObject, bool castedIl2Cpp = true) { return gameObject.GetComponents<Component>(); } public static Component[] AbstractGetAllComponents(this Component component, bool castedIl2Cpp = true) { return component.GetComponents<Component>(); } public static Component[] AbstractGetAllComponentsInChildren(this GameObject gameObject, bool includeInactive, bool castedIl2Cpp = true) { return gameObject.GetComponentsInChildren<Component>(includeInactive); } public static Component[] AbstractGetAllComponentsInChildren(this Component component, bool includeInactive, bool castedIl2Cpp = true) { return component.GetComponentsInChildren<Component>(includeInactive); } public static Coroutine AbstractStartCoroutine(this MonoBehaviour monoBehaviour, IEnumerator routine) { return monoBehaviour.StartCoroutine(routine); } public static T AbstractAddComponent<T>(this GameObject go) where T : Component { return go.AddComponent<T>(); } } public static class GUILayoutShim { public static GUILayoutOption MaxWidth(float width) { return GUILayout.MaxWidth(width); } public static GUILayoutOption ExpandWidth(bool expand) { return GUILayout.ExpandWidth(expand); } public static GUILayoutOption ExpandHeight(bool expand) { return GUILayout.ExpandHeight(expand); } public static GUILayoutOption MinWidth(float width) { return GUILayout.MinWidth(width); } } public static class GUILayoutUtilityShim { public static Rect GetLastRect() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return GUILayoutUtility.GetLastRect(); } } public static class GUILayoutGroupShim { } public interface IWindow : IFeature { string Title { get; set; } int WindowId { get; set; } Rect WindowRect { get; set; } Vector2 MinimumSize { get; set; } ScreenPartition DefaultScreenPosition { get; } } public abstract class Window<T> : FeatureBase<T>, IWindow, IFeature where T : Window<T> { [CompilerGenerated] private sealed class <<OnVisibleChanged>g__DelayedVisible|19_0>d : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public Window<T> <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <<OnVisibleChanged>g__DelayedVisible|19_0>d(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { int num = <>1__state; Window<T> window = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>2__current = null; <>1__state = 1; return true; case 1: <>1__state = -1; ((FeatureBase<T>)window).OnVisibleChanged(window.Visible); return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } protected const int DefaultTooltipWidth = 400; private static GUIStyle _tooltipStyle; private static GUIContent _tooltipContent; private static Texture2D _tooltipBackground; private bool _canShow; private Rect _initialWindowRect; private InitSettings.Setting<Rect> _windowRect; public int TooltipWidth { get; set; } = 400; public override string DisplayName { get { string text = _displayName; if (text == null) { string obj = Title ?? base.DisplayName; string text2 = obj; _displayName = obj; text = text2; } return text; } set { _displayName = value; } } public virtual string Title { get; set; } public int WindowId { get; set; } public virtual Rect WindowRect { get { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (_windowRect != null) { return _windowRect.Value; } return _initialWindowRect; } set { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (_windowRect != null) { _windowRect.Value = value; } else { _initialWindowRect = value; } } } public Vector2 MinimumSize { get; set; } = new Vector2(100f, 100f); public ScreenPartition DefaultScreenPosition { get; protected set; } protected Window() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) base.DisplayType = FeatureDisplayType.Window; SettingCategory = "Windows"; } protected override void AfterInitialized(InitSettings initSettings) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) base.AfterInitialized(initSettings); WindowId = base.GetHashCode(); _windowRect = initSettings.RegisterSetting<Rect>(SettingCategory, DisplayName + " window size", _initialWindowRect, string.Empty); } protected override void OnGUI() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown //IL_0030: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: 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_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: 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) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) if (_canShow) { string title = Title; WindowRect = GUILayout.Window(WindowId, WindowRect, new WindowFunction(DrawContentsInt), title, (GUILayoutOption[])(object)new GUILayoutOption[0]); Rect windowRect = WindowRect; if (((Rect)(ref windowRect)).width < MinimumSize.x) { Rect windowRect2 = WindowRect; ((Rect)(ref windowRect2)).width = MinimumSize.x; WindowRect = windowRect2; } windowRect = WindowRect; if (((Rect)(ref windowRect)).height < MinimumSize.y) { Rect windowRect3 = WindowRect; ((Rect)(ref windowRect3)).height = MinimumSize.y; WindowRect = windowRect3; } } } private void DrawContentsInt(int id) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: 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_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) int num = GUI.skin.window.border.top - 4; Rect windowRect = WindowRect; if (GUI.Button(new Rect(((Rect)(ref windowRect)).width - (float)num - 2f, 2f, (float)num, (float)num), "X")) { Enabled = false; return; } try { DrawContents(); DrawTooltip(WindowRect); } catch (Exception ex) { if (!ex.Message.Contains("GUILayout")) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Error, $"[{Title}] GUI crash: {ex}"); } } WindowRect = IMGUIUtils.DragResizeEat(id, WindowRect); } private void DrawTooltip(Rect area) { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_006b: 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) //IL_007e: Expected O, but got Unknown //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) if (!string.IsNullOrEmpty(GUI.tooltip)) { if ((Object)(object)_tooltipBackground == (Object)null) { _tooltipBackground = new Texture2D(1, 1, (TextureFormat)5, false); _tooltipBackground.SetPixel(0, 0, Color.black); _tooltipBackground.Apply(); _tooltipStyle = new GUIStyle { normal = new GUIStyleState { textColor = Color.white, background = _tooltipBackground }, wordWrap = true, alignment = (TextAnchor)4 }; _tooltipContent = new GUIContent(); } _tooltipContent.text = GUI.tooltip; float num = TooltipWidth; Rect windowRect = WindowRect; float num2 = Mathf.Min(num, ((Rect)(ref windowRect)).width); float num3 = _tooltipStyle.CalcHeight(_tooltipContent, num2) + 10f; Event current = Event.current; float num4 = ((current.mousePosition.x + num2 > ((Rect)(ref area)).width) ? (((Rect)(ref area)).width - num2) : current.mousePosition.x); float num5 = ((current.mousePosition.y + 25f + num3 > ((Rect)(ref area)).height) ? (current.mousePosition.y - num3) : (current.mousePosition.y + 25f)); GUI.Box(new Rect(num4, num5, num2, num3), GUI.tooltip, _tooltipStyle); } } protected override void OnVisibleChanged(bool visible) { if (visible && Taskbar.Instance.Height == 0) { RuntimeUnityEditorCore.PluginObject.AbstractStartCoroutine(DelayedVisible()); } else { base.OnVisibleChanged(visible); } IEnumerator DelayedVisible() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <<OnVisibleChanged>g__DelayedVisible|19_0>d(0) { <>4__this = this }; } } protected override void VisibleChanged(bool visible) { if (visible) { if (!WindowManager.IsWindowRectValid(this)) { ResetWindowRect(); } _canShow = true; } } public void ResetWindowRect() { WindowManager.ResetWindowRect(this); } protected abstract void DrawContents(); } public class WindowManager { private const int ScreenMargin = 10; private const int SideWidth = 350; internal static readonly List<IWindow> AdditionalWindows = new List<IWindow>(); public static Rect MakeDefaultWindowRect(Rect screenClientRect, ScreenPartition screenPartition) { //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) switch (screenPartition) { case ScreenPartition.Left: return EnsureVisible(new Rect(((Rect)(ref screenClientRect)).xMin, ((Rect)(ref screenClientRect)).yMin, 350f, ((Rect)(ref screenClientRect)).height)); case ScreenPartition.LeftUpper: return EnsureVisible(new Rect(((Rect)(ref screenClientRect)).xMin, ((Rect)(ref screenClientRect)).yMin, 350f, ((Rect)(ref screenClientRect)).height / 2f - 10f)); case ScreenPartition.LeftLower: return EnsureVisible(new Rect(((Rect)(ref screenClientRect)).xMin, ((Rect)(ref screenClientRect)).yMin + ((Rect)(ref screenClientRect)).height / 2f, 350f, ((Rect)(ref screenClientRect)).height / 2f)); case ScreenPartition.Center: { int num7 = (int)Mathf.Min(850f, ((Rect)(ref screenClientRect)).width); int num8 = (int)(((Rect)(ref screenClientRect)).xMin + ((Rect)(ref screenClientRect)).width / 2f - (float)Mathf.RoundToInt((float)num7 / 2f)); return EnsureVisible(new Rect((float)num8, ((Rect)(ref screenClientRect)).yMin, (float)num7, ((Rect)(ref screenClientRect)).height)); } case ScreenPartition.CenterUpper: { int num4 = (int)Mathf.Min(850f, ((Rect)(ref screenClientRect)).width); int num5 = (int)(((Rect)(ref screenClientRect)).xMin + ((Rect)(ref screenClientRect)).width / 2f - (float)Mathf.RoundToInt((float)num4 / 2f)); int num6 = (int)(((Rect)(ref screenClientRect)).height / 4f) * 3; return EnsureVisible(new Rect((float)num5, ((Rect)(ref screenClientRect)).yMin, (float)num4, (float)num6)); } case ScreenPartition.CenterLower: { int num = (int)Mathf.Min(850f, ((Rect)(ref screenClientRect)).width); int num2 = (int)(((Rect)(ref screenClientRect)).xMin + ((Rect)(ref screenClientRect)).width / 2f - (float)Mathf.RoundToInt((float)num / 2f)); int num3 = (int)(((Rect)(ref screenClientRect)).height / 4f) * 3; return EnsureVisible(new Rect((float)num2, ((Rect)(ref screenClientRect)).yMin + (float)num3 + 10f, (float)num, ((Rect)(ref screenClientRect)).height - (float)num3 - 10f)); } case ScreenPartition.Right: return EnsureVisible(new Rect(((Rect)(ref screenClientRect)).xMax - 350f, ((Rect)(ref screenClientRect)).yMin, 350f, ((Rect)(ref screenClientRect)).height)); case ScreenPartition.RightUpper: return EnsureVisible(new Rect(((Rect)(ref screenClientRect)).xMax - 350f, ((Rect)(ref screenClientRect)).yMin, 350f, ((Rect)(ref screenClientRect)).height / 2f)); case ScreenPartition.RightLower: return EnsureVisible(new Rect(((Rect)(ref screenClientRect)).xMax - 350f, ((Rect)(ref screenClientRect)).yMin + ((Rect)(ref screenClientRect)).height / 2f, 350f, ((Rect)(ref screenClientRect)).height / 2f)); case ScreenPartition.Full: return screenClientRect; case ScreenPartition.Default: if (!FeatureBase<ReplWindow>.Initialized) { goto case ScreenPartition.Center; } goto case ScreenPartition.CenterUpper; default: throw new ArgumentOutOfRangeException("screenPartition", screenPartition, null); } } private static Rect EnsureVisible(Rect rect) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) Rect result = rect; IEnumerable<IWindow> source = RuntimeUnityEditorCore.Instance.InitializedFeatures.OfType<IWindow>().Concat(AdditionalWindows); List<Rect> source2 = source.Select((IWindow w) => w.WindowRect).ToList(); while (source2.Any((Rect r) => Mathf.Abs(((Rect)(ref r)).x - ((Rect)(ref result)).x) < 7f && Mathf.Abs(((Rect)(ref r)).y - ((Rect)(ref result)).y) < 7f)) { ref Rect reference = ref result; ((Rect)(ref reference)).x = ((Rect)(ref reference)).x + 17f; ref Rect reference2 = ref result; ((Rect)(ref reference2)).y = ((Rect)(ref reference2)).y + 17f; } if (!(((Rect)(ref result)).x < (float)(Screen.width - 50)) || !(((Rect)(ref result)).y < (float)(Screen.height - 50))) { return rect; } return result; } public static void ResetWindowRect(IWindow window) { //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) Rect screenClientRect = default(Rect); ((Rect)(ref screenClientRect))..ctor(10f, 10f, (float)(Screen.width - 20), (float)(Screen.height - 20 - Taskbar.Instance.Height)); window.WindowRect = MakeDefaultWindowRect(screenClientRect, window.DefaultScreenPosition); } public static bool IsWindowRectValid(IWindow window) { //IL_0001: 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_000f: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: 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_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: 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_00a7: Unknown result type (might be due to invalid IL or missing references) Rect windowRect = window.WindowRect; if (((Rect)(ref windowRect)).width >= window.MinimumSize.x) { windowRect = window.WindowRect; if (((Rect)(ref windowRect)).height >= window.MinimumSize.y) { windowRect = window.WindowRect; if (((Rect)(ref windowRect)).x < (float)(Screen.width - 10)) { windowRect = window.WindowRect; if (((Rect)(ref windowRect)).y < (float)(Screen.height - 10)) { windowRect = window.WindowRect; float x = ((Rect)(ref windowRect)).x; windowRect = window.WindowRect; if (x >= 0f - ((Rect)(ref windowRect)).width + 10f) { windowRect = window.WindowRect; float y = ((Rect)(ref windowRect)).y; windowRect = window.WindowRect; return y >= 0f - ((Rect)(ref windowRect)).height + 10f; } } } } } return false; } } public class Taskbar : IFeature { private int _windowId; private Rect _windowRect; private readonly GUILayoutOption[] _taskbarLayoutOptions = (GUILayoutOption[])(object)new GUILayoutOption[3] { GUILayoutShim.MaxWidth(Screen.width), GUILayoutShim.ExpandHeight(expand: false), GUILayoutShim.ExpandWidth(expand: false) }; private readonly GUILayoutOption[] _timescaleTextfieldOptions = (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(38f) }; private List<IFeature> _orderedFeatures; private string _title; private string _titleFull; private bool _enabled; public static Taskbar Instance { get; private set; } public int Height => (int)((Rect)(ref _windowRect)).height; public bool Enabled { get { return _enabled; } set { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (value) { _taskbarLayoutOptions[0] = GUILayoutShim.MaxWidth(Screen.width); _titleFull = (((int)RuntimeUnityEditorCore.Instance.ShowHotkey == 0) ? _title : $"{_title} / Press {RuntimeUnityEditorCore.Instance.ShowHotkey} to show/hide"); } _enabled = value; } } FeatureDisplayType IFeature.DisplayType => FeatureDisplayType.Hidden; string IFeature.DisplayName => "WindowManager"; public Taskbar() { Instance = this; } void IFeature.OnInitialize(InitSettings initSettings) { _windowId = GetHashCode(); _title = "RuntimeUnityEditor v6.3"; } public void SetFeatures(List<IFeature> initializedFeatures) { _orderedFeatures = (from x in initializedFeatures orderby x.DisplayType descending, x.DisplayName select x).ToList(); } void IFeature.OnOnGUI() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_0025: 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_0030: Unknown result type (might be due to invalid IL or missing references) _windowRect = GUILayout.Window(_windowId, _windowRect, new WindowFunction(DrawTaskbar), _titleFull, _taskbarLayoutOptions); IMGUIUtils.EatInputInRect(_windowRect); ((Rect)(ref _windowRect)).x = (int)(((float)Screen.width - ((Rect)(ref _windowRect)).width) / 2f); ((Rect)(ref _windowRect)).y = (int)((float)Screen.height - ((Rect)(ref _windowRect)).height); } private void DrawTaskbar(int id) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal(IMGUIUtils.EmptyLayoutOptions); bool flag = true; for (int i = 0; i < _orderedFeatures.Count; i++) { IFeature feature = _orderedFeatures[i]; if (feature.DisplayType == FeatureDisplayType.Window) { GUI.color = (feature.Enabled ? Color.cyan : Color.white); if (GUILayout.Button(feature.DisplayName, IMGUIUtils.EmptyLayoutOptions)) { feature.Enabled = !feature.Enabled; } } else { if (feature.DisplayType != FeatureDisplayType.Feature) { continue; } if (flag) { GUI.color = new Color(1f, 1f, 1f, 0.75f); if (GUILayout.Button("Reset", IMGUIUtils.EmptyLayoutOptions)) { foreach (IWindow item in _orderedFeatures.OfType<IWindow>()) { item.WindowRect = new Rect(-1000f, -1000f, 0f, 0f); } foreach (IWindow item2 in from x in _orderedFeatures.OfType<IWindow>() orderby x.Enabled descending, x.Title select x) { GUI.BringWindowToFront(item2.WindowId); WindowManager.ResetWindowRect(item2); } } flag = false; GUI.color = Color.white; GUILayout.Label("|", IMGUIUtils.EmptyLayoutOptions); } feature.Enabled = GUILayout.Toggle(feature.Enabled, feature.DisplayName, IMGUIUtils.EmptyLayoutOptions); } } GUILayout.Label("|", IMGUIUtils.EmptyLayoutOptions); GUILayout.Label("Time", IMGUIUtils.LayoutOptionsExpandWidthFalse); if (GUILayout.Button(">", IMGUIUtils.LayoutOptionsExpandWidthFalse)) { Time.timeScale = 1f; } if (GUILayout.Button("||", IMGUIUtils.LayoutOptionsExpandWidthFalse)) { Time.timeScale = 0f; } if (float.TryParse(GUILayout.TextField(Time.timeScale.ToString("F2", CultureInfo.InvariantCulture), _timescaleTextfieldOptions), NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) { Time.timeScale = result; } GUI.changed = false; bool runInBackground = GUILayout.Toggle(Application.runInBackground, "in BG", IMGUIUtils.EmptyLayoutOptions); if (GUI.changed) { Application.runInBackground = runInBackground; } GUILayout.Label("|", IMGUIUtils.EmptyLayoutOptions); if (GUILayout.Button("Log", IMGUIUtils.LayoutOptionsExpandWidthFalse)) { UnityFeatureHelper.OpenLog(); } AssetBundleManagerHelper.DrawButtonIfAvailable(); GUILayout.EndHorizontal(); } void IFeature.OnUpdate() { } void IFeature.OnLateUpdate() { } void IFeature.OnEditorShownChanged(bool visible) { } } internal static class Constants { public const string Version = "6.3"; public const string Name = "RuntimeUnityEditor"; public const string Description = "In-game inspector and debugging tools for applications made with Unity3D game engine"; public const string Website = "https://github.com/ManlyMarco/RuntimeUnityEditor"; public const string Copyright = "Copyright GPL-3 © 2018"; } } namespace RuntimeUnityEditor.Core.REPL { public class REPL : InteractiveBase { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)] private class DocumentationAttribute : Attribute { public string Docs { get; } public DocumentationAttribute(string doc) { Docs = doc; } } public static string clear { get { FeatureBase<ReplWindow>.Instance.Clear(); return "Log cleared"; } } public static string help { get { string arg = InteractiveBase.help; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(" clear; - Clear this log\n"); stringBuilder.AppendLine(); stringBuilder.AppendLine("In addition, the following helper methods are provided:"); MethodInfo[] methods = typeof(REPL).GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(DocumentationAttribute), inherit: false); if (customAttributes.Length != 0) { stringBuilder.Append(" "); stringBuilder.AppendLine(((DocumentationAttribute)customAttributes[0]).Docs); } } return $"{arg}{stringBuilder}"; } } public static object InteropTempVar { get; set; } [Documentation("MB - A dummy MonoBehaviour for accessing Unity.")] public static ReplHelper MB { get; } static REPL() { MB = ((Component)RuntimeUnityEditorCore.PluginObject).gameObject.AbstractAddComponent<ReplHelper>(); } [Documentation("find<T>() - find a UnityEngine.Object of type T.")] public static T find<T>() where T : Object { return MB.Find<T>(); } [Documentation("findAll<T>() - find all UnityEngine.Object of type T.")] public static T[] findAll<T>() where T : Object { return MB.FindAll<T>(); } [Documentation("runCoroutine(enumerator) - runs an IEnumerator as a Unity coroutine.")] public static Coroutine runCoroutine(IEnumerator i) { return MB.RunCoroutine(i); } [Documentation("endCoroutine(co) - ends a Unity coroutine.")] public static void endCoroutine(Coroutine c) { MB.EndCoroutine(c); } [Documentation("type<T>() - obtain type info about a type T. Provides some Reflection helpers.")] public static TypeHelper type<T>() { return new TypeHelper(typeof(T)); } [Documentation("type(obj) - obtain type info about object obj. Provides some Reflection helpers.")] public static TypeHelper type(object instance) { return new TypeHelper(instance); } [Documentation("dir(obj) - lists all available methods and fiels of a given obj.")] public static string dir(object instance) { return type(instance).info(); } [Documentation("dir<T>() - lists all available methods and fields of type T.")] public static string dir<T>() { return type<T>().info(); } [Documentation("findrefs(obj) - find references to the object in currently loaded components.")] public static Component[] findrefs(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } List<Component> list = new List<Component>(); Component[] array = Object.FindObjectsOfType<Component>(); foreach (Component val in array) { Type type = ((object)val).GetType(); string[] nameBlacklist = new string[5] { "parent", "parentInternal", "root", "transform", "gameObject" }; Type[] typeBlacklist = new Type[1] { typeof(bool) }; foreach (PropertyInfo item in from x in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where x.CanRead && !nameBlacklist.Contains(x.Name) && !typeBlacklist.Contains(x.PropertyType) select x) { try { if (object.Equals(item.GetValue(val, null), obj)) { list.Add(val); goto IL_0179; } } catch { } } foreach (FieldInfo item2 in from x in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where !nameBlacklist.Contains(x.Name) && !typeBlacklist.Contains(x.FieldType) select x) { try { if (object.Equals(item2.GetValue(val), obj)) { list.Add(val); break; } } catch { } } IL_0179:; } return list.ToArray(); } [Documentation("geti() - get object currently opened in inspector. Will get expanded upon accepting. Best to use like this: var x = geti()")] public static object geti() { return FeatureBase<RuntimeUnityEditor.Core.Inspector.Inspector>.Instance.GetInspectedObject() ?? throw new InvalidOperationException("No object is opened in inspector or a static type is opened"); } public static T geti<T>() { return (T)geti(); } [Documentation("seti(obj) - send the object to the inspector. To send a static class use the setis(type) command.")] public static void seti(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } FeatureBase<RuntimeUnityEditor.Core.Inspector.Inspector>.Instance.Push(new InstanceStackEntry(obj, "REPL > " + obj.GetType().Name), newTab: true); } [Documentation("setis(type) - send the static class to the inspector.")] public static void setis(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } FeatureBase<RuntimeUnityEditor.Core.Inspector.Inspector>.Instance.Push(new StaticStackEntry(type, "REPL > " + type.Name), newTab: true); } [Documentation("getTree() - get the transform currently selected in tree view.")] public static Transform getTree() { return FeatureBase<ObjectTreeViewer>.Instance.SelectedTransform; } [Documentation("findTree(Transform) - find and select the transform in the tree view.")] public static void findTree(Transform tr) { if ((Object)(object)tr == (Object)null) { throw new ArgumentNullException("tr"); } FeatureBase<ObjectTreeViewer>.Instance.SelectAndShowObject(tr); } [Documentation("findTree(GameObject) - find and select the object in the tree view.")] public static void findTree(GameObject go) { if ((Object)(object)go == (Object)null) { throw new ArgumentNullException("go"); } FeatureBase<ObjectTreeViewer>.Instance.SelectAndShowObject(go.transform); } [Documentation("dnspy(type) - open the type in dnSpy if dnSpy path is configured.")] public static void dnspy(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } DnSpyHelper.OpenInDnSpy(type); } [Documentation("dnspy(memberInfo) - open the type member in dnSpy if dnSpy is configured.")] public static void dnspy(MemberInfo member) { if ((object)member == null) { throw new ArgumentNullException("member"); } DnSpyHelper.OpenInDnSpy(member); } [Documentation("echo(string) - write a string to REPL output.")] public static void echo(string message) { FeatureBase<ReplWindow>.Instance.AppendLogLine(message); } [Documentation("message(string) - write a string to log.")] public static void message(string message) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Message, message); } [Documentation("paste(index) - paste clipboard contents from a given int index.")] public static object paste(int index) { return ClipboardWindow.Contents[index]; } [Documentation("copy(object) - copy given object to clipboard (classes are copied by reference, returns the index it was added under).")] public static int copy(object @object) { ClipboardWindow.Contents.Add(@object); return ClipboardWindow.Contents.Count - 1; } [Documentation("dump(object, fileName) - dump given object to a new text file at specitied path.")] public static void dump(object @object, string fileName) { @object.DumpToFile("REPL_OBJECT", fileName); } [Documentation("dump(object) - dump given object to a temporary text file and open it in notepad. Returns path to the temp file.")] public static string dump(object @object) { return Dumper.DumpToTempFile(@object, "REPL_OBJECT"); } [Documentation("registerToString<TObj>(Func<TObj, string>) - add a ToString converter for a Type to change how it's displayed in Inspector and some other places.")] public static void registerToString<TObj>(Func<TObj, string> objectToString) { ToStringConverter.AddConverter(objectToString); } } public class ReplHelper : MonoBehaviour { public T Find<T>() where T : Object { return Object.FindObjectOfType<T>(); } public T[] FindAll<T>() where T : Object { return Object.FindObjectsOfType<T>(); } public Coroutine RunCoroutine(IEnumerator i) { return ((MonoBehaviour)(object)this).AbstractStartCoroutine(i); } public void EndCoroutine(Coroutine c) { ((MonoBehaviour)this).StopCoroutine(c); } } public sealed class ReplWindow : Window<ReplWindow> { private class VoidType { public static readonly VoidType Value = new VoidType(); private VoidType() { } } [CompilerGenerated] private sealed class <DelayedReplSetup>d__24 : IEnumerator<object>, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; public ReplWindow <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <DelayedReplSetup>d__24(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { int num = <>1__state; ReplWindow replWindow = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>2__current = null; <>1__state = 1; return true; case 1: <>1__state = -1; try { replWindow.RunEnvSetup(); } catch (Exception ex) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Warning, "Failed to initialize REPL environment - " + ex.Message); try { RuntimeUnityEditorCore.Instance.RemoveFeature(replWindow); replWindow._evaluator.Dispose(); } catch (Exception content) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Debug, content); } } return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private string _autostartFilename; private static readonly char[] _inputSplitChars = new char[11] { ',', ';', '<', '>', '(', ')', '[', ']', '=', '|', '&' }; private const int HistoryLimit = 50; private ScriptEvaluator _evaluator; private readonly List<string> _history = new List<string>(); private int _historyPosition; private readonly StringBuilder _sb = new StringBuilder(); private string _inputField = ""; private string _prevInput = ""; private Vector2 _scrollPosition = Vector2.zero; private TextEditor _textEditor; private int _newCursorLocation = -1; private MemberInfo _cursorIndex; private MemberInfo _selectIndex; private HashSet<string> _namespaces; private readonly List<Suggestion> _suggestions = new List<Suggestion>(); private const string SnippletSeparator = "/****************************************/"; private string _snippletFilename; private readonly List<string> _savedSnipplets = new List<string>(); private bool _snippletsShown; private GUIStyle _completionsListingStyle; private bool _refocus; private int _refocusCursorIndex = -1; private int _refocusSelectIndex; private HashSet<string> Namespaces { get { if (_namespaces == null) { _namespaces = new HashSet<string>(from x in AppDomain.CurrentDomain.GetAssemblies().SelectMany(Extensions.GetTypesSafe) where !string.IsNullOrEmpty(x.Namespace) select x.Namespace); RuntimeUnityEditorCore.Logger.Log(LogLevel.Debug, $"[REPL] Found {_namespaces.Count} public namespaces"); } return _namespaces; } } protected override void Initialize(InitSettings initSettings) { //IL_00d1: Unknown result type (might be due to invalid IL or missing references) if (!UnityFeatureHelper.SupportsRepl) { throw new InvalidOperationException("mcs is not supported on this Unity version"); } InitSettings.Setting<bool> setting = initSettings.RegisterSetting("General", "Disable REPL function", defaultValue: false, "Completely turn off REPL even if it's supported. Useful if mcs is causing compatibility issues (e.g. in rare cases it can crash the game when used together with some versions of RuntimeDetours in some Unity versions)."); if (setting.Value) { throw new InvalidOperationException("REPL is disabled in config"); } string configPath = initSettings.ConfigPath; _autostartFilename = Path.Combine(configPath, "RuntimeUnityEditor.Autostart.cs"); _snippletFilename = Path.Combine(configPath, "RuntimeUnityEditor.Snipplets.cs"); Title = "C# REPL Console"; _sb.AppendLine("Welcome to C# REPL (read-evaluate-print loop)! Enter \"help\" to get a list of common methods."); ScriptEvaluator scriptEvaluator = new ScriptEvaluator(new StringWriter(_sb)); ((Evaluator)scriptEvaluator).InteractiveBaseClass = typeof(REPL); _evaluator = scriptEvaluator; initSettings.PluginMonoBehaviour.AbstractStartCoroutine(DelayedReplSetup()); DisplayName = "REPL console"; base.MinimumSize = new Vector2(280f, 130f); Enabled = false; base.DefaultScreenPosition = ScreenPartition.CenterLower; ContextMenu.MenuContents.Add(new ContextMenuEntry("Send to REPL", (object o, MemberInfo _) => o != null, delegate(object o, MemberInfo info, string name) { FeatureBase<ReplWindow>.Instance.IngestObject(o); })); } protected override void VisibleChanged(bool visible) { base.VisibleChanged(visible); _namespaces = null; } private IEnumerator DelayedReplSetup() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <DelayedReplSetup>d__24(0) { <>4__this = this }; } public void RunEnvSetup() { string str = "using System;using UnityEngine;using System.Linq;using System.Collections;using System.Collections.Generic;"; Evaluate(str); RunAutostart(_autostartFilename); } private void RunAutostart(string autostartFilename) { if (!File.Exists(autostartFilename)) { return; } string[] array = (from x in File.ReadAllLines(autostartFilename) select x.Trim('\t', ' ', '\r', '\n') into x where !string.IsNullOrEmpty(x) && !x.StartsWith("//") select x).ToArray(); if (array.Length != 0) { string text = "Executing code from " + autostartFilename; RuntimeUnityEditorCore.Logger.Log(LogLevel.Info, text); AppendLogLine(text); string[] array2 = array; foreach (string str in array2) { Evaluate(str); } } } protected override void DrawContents() { //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_030d: Invalid comparison between Unknown and I4 //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) if (_completionsListingStyle == null) { _completionsListingStyle = GUI.skin.button.CreateCopy(); _completionsListingStyle.border = new RectOffset(); _completionsListingStyle.margin = new RectOffset(); _completionsListingStyle.padding = new RectOffset(); _completionsListingStyle.hover.background = Texture2D.whiteTexture; _completionsListingStyle.hover.textColor = Color.black; _completionsListingStyle.normal.background = null; _completionsListingStyle.focused.background = Texture2D.whiteTexture; _completionsListingStyle.focused.textColor = Color.black; _completionsListingStyle.active.background = Texture2D.whiteTexture; _completionsListingStyle.active.textColor = Color.black; } GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); _scrollPosition = GUILayout.BeginScrollView(_scrollPosition, false, true, GUIStyle.none, GUI.skin.verticalScrollbar, GUI.skin.textArea, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.FlexibleSpace(); if (_snippletsShown) { if (_savedSnipplets.Count == 0) { GUILayout.Label("This is a list of saved snipplets of code that you can load later into the input field.\n\nTo save a snipplet, type someting in the input field and click the Save button.\nTo load a snipplet, make sure the input field is empty, click the Load button, then choose a snipplet.\nTo remove a snipplet you can edit the snipplet file by choosing the bottom option on the snipplet list.\n\nClose this menu without loading anything by clicking the Cancel button below.", GUI.skin.box, (GUILayoutOption[])(object)new GUILayoutOption[0]); } else { _completionsListingStyle.normal.textColor = Color.white; foreach (string savedSnipplet in _savedSnipplets) { if (GUILayout.Button(savedSnipplet, GUI.skin.box, IMGUIUtils.LayoutOptionsExpandWidthTrue)) { _inputField = savedSnipplet; _snippletsShown = false; break; } } if (GUILayout.Button(">> Edit snipplet list in external editor <<", GUI.skin.box, IMGUIUtils.LayoutOptionsExpandWidthTrue)) { AppendLogLine("Opening snipplet file at " + _snippletFilename); if (!File.Exists(_snippletFilename)) { File.WriteAllText(_snippletFilename, ""); } try { Process.Start(_snippletFilename); } catch (Exception ex) { AppendLogLine(ex.Message); } } } } else if (_suggestions.Count > 0) { foreach (Suggestion suggestion in _suggestions) { _completionsListingStyle.normal.textColor = suggestion.GetTextColor(); if (GUILayout.Button(suggestion.Result, _completionsListingStyle, IMGUIUtils.LayoutOptionsExpandWidthTrue)) { AcceptSuggestion(suggestion); break; } } } else { GUILayout.TextArea(_sb.ToString(), GUI.skin.label, (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUILayout.EndScrollView(); GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); GUI.SetNextControlName("replInput"); _inputField = GUILayout.TextArea(_inputField, (GUILayoutOption[])(object)new GUILayoutOption[0]); if ((int)Event.current.type == 7) { if (_refocus) { if (_refocusCursorIndex < 0) { _refocusCursorIndex = (int)ReflectionUtils.GetValue(_cursorIndex, _textEditor); _refocusSelectIndex = (int)ReflectionUtils.GetValue(_selectIndex, _textEditor); } GUI.FocusControl("replInput"); _refocus = false; } else if (_refocusCursorIndex >= 0) { ReflectionUtils.SetValue(_cursorIndex, _textEditor, _refocusCursorIndex); ReflectionUtils.SetValue(_selectIndex, _textEditor, _refocusSelectIndex); _refocusCursorIndex = -1; } } if (GUILayout.Button("Run", IMGUIUtils.LayoutOptionsExpandWidthFalse)) { AcceptInput(); } if (GUILayout.Button(_snippletsShown ? "Cancel" : ((_inputField.Length == 0) ? "Load" : "Save"), IMGUIUtils.LayoutOptionsExpandWidthFalse)) { if (_snippletsShown) { _snippletsShown = false; } else if (_inputField.Length == 0) { _snippletsShown = true; IEnumerable<string> enumerable2; if (!File.Exists(_snippletFilename)) { IEnumerable<string> enumerable = new string[0]; enumerable2 = enumerable; } else { enumerable2 = from x in File.ReadAllText(_snippletFilename).Split(new string[1] { "/****************************************/" }, StringSplitOptions.RemoveEmptyEntries) select x.Replace("\t", " ").Trim(' ', '\r', '\n') into x where x.Length > 0 select x; } IEnumerable<string> collection = enumerable2; _savedSnipplets.Clear(); _savedSnipplets.AddRange(collection); } else { string contents = (File.Exists(_snippletFilename) ? (_inputField + Environment.NewLine + "/****************************************/" + Environment.NewLine + File.ReadAllText(_snippletFilename)) : _inputField); File.WriteAllText(_snippletFilename, contents); AppendLogLine("Saved current command to snipplets. Clear the input box and click Load to load it."); } } if (GUILayout.Button("Autostart", IMGUIUtils.LayoutOptionsExpandWidthFalse)) { AppendLogLine("Opening autostart file at " + _autostartFilename); if (!File.Exists(_autostartFilename)) { File.WriteAllText(_autostartFilename, "// This C# code will be executed by the REPL near the end of plugin initialization. Only single-line statements are supported. Use echo(string) to write to REPL log and message(string) to write to global log.\n\n"); } try { Process.Start(_autostartFilename); } catch (Exception ex2) { AppendLogLine(ex2.Message); } ScrollToBottom(); } if (GUILayout.Button("History", IMGUIUtils.LayoutOptionsExpandWidthFalse)) { AppendLogLine(""); AppendLogLine("# History of executed commands:"); foreach (string item in _history) { AppendLogLine(item); } ScrollToBottom(); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); CheckReplInput(); } private void AcceptSuggestion(Suggestion suggestion) { int num = (int)ReflectionUtils.GetValue(_cursorIndex, _textEditor); if (num - suggestion.Original.Length >= 0) { num -= suggestion.Original.Length; _inputField = _inputField.Remove(num, suggestion.Original.Length); } _inputField = _inputField.Insert(num, suggestion.Result); _newCursorLocation = num + suggestion.Result.Length; ClearSuggestions(); _refocus = true; _refocusCursorIndex = _newCursorLocation; _refocusSelectIndex = _newCursorLocation; } public object Evaluate(string str) { object value = VoidType.Value; CompiledMethod val = default(CompiledMethod); ((Evaluator)_evaluator).Compile(str, ref val); try { if (val != null) { val.Invoke(ref value); } } catch (Exception ex) { AppendLogLine(ex.ToString()); } return value; } private void FetchHistory(int move) { if (_history.Count != 0) { _historyPosition += move; _historyPosition %= _history.Count; if (_historyPosition < 0) { _historyPosition = _history.Count - 1; } _inputField = _history[_historyPosition]; } } private void FetchSuggestions(string input) { try { _suggestions.Clear(); if (input.IndexOfAny(new char[5] { '?', '{', '}', '[', ']' }) < 0) { int length = _sb.Length; string prefix = default(string); string[] completions = ((Evaluator)_evaluator).GetCompletions(input, ref prefix); _sb.Length = length; if (completions != null) { if (prefix == null) { prefix = input; } _suggestions.AddRange(from x in completions where !string.IsNullOrEmpty(x) select new Suggestion(x, prefix, Namespaces.Contains(x) ? SuggestionKind.Namespace : SuggestionKind.Unknown)); } } _refocus = true; } catch (Exception ex) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Debug, "[REPL] " + ex); ClearSuggestions(); } } private void CheckReplInput() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Invalid comparison between Unknown and I4 //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Invalid comparison between Unknown and I4 //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Invalid comparison between Unknown and I4 //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Invalid comparison between Unknown and I4 if (GUI.GetNameOfFocusedControl() != "replInput") { return; } _textEditor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl); Type typeFromHandle = typeof(TextEditor); _cursorIndex = typeFromHandle.GetProperty("cursorIndex", BindingFlags.Instance | BindingFlags.Public); _selectIndex = typeFromHandle.GetProperty("selectIndex", BindingFlags.Instance | BindingFlags.Public); if ((object)_cursorIndex == null && (object)_selectIndex == null) { _cursorIndex = typeFromHandle.GetField("pos", BindingFlags.Instance | BindingFlags.Public); _selectIndex = typeFromHandle.GetField("selectPos", BindingFlags.Instance | BindingFlags.Public); } if (_newCursorLocation >= 0) { ReflectionUtils.SetValue(_cursorIndex, _textEditor, _newCursorLocation); ReflectionUtils.SetValue(_selectIndex, _textEditor, _newCursorLocation); _newCursorLocation = -1; } string text = _inputField; Event current = Event.current; if (current.isKey) { if ((int)current.keyCode == 13 || (int)current.keyCode == 271) { if (!current.shift) { int num = (int)ReflectionUtils.GetValue(_cursorIndex, _textEditor); if (num - 1 >= 0) { _inputField = _inputField.Remove(num - 1, 1); } AcceptInput(); current.Use(); } } else if (text == null || !Enumerable.Contains(text, '\n')) { if ((int)current.keyCode == 273) { FetchHistory(-1); current.Use(); ClearSuggestions(); } else if ((int)current.keyCode == 274) { FetchHistory(1); current.Use(); ClearSuggestions(); } } } if (!string.IsNullOrEmpty(text)) { try { int num2 = ((_refocusCursorIndex >= 0) ? _refocusCursorIndex : ((int)ReflectionUtils.GetValue(_cursorIndex, _textEditor))); int num3 = ((num2 > 0) ? (text.LastIndexOfAny(_inputSplitChars, num2 - 1) + 1) : 0); int num4 = ((num2 <= 0) ? text.Length : text.IndexOfAny(_inputSplitChars, num2 - 1)); if (num4 < 0 || num4 < num3) { num4 = text.Length; } text = text.Substring(num3, num4 - num3); } catch (ArgumentException) { } if (text != _prevInput && !string.IsNullOrEmpty(text)) { FetchSuggestions(text); } } else { ClearSuggestions(); } _prevInput = text; } private void ClearSuggestions() { if (_suggestions.Any()) { _suggestions.Clear(); _refocus = true; } } private void AcceptInput() { _inputField = _inputField.Trim(); if (_inputField == "") { return; } _history.Add(_inputField); if (_history.Count > 50) { _history.RemoveRange(0, _history.Count - 50); } _historyPosition = 0; Change.Report("(REPL)::" + _inputField); if (_inputField.Contains("geti()")) { try { object obj = REPL.geti(); if (obj != null) { _inputField = _inputField.Replace("geti()", "geti<" + obj.GetType().GetSourceCodeRepresentation() + ">()"); } } catch (SystemException) { } } AppendLogLine("> " + _inputField); object obj2 = Evaluate(_inputField); if (obj2 != null && !object.Equals(obj2, VoidType.Value)) { AppendLogLine(obj2.ToString()); } ScrollToBottom(); _inputField = string.Empty; ClearSuggestions(); } private void ScrollToBottom() { _scrollPosition.y = float.MaxValue; } internal void AppendLogLine(string message) { _sb.AppendLine(message); } public void Clear() { _sb.Length = 0; } public void IngestObject(object obj) { if (obj == null) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Warning, "obj is null in: " + new StackTrace()); return; } REPL.InteropTempVar = obj; _prevInput = (_inputField = "var " + GetUniqueVarName() + " = (" + obj.GetType().GetSourceCodeRepresentation() + ")InteropTempVar"); ClearSuggestions(); } private string GetUniqueVarName() { string text = default(string); int num = ((Evaluator)_evaluator).GetCompletions("q", ref text).Max(delegate(string x) { Match match = Regex.Match(x, "^q(\\d*)$", RegexOptions.Singleline); if (match.Success) { string value = match.Groups[1].Value; if (!string.IsNullOrEmpty(value)) { return int.Parse(value); } return 0; } return -1; }); return "q" + ((num >= 0) ? (num + 1).ToString() : ""); } } internal struct Suggestion { public readonly string Original; public readonly string Result; public readonly SuggestionKind Kind; public Suggestion(string result, string original, SuggestionKind kind) { Original = original; Kind = kind; Result = result; } public Color GetTextC
UMM/Mods/Runtime Unity Editor/RuntimeUnityEditor.UMM.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml.Serialization; using RuntimeUnityEditor.Core; using RuntimeUnityEditor.Core.Utils; using RuntimeUnityEditor.Core.Utils.Abstractions; using UnityEngine; using UnityModManagerNet; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("https://github.com/ManlyMarco/RuntimeUnityEditor")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright GPL-3 © 2018")] [assembly: AssemblyFileVersion("6.3.0.0")] [assembly: AssemblyInformationalVersion("6.3+3bd95bfd1fb716fd440f3c30b4a05b364238d2fc")] [assembly: AssemblyProduct("RuntimeUnityEditor")] [assembly: AssemblyTitle("In-game inspector and debugging tools for applications made with Unity3D game engine")] [assembly: AssemblyVersion("6.3.0.0")] namespace RuntimeUnityEditor.UMM; [XmlInclude(typeof(XmlRect))] public class RuntimeUnityEditorSettings : ModSettings { public abstract class SettingBase { [XmlIgnore] public abstract object BoxedValue { get; set; } [XmlIgnore] public abstract Type type { get; } } public class Setting<T> : SettingBase { private T _value; [XmlIgnore] public Action<T> OnChanged; public T Value { get { return _value; } set { if (!object.Equals(_value, value)) { _value = value; OnChanged?.Invoke(value); } } } [XmlIgnore] public override object BoxedValue { get { return Value; } set { Value = (T)value; } } [XmlIgnore] public override Type type => typeof(T); internal Setting() { } public Setting(T value) { Value = value; } } public class SerializableCategory { [XmlAttribute] public string Name; [XmlElement("Setting")] public List<SerializableSetting> Settings; } public class SerializableSetting { [XmlAttribute("Name")] public string Key; [XmlElement(typeof(Setting<XmlRect>), ElementName = "Rect")] [XmlElement(typeof(Setting<KeyCode>), ElementName = "KeyCode")] [XmlElement(typeof(Setting<bool>), ElementName = "bool")] [XmlElement(typeof(Setting<int>), ElementName = "int")] [XmlElement(typeof(Setting<float>), ElementName = "float")] [XmlElement(typeof(Setting<string>), ElementName = "text")] public SettingBase Value; } public class XmlRect { public float x; public float y; public float width; public float height; public XmlRect() { } public XmlRect(Rect r) { x = ((Rect)(ref r)).x; y = (y = ((Rect)(ref r)).y); width = ((Rect)(ref r)).width; height = ((Rect)(ref r)).height; } private Rect ToRect() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) return new Rect(x, y, width, height); } } private readonly Dictionary<string, Dictionary<string, SettingBase>> Categories = new Dictionary<string, Dictionary<string, SettingBase>>(); [XmlElement("Category")] public List<SerializableCategory> SerializableSettings { get; set; } public void Add(string category, string settingName, SettingBase setting) { if (!Categories.ContainsKey(category)) { Categories.Add(category, new Dictionary<string, SettingBase>()); } Categories[category][settingName] = setting; } public bool Get<T>(string categoryName, string settingName, out Setting<T> setting) { if (Categories.TryGetValue(categoryName, out var value) && value.TryGetValue(settingName, out var value2)) { setting = (Setting<T>)value2; return true; } setting = null; return false; } public override void Save(ModEntry entry) { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) SerializableSettings = new List<SerializableCategory>(); string path = ((ModSettings)this).GetPath(RuntimeUnityEditorUMM.Instance); foreach (string key in Categories.Keys) { List<SerializableSetting> list = new List<SerializableSetting>(); foreach (string key2 in Categories[key].Keys) { if ((object)Categories[key][key2].GetType() == typeof(Setting<Rect>)) { list.Add(new SerializableSetting { Key = key2, Value = new Setting<XmlRect>(new XmlRect((Categories[key][key2] as Setting<Rect>).Value)) }); } else { list.Add(new SerializableSetting { Key = key2, Value = Categories[key][key2] }); } } SerializableSettings.Add(new SerializableCategory { Name = key, Settings = list }); } ModSettings.Save<RuntimeUnityEditorSettings>(this, entry); try { using StreamWriter textWriter = new StreamWriter(path); XmlSerializer xmlSerializer = new XmlSerializer(typeof(RuntimeUnityEditorSettings)); xmlSerializer.Serialize(textWriter, RuntimeUnityEditorUMM.Settings); } catch (Exception ex) { RuntimeUnityEditorUMM.Instance.Logger.Error("Error writing to Settings.xml"); RuntimeUnityEditorUMM.Instance.Logger.LogException(ex); } } public void Load(ModEntry entry) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) if (SerializableSettings == null) { return; } foreach (SerializableCategory serializableSetting in SerializableSettings) { foreach (SerializableSetting setting2 in serializableSetting.Settings) { if (setting2.Value is Setting<XmlRect> setting) { Add(serializableSetting.Name, setting2.Key, new Setting<Rect>(new Rect(setting.Value.x, setting.Value.y, setting.Value.width, setting.Value.height))); } else { Add(serializableSetting.Name, setting2.Key, setting2.Value); } } } } public void Draw(ModEntry entry) { //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Expected O, but got Unknown //IL_0186: Unknown result type (might be due to invalid IL or missing references) foreach (string key in Categories.Keys) { if (key == "Windows") { continue; } GUILayout.Label(key, UI.bold, (GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.BeginVertical(GUIStyle.op_Implicit("box"), (GUILayoutOption[])(object)new GUILayoutOption[0]); foreach (string key2 in Categories[key].Keys) { SettingBase settingBase = Categories[key][key2]; GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]); if (settingBase is Setting<int> setting) { int value = setting.Value; if (UI.DrawIntField(ref value, key2, (GUIStyle)null, (GUILayoutOption[])(object)new GUILayoutOption[0])) { setting.Value = value; } } else if (settingBase is Setting<float> setting2) { float value2 = setting2.Value; if (UI.DrawFloatField(ref value2, key2, (GUIStyle)null, (GUILayoutOption[])(object)new GUILayoutOption[0])) { setting2.Value = value2; } } else if (settingBase is Setting<bool> setting3) { bool flag = GUILayout.Toggle(setting3.Value, key2, (GUILayoutOption[])(object)new GUILayoutOption[0]); if (flag != setting3.Value) { setting3.Value = flag; } } else if (settingBase is Setting<KeyCode> setting4) { GUILayout.Label(key2, IMGUIUtils.LayoutOptionsExpandWidthFalse); KeyBinding val = new KeyBinding { keyCode = setting4.Value }; if (UI.DrawKeybinding(ref val, key2, (GUIStyle)null, (GUILayoutOption[])(object)new GUILayoutOption[0])) { setting4.Value = val.keyCode; } GUILayout.FlexibleSpace(); } else if (settingBase is Setting<string> setting5) { GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[0]); GUILayout.Label(key2, IMGUIUtils.LayoutOptionsExpandWidthFalse); string text = GUILayout.TextField(setting5.Value, IMGUIUtils.LayoutOptionsExpandWidthTrue); if (text != setting5.Value) { setting5.Value = text; } GUILayout.EndVertical(); } else { GUILayout.Label("Unknown config entry type: " + settingBase.type.ToString(), (GUILayoutOption[])(object)new GUILayoutOption[0]); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); } } } [Obsolete("It's recommended to reference RuntimeUnityEditorCore directly")] public static class RuntimeUnityEditorUMM { private class RuntimeUnityEditorBehaviour : MonoBehaviour { private void Start() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown _editorMonoBehaviour = (MonoBehaviour)(object)this; CoreInstance = new RuntimeUnityEditorCore((InitSettings)(object)new UMMInitSettings(Instance, Settings)); } private void Update() { CoreInstance.Update(); } private void LateUpdate() { CoreInstance.LateUpdate(); } private void OnGUI() { CoreInstance.OnGUI(); } } private sealed class UMMInitSettings : InitSettings { private readonly RuntimeUnityEditorSettings _settings; public override MonoBehaviour PluginMonoBehaviour => _editorMonoBehaviour; public override ILoggerWrapper LoggerWrapper { get; } public override string ConfigPath => Instance.Path; public UMMInitSettings(ModEntry instance, RuntimeUnityEditorSettings settings) { _settings = settings; LoggerWrapper = (ILoggerWrapper)(object)new LoggerUMM(instance.Logger); } protected override Action<T> RegisterSetting<T>(string category, string name, T defaultValue, string description, Action<T> onValueUpdated) { if (!_settings.Get(category, name, out RuntimeUnityEditorSettings.Setting<T> setting)) { setting = new RuntimeUnityEditorSettings.Setting<T>(defaultValue); _settings.Add(category, name, setting); } setting.OnChanged = onValueUpdated; onValueUpdated(setting.Value); return delegate(T newValue) { setting.Value = newValue; onValueUpdated(newValue); }; } } private sealed class LoggerUMM : ILoggerWrapper { private readonly ModLogger _logger; public LoggerUMM(ModLogger logger) { _logger = logger; } public void Log(LogLevel logLevel, object content) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Invalid comparison between Unknown and I4 //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected I4, but got Unknown //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Invalid comparison between Unknown and I4 //IL_00fb: 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_0032: Invalid comparison between Unknown and I4 if ((int)logLevel <= 16) { switch ((int)logLevel) { default: if ((int)logLevel == 16) { goto IL_00c7; } goto IL_00f0; case 0: case 1: break; case 2: goto IL_0075; case 4: goto IL_009e; case 8: goto IL_00c7; case 3: case 5: case 6: case 7: goto IL_00f0; } } else { if ((int)logLevel == 32) { goto IL_00c7; } if ((int)logLevel != 63) { goto IL_00f0; } } if (content is Exception ex) { _logger.LogException(ex); } else { _logger.Critical(content as string); } return; IL_0075: if (content is Exception ex2) { _logger.LogException(ex2); } else { _logger.Error(content as string); } return; IL_00c7: if (content is Exception ex3) { _logger.LogException(ex3); } else { _logger.Log(content as string); } return; IL_009e: if (content is Exception ex4) { _logger.LogException(ex4); } else { _logger.Warning(content as string); } return; IL_00f0: _logger.Warning($"Unknown LogLevel [{logLevel}] for content: {content}"); } } private static GameObject _editorGameObject; private static MonoBehaviour _editorMonoBehaviour; public static bool Enabled { get { MonoBehaviour editorMonoBehaviour = _editorMonoBehaviour; if (editorMonoBehaviour == null) { return false; } return ((Behaviour)editorMonoBehaviour).enabled; } private set { ((Behaviour)_editorMonoBehaviour).enabled = value; } } public static ModEntry Instance { get; private set; } public static RuntimeUnityEditorCore CoreInstance { get; private set; } public static RuntimeUnityEditorSettings Settings { get; private set; } public static bool Load(ModEntry modEntry) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown if (Instance != null) { Instance.Logger.Critical("Multiple copies of Runtime Unity Editor detected!"); return false; } Instance = modEntry; Settings = ModSettings.Load<RuntimeUnityEditorSettings>(Instance); Settings.Load(Instance); _editorGameObject = new GameObject("RuntimeUnityEditor", new Type[1] { typeof(RuntimeUnityEditorBehaviour) }); Object.DontDestroyOnLoad((Object)(object)_editorGameObject); Instance.OnGUI = OnGUI; Instance.OnSaveGUI = ((ModSettings)Settings).Save; return true; } private static void OnGUI(ModEntry modEntry) { Settings.Draw(modEntry); } } internal static class Constants { public const string Version = "6.3"; public const string Name = "RuntimeUnityEditor"; public const string Description = "In-game inspector and debugging tools for applications made with Unity3D game engine"; public const string Website = "https://github.com/ManlyMarco/RuntimeUnityEditor"; public const string Copyright = "Copyright GPL-3 © 2018"; }