using System; using System.Buffers.Binary; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Text.RegularExpressions; using System.Threading; using AsmResolver.Collections; using AsmResolver.DotNet.Builder; using AsmResolver.DotNet.Builder.Discovery; using AsmResolver.DotNet.Builder.Metadata; using AsmResolver.DotNet.Builder.Metadata.Blob; using AsmResolver.DotNet.Builder.Metadata.Guid; using AsmResolver.DotNet.Builder.Metadata.Strings; using AsmResolver.DotNet.Builder.Metadata.Tables; using AsmResolver.DotNet.Builder.Metadata.UserStrings; using AsmResolver.DotNet.Builder.Resources; using AsmResolver.DotNet.Builder.VTableFixups; using AsmResolver.DotNet.Code; using AsmResolver.DotNet.Code.Cil; using AsmResolver.DotNet.Code.Native; using AsmResolver.DotNet.Collections; using AsmResolver.DotNet.Config.Json; using AsmResolver.DotNet.Serialized; using AsmResolver.DotNet.Signatures; using AsmResolver.DotNet.Signatures.Marshal; using AsmResolver.DotNet.Signatures.Security; using AsmResolver.DotNet.Signatures.Types; using AsmResolver.DotNet.Signatures.Types.Parsing; using AsmResolver.IO; using AsmResolver.PE; using AsmResolver.PE.Builder; using AsmResolver.PE.Code; using AsmResolver.PE.Debug; using AsmResolver.PE.DotNet; using AsmResolver.PE.DotNet.Builder; using AsmResolver.PE.DotNet.Cil; using AsmResolver.PE.DotNet.Metadata; using AsmResolver.PE.DotNet.Metadata.Blob; using AsmResolver.PE.DotNet.Metadata.Guid; using AsmResolver.PE.DotNet.Metadata.Strings; using AsmResolver.PE.DotNet.Metadata.Tables; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; using AsmResolver.PE.DotNet.Metadata.UserStrings; using AsmResolver.PE.DotNet.Resources; using AsmResolver.PE.DotNet.StrongName; using AsmResolver.PE.DotNet.VTableFixups; using AsmResolver.PE.Exports; using AsmResolver.PE.File; using AsmResolver.PE.File.Headers; using AsmResolver.PE.Imports; using AsmResolver.PE.Platforms; using AsmResolver.PE.Relocations; using AsmResolver.PE.Win32Resources; using AsmResolver.PE.Win32Resources.Builder; using AsmResolver.Patching; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("AsmResolver.DotNet")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © Washi 2016-2022")] [assembly: AssemblyDescription("High level .NET image models for the AsmResolver executable file inspection toolsuite.")] [assembly: AssemblyFileVersion("5.1.0.0")] [assembly: AssemblyInformationalVersion("5.1.0")] [assembly: AssemblyProduct("AsmResolver.DotNet")] [assembly: AssemblyTitle("AsmResolver.DotNet")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Washi1337/AsmResolver")] [assembly: AssemblyVersion("5.1.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = P_0; } } } namespace AsmResolver.DotNet { public class AssemblyDefinition : AssemblyDescriptor, IModuleProvider, IHasSecurityDeclaration, IMetadataMember { private IList? _modules; private IList? _securityDeclarations; private readonly LazyVariable _publicKey; private byte[]? _publicKeyToken; public AssemblyHashAlgorithm HashAlgorithm { get; set; } [MemberNotNullWhen(true, "ManifestModule")] public bool HasManifestModule { [MemberNotNullWhen(true, "ManifestModule")] get { return ManifestModule != null; } } public ModuleDefinition? ManifestModule { get { if (Modules.Count <= 0) { return null; } return Modules[0]; } } ModuleDefinition? IModuleProvider.Module => ManifestModule; public IList Modules { get { if (_modules == null) { Interlocked.CompareExchange(ref _modules, GetModules(), null); } return _modules; } } public IList SecurityDeclarations { get { if (_securityDeclarations == null) { Interlocked.CompareExchange(ref _securityDeclarations, GetSecurityDeclarations(), null); } return _securityDeclarations; } } public byte[]? PublicKey { get { return _publicKey.Value; } set { _publicKey.Value = value; _publicKeyToken = null; } } public override bool IsCorLib { get { if (base.Name != null) { return KnownCorLibs.KnownCorLibNames.Contains(Utf8String.op_Implicit(base.Name)); } return false; } } public static AssemblyDefinition FromBytes(byte[] buffer) { return FromImage(PEImage.FromBytes(buffer)); } public static AssemblyDefinition FromFile(string filePath) { return FromImage(PEImage.FromFile(filePath), new ModuleReaderParameters(Path.GetDirectoryName(filePath))); } public static AssemblyDefinition FromFile(PEFile file) { return FromImage(PEImage.FromFile((IPEFile)(object)file)); } public static AssemblyDefinition FromFile(IInputFile file) { return FromImage(PEImage.FromFile(file)); } public static AssemblyDefinition FromReader(in BinaryStreamReader reader, PEMappingMode mode = 0) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return FromImage(PEImage.FromReader(ref reader, mode)); } public static AssemblyDefinition FromImage(IPEImage peImage) { return FromImage(peImage, new ModuleReaderParameters(Path.GetDirectoryName(peImage.FilePath))); } public static AssemblyDefinition FromImage(IPEImage peImage, ModuleReaderParameters readerParameters) { return ModuleDefinition.FromImage(peImage, readerParameters).Assembly ?? throw new BadImageFormatException("The provided PE image does not contain an assembly manifest."); } protected AssemblyDefinition(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _publicKey = new LazyVariable((Func)GetPublicKey); } public AssemblyDefinition(Utf8String? name, Version version) : this(new MetadataToken((TableIndex)32, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) base.Name = name; base.Version = version; } protected virtual IList GetModules() { return (IList)new OwnedCollection(this); } protected virtual IList GetSecurityDeclarations() { return (IList)new OwnedCollection((IHasSecurityDeclaration)this); } protected virtual byte[]? GetPublicKey() { return null; } public override byte[]? GetPublicKeyToken() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (!base.HasPublicKey) { return PublicKey; } if (_publicKeyToken == null) { _publicKeyToken = ((PublicKey != null) ? AssemblyDescriptor.ComputePublicKeyToken(PublicKey, HashAlgorithm) : null); } return _publicKeyToken; } public override bool IsImportedInModule(ModuleDefinition module) { return ManifestModule == module; } public override AssemblyReference ImportWith(ReferenceImporter importer) { return (AssemblyReference)importer.ImportScope(new AssemblyReference(this)); } public override AssemblyDefinition Resolve() { return this; } public virtual bool TryGetTargetFramework(out DotNetRuntimeInfo info) { for (int i = 0; i < base.CustomAttributes.Count; i++) { ICustomAttributeType constructor = base.CustomAttributes[i].Constructor; if (constructor?.DeclaringType != null && constructor.DeclaringType.IsTypeOf("System.Runtime.Versioning", "TargetFrameworkAttribute") && base.CustomAttributes[i].Signature?.FixedArguments[0].Element is string frameworkName && DotNetRuntimeInfo.TryParse(frameworkName, out info)) { return true; } } info = default(DotNetRuntimeInfo); return false; } public void Write(string filePath) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown Write(filePath, new ManagedPEImageBuilder(), (IPEFileBuilder)new ManagedPEFileBuilder()); } public void Write(string filePath, IPEImageBuilder imageBuilder) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown Write(filePath, imageBuilder, (IPEFileBuilder)new ManagedPEFileBuilder()); } public void Write(string filePath, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder) { string directoryName = Path.GetDirectoryName(Path.GetFullPath(filePath)); if (directoryName == null || !Directory.Exists(directoryName)) { throw new DirectoryNotFoundException(); } for (int i = 0; i < Modules.Count; i++) { ModuleDefinition moduleDefinition = Modules[i]; string text; if (moduleDefinition != ManifestModule) { Utf8String? name = moduleDefinition.Name; text = Path.Combine(directoryName, ((name != null) ? name.Value : null) ?? $"module{i}.bin"); } else { text = filePath; } string filePath2 = text; moduleDefinition.Write(filePath2, imageBuilder, fileBuilder); } } public void WriteManifest(Stream stream) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown WriteManifest(stream, new ManagedPEImageBuilder(), (IPEFileBuilder)new ManagedPEFileBuilder()); } public void WriteManifest(Stream stream, IPEImageBuilder imageBuilder) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown WriteManifest(stream, imageBuilder, (IPEFileBuilder)new ManagedPEFileBuilder()); } public void WriteManifest(Stream stream, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder) { ManifestModule?.Write(stream, imageBuilder, fileBuilder); } } public abstract class AssemblyDescriptor : MetadataMember, IHasCustomAttribute, IMetadataMember, IFullNameProvider, INameProvider, IImportable { private const int PublicKeyTokenLength = 8; private readonly LazyVariable _name; private readonly LazyVariable _culture; private IList? _customAttributes; public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public string FullName { get { byte[] publicKeyToken = GetPublicKeyToken(); string value = ((publicKeyToken != null) ? string.Join(string.Empty, publicKeyToken.Select((byte x) => x.ToString("x2"))) : "null"); return $"{Name}, Version={Version}, PublicKeyToken={value}"; } } public Version Version { get; set; } public AssemblyAttributes Attributes { get; set; } public bool HasPublicKey { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 1) > 0; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (AssemblyAttributes)((Attributes & -2) | (value ? 1 : 0)); } } public bool EnableJitCompileTracking { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x8000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (AssemblyAttributes)((Attributes & -32769) | (value ? 32768 : 0)); } } public bool DisableJitCompileOptimizer { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x4000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (AssemblyAttributes)((Attributes & -16385) | (value ? 16384 : 0)); } } public bool IsWindowsRuntime { get { //IL_0001: 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_0011: Invalid comparison between Unknown and I4 return (Attributes & 0xE00) == 512; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (AssemblyAttributes)((Attributes & -3585) | (value ? 512 : 0)); } } public bool IsRetargetable { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x100) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (AssemblyAttributes)((Attributes & -257) | (value ? 256 : 0)); } } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } public Utf8String? Culture { get { return _culture.Value; } set { _culture.Value = value; } } public abstract bool IsCorLib { get; } protected AssemblyDescriptor(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _culture = new LazyVariable((Func)GetCulture); Version = new Version(0, 0, 0, 0); } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } public abstract byte[]? GetPublicKeyToken(); protected virtual Utf8String? GetName() { return null; } protected virtual Utf8String? GetCulture() { return null; } public override string ToString() { return FullName; } public abstract bool IsImportedInModule(ModuleDefinition module); public abstract AssemblyReference ImportWith(ReferenceImporter importer); IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } protected static byte[] ComputePublicKeyToken(byte[] publicKey, AssemblyHashAlgorithm algorithm) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Invalid comparison between Unknown and I4 //IL_0008: 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_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected I4, but got Unknown //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_007f: Unknown result type (might be due to invalid IL or missing references) HashAlgorithm hashAlgorithm; if ((int)algorithm <= 32771) { if ((int)algorithm != 0) { if ((int)algorithm != 32771) { goto IL_0067; } hashAlgorithm = MD5.Create(); } else { hashAlgorithm = SHA1.Create(); } } else if ((int)algorithm != 32772) { switch (algorithm - 32780) { case 0: break; case 1: goto IL_0057; case 2: goto IL_005f; default: goto IL_0067; } hashAlgorithm = SHA256.Create(); } else { hashAlgorithm = SHA1.Create(); } goto IL_009e; IL_009e: using (HashAlgorithm hashAlgorithm2 = hashAlgorithm) { byte[] array = hashAlgorithm2.ComputeHash(publicKey); byte[] array2 = new byte[8]; for (int i = 0; i < 8; i++) { array2[i] = array[array.Length - 1 - i]; } return array2; } IL_0067: throw new NotSupportedException($"Unsupported hashing algorithm {algorithm}."); IL_0057: hashAlgorithm = SHA384.Create(); goto IL_009e; IL_005f: hashAlgorithm = SHA512.Create(); goto IL_009e; } public abstract AssemblyDefinition? Resolve(); } public class AssemblyReference : AssemblyDescriptor, IResolutionScope, IMetadataMember, INameProvider, IModuleProvider, IImportable, IOwnedCollectionElement, IImplementation, IFullNameProvider, IHasCustomAttribute { private readonly LazyVariable _publicKeyOrToken; private readonly LazyVariable _hashValue; private byte[]? _publicKeyToken; public ModuleDefinition? Module { get; private set; } ModuleDefinition? IOwnedCollectionElement.Owner { get { return Module; } set { Module = value; } } public byte[]? PublicKeyOrToken { get { return _publicKeyOrToken.Value; } set { _publicKeyOrToken.Value = value; } } public byte[]? HashValue { get { return _hashValue.Value; } set { _hashValue.Value = value; } } public override bool IsCorLib => KnownCorLibs.KnownCorLibReferences.Contains(this); protected AssemblyReference(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _publicKeyOrToken = new LazyVariable((Func)GetPublicKeyOrToken); _hashValue = new LazyVariable((Func)GetHashValue); } public AssemblyReference(Utf8String? name, Version version) : this(new MetadataToken((TableIndex)35, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) base.Name = name; base.Version = version; } public AssemblyReference(Utf8String? name, Version version, bool publicKey, byte[]? publicKeyOrToken) : this(new MetadataToken((TableIndex)35, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) base.Name = name; base.Version = version; base.HasPublicKey = publicKey; PublicKeyOrToken = publicKeyOrToken; } public AssemblyReference(AssemblyDescriptor descriptor) : this(new MetadataToken((TableIndex)35, 0u)) { //IL_0004: 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) base.Name = descriptor.Name; base.Version = descriptor.Version; base.Attributes = descriptor.Attributes; base.HasPublicKey = false; PublicKeyOrToken = descriptor.GetPublicKeyToken(); byte[]? publicKeyOrToken = PublicKeyOrToken; if (publicKeyOrToken != null && publicKeyOrToken.Length == 0) { PublicKeyOrToken = null; } base.Culture = descriptor.Culture; if (Utf8String.IsNullOrEmpty(base.Culture)) { base.Culture = null; } } public override byte[]? GetPublicKeyToken() { if (!base.HasPublicKey) { return PublicKeyOrToken; } if (_publicKeyToken == null && PublicKeyOrToken != null) { lock (_publicKeyOrToken) { if (_publicKeyToken == null && PublicKeyOrToken != null) { _publicKeyToken = AssemblyDescriptor.ComputePublicKeyToken(PublicKeyOrToken, (AssemblyHashAlgorithm)32772); } } } return _publicKeyToken; } protected virtual byte[]? GetPublicKeyOrToken() { return null; } protected virtual byte[]? GetHashValue() { return null; } public override bool IsImportedInModule(ModuleDefinition module) { return Module == module; } public override AssemblyReference ImportWith(ReferenceImporter importer) { return (AssemblyReference)importer.ImportScope(this); } public override AssemblyDefinition? Resolve() { return Module?.MetadataResolver.AssemblyResolver.Resolve(this); } AssemblyDescriptor IResolutionScope.GetAssembly() { return this; } } public abstract class AssemblyResolverBase : IAssemblyResolver { private static readonly string[] BinaryFileExtensions = new string[2] { ".dll", ".exe" }; private static readonly SignatureComparer Comparer = new SignatureComparer(SignatureComparisonFlags.AcceptNewerVersions); private readonly Dictionary _cache = new Dictionary(new SignatureComparer()); public IFileService FileService { get; } public IList SearchDirectories { get; } = new List(); protected AssemblyResolverBase(IFileService fileService) { FileService = fileService ?? throw new ArgumentNullException("fileService"); } public AssemblyDefinition? Resolve(AssemblyDescriptor assembly) { if (_cache.TryGetValue(assembly, out AssemblyDefinition value)) { return value; } value = ResolveImpl(assembly); if (value != null) { _cache.Add(assembly, value); } return value; } public void AddToCache(AssemblyDescriptor descriptor, AssemblyDefinition definition) { if (_cache.ContainsKey(descriptor)) { throw new ArgumentException("The cache already contains an entry of assembly " + descriptor.FullName + ".", "descriptor"); } if (!Comparer.Equals(descriptor, definition)) { throw new ArgumentException("Assembly descriptor and definition do not refer to the same assembly."); } _cache.Add(descriptor, definition); } public bool RemoveFromCache(AssemblyDescriptor descriptor) { return _cache.Remove(descriptor); } public bool HasCached(AssemblyDescriptor descriptor) { return _cache.ContainsKey(descriptor); } public void ClearCache() { _cache.Clear(); } protected virtual AssemblyDefinition? ResolveImpl(AssemblyDescriptor assembly) { string text = ProbeSearchDirectories(assembly); if (string.IsNullOrEmpty(text)) { if (assembly.GetPublicKeyToken() != null) { text = ProbeRuntimeDirectories(assembly); } if (string.IsNullOrEmpty(text)) { return null; } } AssemblyDefinition result = null; try { result = LoadAssemblyFromFile(text); } catch { } return result; } protected virtual AssemblyDefinition LoadAssemblyFromFile(string path) { return AssemblyDefinition.FromFile(FileService.OpenFile(path)); } protected string? ProbeSearchDirectories(AssemblyDescriptor assembly) { for (int i = 0; i < SearchDirectories.Count; i++) { string text = ProbeDirectory(assembly, SearchDirectories[i]); if (!string.IsNullOrEmpty(text)) { return text; } } return null; } protected abstract string? ProbeRuntimeDirectories(AssemblyDescriptor assembly); protected static string? ProbeDirectory(AssemblyDescriptor assembly, string directory) { if (assembly.Name == null) { return null; } string text; if (!string.IsNullOrEmpty(Utf8String.op_Implicit(assembly.Culture))) { text = Path.Combine(directory, Utf8String.op_Implicit(assembly.Culture), Utf8String.op_Implicit(assembly.Name)); if ((ProbeFileFromFilePathWithoutExtension(text) ?? ProbeFileFromFilePathWithoutExtension(Path.Combine(text, Utf8String.op_Implicit(assembly.Name)))) == null) { return null; } } text = Path.Combine(directory, Utf8String.op_Implicit(assembly.Name)); return ProbeFileFromFilePathWithoutExtension(text) ?? ProbeFileFromFilePathWithoutExtension(Path.Combine(text, Utf8String.op_Implicit(assembly.Name))); } internal static string? ProbeFileFromFilePathWithoutExtension(string baseFilePath) { string[] binaryFileExtensions = BinaryFileExtensions; foreach (string text in binaryFileExtensions) { string text2 = baseFilePath + text; if (File.Exists(text2)) { return text2; } } return null; } } public class ClassLayout : MetadataMember { private readonly LazyVariable _parent; public ushort PackingSize { get; set; } public uint ClassSize { get; set; } public TypeDefinition? Parent { get { return _parent.Value; } internal set { _parent.Value = value; } } protected ClassLayout(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _parent = new LazyVariable((Func)GetParent); } public ClassLayout(ushort packingSize, uint classSize) : this(new MetadataToken((TableIndex)15, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) PackingSize = packingSize; ClassSize = classSize; } protected virtual TypeDefinition? GetParent() { return null; } public override string ToString() { return $"{"PackingSize"}: {PackingSize}, {"ClassSize"}: {ClassSize}"; } } public class Constant : MetadataMember { private readonly LazyVariable _parent; private readonly LazyVariable _value; public ElementType Type { get; set; } public IHasConstant? Parent { get { return _parent.Value; } internal set { _parent.Value = value; } } public DataBlobSignature? Value { get { return _value.Value; } set { _value.Value = value; } } protected Constant(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _parent = new LazyVariable((Func)GetParent); _value = new LazyVariable((Func)GetValue); } public Constant(ElementType type, DataBlobSignature? value) : this(new MetadataToken((TableIndex)11, 0u)) { //IL_0004: 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) Type = type; Value = value; } protected virtual IHasConstant? GetParent() { return null; } protected virtual DataBlobSignature? GetValue() { return null; } public static Constant FromValue(bool value) { return new Constant((ElementType)2, DataBlobSignature.FromValue(value)); } public static Constant FromValue(char value) { return new Constant((ElementType)3, DataBlobSignature.FromValue(value)); } public static Constant FromValue(byte value) { return new Constant((ElementType)5, DataBlobSignature.FromValue(value)); } public static Constant FromValue(sbyte value) { return new Constant((ElementType)4, DataBlobSignature.FromValue(value)); } public static Constant FromValue(ushort value) { return new Constant((ElementType)7, DataBlobSignature.FromValue(value)); } public static Constant FromValue(short value) { return new Constant((ElementType)6, DataBlobSignature.FromValue(value)); } public static Constant FromValue(uint value) { return new Constant((ElementType)9, DataBlobSignature.FromValue(value)); } public static Constant FromValue(int value) { return new Constant((ElementType)8, DataBlobSignature.FromValue(value)); } public static Constant FromValue(ulong value) { return new Constant((ElementType)11, DataBlobSignature.FromValue(value)); } public static Constant FromValue(long value) { return new Constant((ElementType)10, DataBlobSignature.FromValue(value)); } public static Constant FromValue(float value) { return new Constant((ElementType)12, DataBlobSignature.FromValue(value)); } public static Constant FromValue(double value) { return new Constant((ElementType)13, DataBlobSignature.FromValue(value)); } public static Constant FromValue(string value) { return new Constant((ElementType)14, DataBlobSignature.FromValue(value)); } } public class CustomAttribute : MetadataMember, IOwnedCollectionElement { private readonly LazyVariable _parent; private readonly LazyVariable _constructor; private readonly LazyVariable _signature; public IHasCustomAttribute? Parent { get { return _parent.Value; } private set { _parent.Value = value; } } IHasCustomAttribute? IOwnedCollectionElement.Owner { get { return Parent; } set { Parent = value; } } public ICustomAttributeType? Constructor { get { return _constructor.Value; } set { _constructor.Value = value; } } public CustomAttributeSignature? Signature { get { return _signature.Value; } set { _signature.Value = value; } } protected CustomAttribute(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _parent = new LazyVariable((Func)GetParent); _constructor = new LazyVariable((Func)GetConstructor); _signature = new LazyVariable((Func)GetSignature); } public CustomAttribute(ICustomAttributeType? constructor) : this(new MetadataToken((TableIndex)12, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Constructor = constructor; Signature = new CustomAttributeSignature(); } public CustomAttribute(ICustomAttributeType? constructor, CustomAttributeSignature? signature) : this(new MetadataToken((TableIndex)12, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Constructor = constructor; Signature = signature; } protected virtual IHasCustomAttribute? GetParent() { return null; } protected virtual ICustomAttributeType? GetConstructor() { return null; } protected virtual CustomAttributeSignature? GetSignature() { return null; } public override string ToString() { return Constructor?.FullName ?? "<<>>"; } } public class DefaultMetadataResolver : IMetadataResolver { private readonly struct TypeResolution { private readonly IAssemblyResolver _assemblyResolver; private readonly Stack _scopeStack; private readonly Stack _implementationStack; public TypeResolution(IAssemblyResolver resolver) { _assemblyResolver = resolver ?? throw new ArgumentNullException("resolver"); _scopeStack = new Stack(); _implementationStack = new Stack(); } public TypeDefinition? ResolveTypeReference(TypeReference? reference) { //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_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_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Invalid comparison between Unknown and I4 //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Invalid comparison between Unknown and I4 IResolutionScope resolutionScope = reference?.Scope; if (reference?.Name == null || resolutionScope == null || _scopeStack.Contains(resolutionScope)) { return null; } _scopeStack.Push(resolutionScope); MetadataToken metadataToken = resolutionScope.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; if ((int)table != 0) { if ((int)table != 1) { if ((int)table == 35) { AssemblyDefinition assemblyDefinition = _assemblyResolver.Resolve((AssemblyReference)resolutionScope); if (assemblyDefinition == null) { return null; } return FindTypeInAssembly(assemblyDefinition, reference.Namespace, reference.Name); } return null; } TypeDefinition typeDefinition = ResolveTypeReference((TypeReference)resolutionScope); if (typeDefinition == null) { return null; } return FindTypeInType(typeDefinition, reference.Name); } return FindTypeInModule((ModuleDefinition)resolutionScope, reference.Namespace, reference.Name); } public TypeDefinition? ResolveExportedType(ExportedType? exportedType) { //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_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_004b: 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_0069: Expected I4, but got Unknown IImplementation implementation = exportedType?.Implementation; if (exportedType?.Name == null || implementation == null || _implementationStack.Contains(implementation)) { return null; } _implementationStack.Push(implementation); MetadataToken metadataToken = implementation.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; switch (table - 35) { case 0: { AssemblyDefinition assemblyDefinition = _assemblyResolver.Resolve((AssemblyReference)implementation); if (assemblyDefinition == null) { return null; } return FindTypeInAssembly(assemblyDefinition, exportedType.Namespace, exportedType.Name); } case 3: if (!string.IsNullOrEmpty(implementation.Name)) { ModuleDefinition moduleDefinition = FindModuleInAssembly(exportedType.Module.Assembly, Utf8String.op_Implicit(implementation.Name)); if (moduleDefinition == null) { return null; } return FindTypeInModule(moduleDefinition, exportedType.Namespace, exportedType.Name); } break; case 4: { ExportedType exportedType2 = (ExportedType)implementation; TypeDefinition typeDefinition = ResolveExportedType(exportedType2); if (typeDefinition == null) { return null; } return FindTypeInType(typeDefinition, exportedType.Name); } } throw new ArgumentOutOfRangeException(); } private TypeDefinition? FindTypeInAssembly(AssemblyDefinition assembly, Utf8String? ns, Utf8String name) { for (int i = 0; i < assembly.Modules.Count; i++) { ModuleDefinition module = assembly.Modules[i]; TypeDefinition typeDefinition = FindTypeInModule(module, ns, name); if (typeDefinition != null) { return typeDefinition; } } return null; } private TypeDefinition? FindTypeInModule(ModuleDefinition module, Utf8String? ns, Utf8String name) { for (int i = 0; i < module.ExportedTypes.Count; i++) { ExportedType exportedType = module.ExportedTypes[i]; if (exportedType.IsTypeOfUtf8(ns, name)) { return ResolveExportedType(exportedType); } } for (int j = 0; j < module.TopLevelTypes.Count; j++) { TypeDefinition typeDefinition = module.TopLevelTypes[j]; if (typeDefinition.IsTypeOfUtf8(ns, name)) { return typeDefinition; } } return null; } private static TypeDefinition? FindTypeInType(TypeDefinition enclosingType, Utf8String name) { for (int i = 0; i < enclosingType.NestedTypes.Count; i++) { TypeDefinition typeDefinition = enclosingType.NestedTypes[i]; if (typeDefinition.Name == name) { return typeDefinition; } } return null; } private static ModuleDefinition? FindModuleInAssembly(AssemblyDefinition assembly, Utf8String name) { for (int i = 0; i < assembly.Modules.Count; i++) { ModuleDefinition moduleDefinition = assembly.Modules[i]; if (moduleDefinition.Name == name) { return moduleDefinition; } } return null; } } private readonly ConcurrentDictionary _typeCache; private readonly SignatureComparer _comparer = new SignatureComparer(SignatureComparisonFlags.VersionAgnostic); public IAssemblyResolver AssemblyResolver { get; } public DefaultMetadataResolver(IAssemblyResolver assemblyResolver) { AssemblyResolver = assemblyResolver ?? throw new ArgumentNullException("assemblyResolver"); _typeCache = new ConcurrentDictionary(); } public TypeDefinition? ResolveType(ITypeDescriptor? type) { if (!(type is TypeDefinition result)) { if (!(type is TypeReference reference)) { if (!(type is TypeSpecification typeSpecification)) { if (!(type is TypeSignature signature)) { if (type is ExportedType exportedType) { return ResolveExportedType(exportedType); } return null; } return ResolveTypeSignature(signature); } return ResolveType(typeSpecification.Signature); } return ResolveTypeReference(reference); } return result; } private TypeDefinition? LookupInCache(ITypeDescriptor type) { if (_typeCache.TryGetValue(type, out TypeDefinition value)) { if (value.IsTypeOf(type.Namespace, type.Name)) { return value; } _typeCache.TryRemove(type, out TypeDefinition _); } return null; } private TypeDefinition? ResolveTypeReference(TypeReference? reference) { if (reference == null) { return null; } TypeDefinition typeDefinition = LookupInCache(reference); if (typeDefinition != null) { return typeDefinition; } typeDefinition = new TypeResolution(AssemblyResolver).ResolveTypeReference(reference); if (typeDefinition != null) { _typeCache[reference] = typeDefinition; } return typeDefinition; } private TypeDefinition? ResolveExportedType(ExportedType? exportedType) { if (exportedType == null) { return null; } TypeDefinition typeDefinition = LookupInCache(exportedType); if (typeDefinition != null) { return typeDefinition; } typeDefinition = new TypeResolution(AssemblyResolver).ResolveExportedType(exportedType); if (typeDefinition != null) { _typeCache[exportedType] = typeDefinition; } return typeDefinition; } private TypeDefinition? ResolveTypeSignature(TypeSignature? signature) { //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_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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Invalid comparison between Unknown and I4 //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Invalid comparison between Unknown and I4 ITypeDefOrRef typeDefOrRef = signature?.GetUnderlyingTypeDefOrRef(); if (typeDefOrRef == null) { return null; } MetadataToken metadataToken = typeDefOrRef.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; if ((int)table != 1) { if ((int)table != 2) { if ((int)table == 27) { return ResolveTypeSignature(((TypeSpecification)typeDefOrRef).Signature); } return null; } return (TypeDefinition)typeDefOrRef; } return ResolveTypeReference((TypeReference)typeDefOrRef); } public MethodDefinition? ResolveMethod(IMethodDescriptor? method) { if (method == null) { return null; } TypeDefinition typeDefinition = ResolveType(method.DeclaringType); if (typeDefinition == null) { return null; } for (int i = 0; i < typeDefinition.Methods.Count; i++) { MethodDefinition methodDefinition = typeDefinition.Methods[i]; if (methodDefinition.Name == method.Name && _comparer.Equals(method.Signature, methodDefinition.Signature)) { return methodDefinition; } } return null; } public FieldDefinition? ResolveField(IFieldDescriptor? field) { if (field == null) { return null; } TypeDefinition typeDefinition = ResolveType(field.DeclaringType); if (typeDefinition == null) { return null; } if (!(field is MemberReference memberReference)) { _ = field.Name; } else { _ = memberReference.Name; } for (int i = 0; i < typeDefinition.Fields.Count; i++) { FieldDefinition fieldDefinition = typeDefinition.Fields[i]; if (fieldDefinition.Name == field.Name && _comparer.Equals(field.Signature, fieldDefinition.Signature)) { return fieldDefinition; } } return null; } } public class DotNetCoreAssemblyResolver : AssemblyResolverBase { private sealed class RuntimeNameComparer : IComparer { public static readonly RuntimeNameComparer Instance = new RuntimeNameComparer(); public int Compare(string? x, string? y) { if (x == y) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } if (x == "Microsoft.NETCore.App") { return 1; } if (y == "Microsoft.NETCore.App") { return -1; } return 0; } } private readonly List _runtimeDirectories = new List(); public DotNetCoreAssemblyResolver(Version runtimeVersion) : this((IFileService)(object)UncachedFileService.Instance, null, runtimeVersion, DotNetCorePathProvider.Default) { } public DotNetCoreAssemblyResolver(IFileService fileService, Version runtimeVersion) : this(fileService, null, runtimeVersion, DotNetCorePathProvider.Default) { } public DotNetCoreAssemblyResolver(RuntimeConfiguration? configuration, Version fallbackVersion) : this((IFileService)(object)UncachedFileService.Instance, configuration, fallbackVersion, DotNetCorePathProvider.Default) { } public DotNetCoreAssemblyResolver(IFileService fileService, RuntimeConfiguration? configuration, Version fallbackVersion) : this(fileService, configuration, fallbackVersion, DotNetCorePathProvider.Default) { } public DotNetCoreAssemblyResolver(IFileService fileService, RuntimeConfiguration? configuration, DotNetCorePathProvider pathProvider) : this(fileService, configuration, null, pathProvider) { } public DotNetCoreAssemblyResolver(IFileService fileService, RuntimeConfiguration? configuration, Version? fallbackVersion, DotNetCorePathProvider pathProvider) : base(fileService) { if ((object)fallbackVersion == null) { throw new ArgumentNullException("fallbackVersion"); } if (pathProvider == null) { throw new ArgumentNullException("pathProvider"); } bool flag = false; RuntimeOptions runtimeOptions = configuration?.RuntimeOptions; if (runtimeOptions != null) { foreach (RuntimeFramework item in runtimeOptions.GetAllFrameworks().OrderBy((RuntimeFramework framework) => framework.Name, RuntimeNameComparer.Instance)) { string[] frameworkDirectories = GetFrameworkDirectories(pathProvider, item); if (frameworkDirectories.Length != 0) { flag |= item.Name == "Microsoft.NETCore.App"; _runtimeDirectories.AddRange(frameworkDirectories); } } } if (pathProvider.HasRuntimeInstalled(fallbackVersion)) { if (_runtimeDirectories.Count == 0) { _runtimeDirectories.AddRange(pathProvider.GetRuntimePathCandidates(fallbackVersion)); } else if (!flag) { _runtimeDirectories.AddRange(pathProvider.GetRuntimePathCandidates("Microsoft.NETCore.App", fallbackVersion)); } } } private static string[] GetFrameworkDirectories(DotNetCorePathProvider pathProvider, RuntimeFramework framework) { if (TryParseVersion(framework.Version, out Version version) && pathProvider.HasRuntimeInstalled(framework.Name, version)) { return pathProvider.GetRuntimePathCandidates(framework.Name, version).ToArray(); } return Array.Empty(); } protected override string? ProbeRuntimeDirectories(AssemblyDescriptor assembly) { foreach (string runtimeDirectory in _runtimeDirectories) { string text = AssemblyResolverBase.ProbeDirectory(assembly, runtimeDirectory); if (!string.IsNullOrEmpty(text)) { return text; } } return null; } private static bool TryParseVersion(string? versionString, [NotNullWhen(true)] out Version? version) { if (string.IsNullOrEmpty(versionString)) { version = null; return false; } int num = versionString.IndexOf('-'); if (num >= 0) { versionString = versionString.Remove(num); } return Version.TryParse(versionString, out version); } } public class DotNetCorePathProvider { private readonly struct DotNetInstallationInfo : IComparable { public string Name { get; } public string FullPath { get; } public IReadOnlyList InstalledVersions { get; } public DotNetInstallationInfo(string path) { string fileName = Path.GetFileName(path); List list = DetectInstalledVersionsInDirectory(fileName, path); Name = fileName; FullPath = path; InstalledVersions = list.AsReadOnly(); } public bool TryFindBestMatchingVersion(Version requestedVersion, out DotNetRuntimeVersionInfo versionInfo) { versionInfo = default(DotNetRuntimeVersionInfo); Version version = new Version(); bool result = false; for (int i = 0; i < InstalledVersions.Count; i++) { DotNetRuntimeVersionInfo dotNetRuntimeVersionInfo = InstalledVersions[i]; Version version2 = dotNetRuntimeVersionInfo.Version; if (version2 == requestedVersion) { versionInfo = dotNetRuntimeVersionInfo; return true; } if (version2.Major == requestedVersion.Major && version < requestedVersion) { versionInfo = dotNetRuntimeVersionInfo; version = version2; result = true; } } return result; } private static List DetectInstalledVersionsInDirectory(string name, string path) { List list = new List(); foreach (string item in Directory.EnumerateDirectories(path)) { string text = Path.GetFileName(item); int num = text.IndexOf('-'); if (num >= 0) { text = text.Remove(num); } if (Version.TryParse(text, out Version result)) { list.Add(new DotNetRuntimeVersionInfo(name, result, item)); } } return list; } public int CompareTo(DotNetInstallationInfo other) { if (Name == other.Name) { return 0; } if (Name == "Microsoft.NETCore.App") { return 1; } if (other.Name == "Microsoft.NETCore.App") { return -1; } return 0; } } private readonly struct DotNetRuntimeVersionInfo { public string RuntimeName { get; } public Version Version { get; } public string FullPath { get; } public DotNetRuntimeVersionInfo(string runtimeName, Version version, string fullPath) { RuntimeName = runtimeName; Version = version; FullPath = fullPath; } public bool IsCompatibleWithStandard(Version standardVersion) { if (standardVersion.Major == 2) { if (standardVersion.Minor == 0) { return Version.Major >= 2; } if (standardVersion.Minor == 1) { return Version.Major >= 3; } } return true; } } private static readonly string[] DefaultDotNetUnixPaths; private static readonly Regex NetCoreRuntimePattern; private readonly List _installedRuntimes = new List(); public static DotNetCorePathProvider Default { get; } public static string? DefaultInstallationPath { get; } static DotNetCorePathProvider() { DefaultDotNetUnixPaths = new string[3] { "/usr/share/dotnet/", "/usr/local/share/dotnet/", "/opt/dotnet/" }; NetCoreRuntimePattern = new Regex("\\.NET( Core)? \\d+\\.\\d+\\.\\d+"); DefaultInstallationPath = FindDotNetPath(); Default = new DotNetCorePathProvider(); } public DotNetCorePathProvider() : this(DefaultInstallationPath) { } public DotNetCorePathProvider(string? installationDirectory) { if (!string.IsNullOrEmpty(installationDirectory) && Directory.Exists(installationDirectory)) { DetectInstalledRuntimes(installationDirectory); } } public bool TryGetLatestStandardCompatibleVersion(Version standardVersion, [NotNullWhen(true)] out Version? coreVersion) { bool result = false; coreVersion = null; foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes) { for (int i = 0; i < installedRuntime.InstalledVersions.Count; i++) { DotNetRuntimeVersionInfo dotNetRuntimeVersionInfo = installedRuntime.InstalledVersions[i]; if (dotNetRuntimeVersionInfo.IsCompatibleWithStandard(standardVersion) && ((object)coreVersion == null || dotNetRuntimeVersionInfo.Version > coreVersion)) { result = true; coreVersion = dotNetRuntimeVersionInfo.Version; } } } return result; } public IEnumerable GetRuntimePathCandidates(Version requestedRuntimeVersion) { foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes) { if (installedRuntime.TryFindBestMatchingVersion(requestedRuntimeVersion, out var versionInfo)) { yield return versionInfo.FullPath; } } } public IEnumerable GetRuntimePathCandidates(string runtimeName, Version runtimeVersion) { foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes) { if (installedRuntime.Name == runtimeName && installedRuntime.TryFindBestMatchingVersion(runtimeVersion, out var versionInfo)) { yield return versionInfo.FullPath; } } } public bool HasRuntimeInstalled(Version runtimeVersion) { foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes) { if (installedRuntime.TryFindBestMatchingVersion(runtimeVersion, out var _)) { return true; } } return false; } public bool HasRuntimeInstalled(string runtimeName, Version runtimeVersion) { foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes) { if (installedRuntime.Name == runtimeName && installedRuntime.TryFindBestMatchingVersion(runtimeVersion, out var _)) { return true; } } return false; } private void DetectInstalledRuntimes(string installationDirectory) { installationDirectory = Path.Combine(installationDirectory, "shared"); if (!Directory.Exists(installationDirectory)) { return; } foreach (string item in Directory.EnumerateDirectories(installationDirectory)) { _installedRuntimes.Add(new DotNetInstallationInfo(item)); } _installedRuntimes.Sort(); } private static string? FindDotNetPath() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { string[] array = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator); foreach (string text in array) { if (File.Exists(Path.Combine(text, "dotnet.exe"))) { return text; } } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { string[] array = DefaultDotNetUnixPaths; foreach (string text2 in array) { if (File.Exists(Path.Combine(text2, "dotnet"))) { return text2; } } } if (NetCoreRuntimePattern.Match(RuntimeInformation.FrameworkDescription).Success) { return Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Assembly.Location)))); } return null; } } public class DotNetFrameworkAssemblyResolver : AssemblyResolverBase { public IList Gac32Directories { get; } = new List(); public IList Gac64Directories { get; } = new List(); public IList GacMsilDirectories { get; } = new List(); public DotNetFrameworkAssemblyResolver() : this((IFileService)(object)UncachedFileService.Instance) { } public DotNetFrameworkAssemblyResolver(IFileService fileService) : base(fileService) { DetectGacDirectories(); } private void DetectGacDirectories() { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { DetectWindowsGacDirectories(); } else if (Directory.Exists("/usr/lib/mono")) { DetectMonoGacDirectories(); } } private void DetectWindowsGacDirectories() { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows); string windowsGac = Path.Combine(folderPath, "assembly"); AddGacDirectories(windowsGac, null); string windowsGac2 = Path.Combine(folderPath, "Microsoft.NET", "assembly"); AddGacDirectories(windowsGac2, "v4.0_"); } private void DetectMonoGacDirectories() { if (Directory.Exists("/usr/lib/mono/gac")) { GacMsilDirectories.Add(new GacDirectory("/usr/lib/mono/gac")); } string text = (from d in Directory.EnumerateDirectories("/usr/lib/mono") where d.EndsWith("-api") select d into x orderby x descending select x).FirstOrDefault(); if (text != null) { base.SearchDirectories.Add(text); } } private void AddGacDirectories(string windowsGac, string? prefix) { if (!Directory.Exists(windowsGac)) { return; } foreach (string item in Directory.EnumerateDirectories(windowsGac)) { GetGacDirectoryCollection(item).Add(new GacDirectory(item, prefix)); } IList GetGacDirectoryCollection(string directory) { string fileName = Path.GetFileName(directory); if (fileName == "GAC_32") { return Gac32Directories; } if (fileName == "GAC_64") { return Gac64Directories; } return GacMsilDirectories; } } protected override string? ProbeRuntimeDirectories(AssemblyDescriptor assembly) { AssemblyDescriptor assembly2 = assembly; bool flag; bool flag2; if (assembly2 is IModuleProvider moduleProvider) { ModuleDefinition module = moduleProvider.Module; if (module != null) { flag = module.IsBit32Preferred; flag2 = module.IsBit32Required; goto IL_0038; } } flag = false; flag2 = false; goto IL_0038; IL_0038: string text; if (flag2) { text = ProbeGacDirectories(Gac32Directories); } else if (flag) { text = ProbeGacDirectories(Gac32Directories); if (text == null) { text = ProbeGacDirectories(Gac64Directories); } } else { text = ProbeGacDirectories(Gac64Directories); if (text == null) { text = ProbeGacDirectories(Gac32Directories); } } return text ?? ProbeGacDirectories(GacMsilDirectories); string? ProbeGacDirectories(IList directories) { for (int i = 0; i < directories.Count; i++) { string text2 = directories[i].Probe(assembly2); if (text2 != null) { return text2; } } return null; } } } public readonly struct DotNetRuntimeInfo { public const string NetCoreApp = ".NETCoreApp"; public const string NetStandard = ".NETStandard"; public const string NetFramework = ".NETFramework"; private static readonly Regex FormatRegex = new Regex("([a-zA-Z.]+)\\s*,\\s*Version=v(\\d+\\.\\d+)"); public string Name { get; } public Version Version { get; } public bool IsNetCoreApp => Name == ".NETCoreApp"; public bool IsNetFramework => Name == ".NETFramework"; public bool IsNetStandard => Name == ".NETStandard"; public DotNetRuntimeInfo(string name, Version version) { Name = name ?? throw new ArgumentNullException("name"); Version = version ?? throw new ArgumentNullException("version"); } public static bool TryParse(string frameworkName, out DotNetRuntimeInfo info) { Match match = FormatRegex.Match(frameworkName); if (!match.Success) { info = default(DotNetRuntimeInfo); return false; } string value = match.Groups[1].Value; Version version = new Version(match.Groups[2].Value); info = new DotNetRuntimeInfo(value, version); return true; } public override string ToString() { return $"{Name},Version=v{Version}"; } } public class EventDefinition : MetadataMember, IHasSemantics, IMetadataMember, IMemberDefinition, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IHasCustomAttribute, IOwnedCollectionElement { private readonly LazyVariable _name; private readonly LazyVariable _declaringType; private readonly LazyVariable _eventType; private IList? _semantics; private IList? _customAttributes; public EventAttributes Attributes { get; set; } public bool IsSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x200) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (EventAttributes)((Attributes & 0xFDFF) | (value ? 512 : 0)); } } public bool IsRuntimeSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x400) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (EventAttributes)((Attributes & 0xFBFF) | (value ? 1024 : 0)); } } public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public string FullName => MemberNameGenerator.GetEventFullName(this); public ITypeDefOrRef? EventType { get { return _eventType.Value; } set { _eventType.Value = value; } } public ModuleDefinition? Module => DeclaringType?.Module; public TypeDefinition? DeclaringType { get { return _declaringType.Value; } private set { _declaringType.Value = value; } } ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; TypeDefinition? IOwnedCollectionElement.Owner { get { return DeclaringType; } set { DeclaringType = value; } } public IList Semantics { get { if (_semantics == null) { Interlocked.CompareExchange(ref _semantics, GetSemantics(), null); } return _semantics; } } public MethodDefinition? AddMethod => Semantics.FirstOrDefault((MethodSemantics s) => (int)s.Attributes == 8)?.Method; public MethodDefinition? RemoveMethod => Semantics.FirstOrDefault((MethodSemantics s) => (int)s.Attributes == 16)?.Method; public MethodDefinition? FireMethod => Semantics.FirstOrDefault((MethodSemantics s) => (int)s.Attributes == 32)?.Method; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected EventDefinition(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)(() => GetName())); _eventType = new LazyVariable((Func)GetEventType); _declaringType = new LazyVariable((Func)GetDeclaringType); } public EventDefinition(Utf8String? name, EventAttributes attributes, ITypeDefOrRef? eventType) : this(new MetadataToken((TableIndex)20, 0u)) { //IL_0004: 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) Name = name; Attributes = attributes; EventType = eventType; } public void SetSemanticMethods(MethodDefinition? addMethod, MethodDefinition? removeMethod, MethodDefinition? fireMethod) { Semantics.Clear(); if (addMethod != null) { Semantics.Add(new MethodSemantics(addMethod, (MethodSemanticsAttributes)8)); } if (removeMethod != null) { Semantics.Add(new MethodSemantics(removeMethod, (MethodSemanticsAttributes)16)); } if (fireMethod != null) { Semantics.Add(new MethodSemantics(fireMethod, (MethodSemanticsAttributes)32)); } } public bool IsAccessibleFromType(TypeDefinition type) { TypeDefinition type2 = type; return Semantics.Any((MethodSemantics s) => s.Method?.IsAccessibleFromType(type2) ?? false); } IMemberDefinition IMemberDescriptor.Resolve() { return this; } public bool IsImportedInModule(ModuleDefinition module) { if (Module == module) { return EventType?.IsImportedInModule(module) ?? false; } return false; } IImportable IImportable.ImportWith(ReferenceImporter importer) { throw new NotSupportedException(); } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } protected virtual Utf8String? GetName() { return null; } protected virtual ITypeDefOrRef? GetEventType() { return null; } protected virtual TypeDefinition? GetDeclaringType() { return null; } protected virtual IList GetSemantics() { return (IList)new MethodSemanticsCollection(this); } public override string ToString() { return FullName; } } public class ExportedType : MetadataMember, IImplementation, IFullNameProvider, INameProvider, IModuleProvider, IHasCustomAttribute, IMetadataMember, IImportable, ITypeDescriptor, IMemberDescriptor, IOwnedCollectionElement { private readonly LazyVariable _name; private readonly LazyVariable _namespace; private readonly LazyVariable _implementation; private IList? _customAttributes; public TypeAttributes Attributes { get; set; } public uint TypeDefId { get; set; } public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public Utf8String? Namespace { get { return _namespace.Value; } set { _namespace.Value = value; } } string? ITypeDescriptor.Namespace => Utf8String.op_Implicit(Namespace); public string FullName => MemberNameGenerator.GetTypeFullName(this); public ModuleDefinition? Module { get; private set; } ModuleDefinition? IOwnedCollectionElement.Owner { get { return Module; } set { Module = value; } } public IImplementation? Implementation { get { return _implementation.Value; } set { _implementation.Value = value; } } public ExportedType? DeclaringType => Implementation as ExportedType; ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; public IResolutionScope? Scope => Module; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } public bool IsValueType => Resolve()?.IsValueType ?? false; protected ExportedType(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _namespace = new LazyVariable((Func)GetNamespace); _implementation = new LazyVariable((Func)GetImplementation); } public ExportedType(IImplementation? implementation, string? ns, string? name) : this(new MetadataToken((TableIndex)39, 1u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Implementation = implementation; Namespace = Utf8String.op_Implicit(ns); Name = Utf8String.op_Implicit(name); } public TypeDefinition? Resolve() { return Module?.MetadataResolver.ResolveType(this); } public bool IsImportedInModule(ModuleDefinition module) { if (Module == module) { return Implementation?.IsImportedInModule(module) ?? false; } return false; } public ExportedType ImportWith(ReferenceImporter importer) { return importer.ImportType(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } IMemberDefinition? IMemberDescriptor.Resolve() { return Resolve(); } public ITypeDefOrRef ToTypeDefOrRef() { return new TypeReference(Module, Scope, Namespace, Name); } public TypeSignature ToTypeSignature() { return new TypeDefOrRefSignature(ToTypeDefOrRef()); } protected virtual Utf8String? GetNamespace() { return null; } protected virtual Utf8String? GetName() { return null; } protected virtual IImplementation? GetImplementation() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } public override string ToString() { return FullName; } } public class FieldDefinition : MetadataMember, IMemberDefinition, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember, IFieldDescriptor, IHasCustomAttribute, IHasConstant, IMemberForwarded, IHasFieldMarshal, IOwnedCollectionElement { private readonly LazyVariable _name; private readonly LazyVariable _signature; private readonly LazyVariable _declaringType; private readonly LazyVariable _constant; private readonly LazyVariable _marshalDescriptor; private readonly LazyVariable _implementationMap; private readonly LazyVariable _fieldRva; private readonly LazyVariable _fieldOffset; private IList? _customAttributes; public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public FieldSignature? Signature { get { return _signature.Value; } set { _signature.Value = value; } } public string FullName => MemberNameGenerator.GetFieldFullName(this); public FieldAttributes Attributes { get; set; } public bool IsPrivateScope { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 0; } set { //IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)(value ? (Attributes & 0xFFF8) : Attributes); } } public bool IsPrivate { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 1; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 1 : 0)); } } public bool IsFamilyAndAssembly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 2; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 2 : 0)); } } public bool IsAssembly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 3; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 3 : 0)); } } public bool IsFamily { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 4; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 4 : 0)); } } public bool IsFamilyOrAssembly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 5; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 5 : 0)); } } public bool IsPublic { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 6; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 6 : 0)); } } public bool IsStatic { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x10) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFFEF) | (value ? 16 : 0)); } } public bool IsInitOnly { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x20) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFFDF) | (value ? 32 : 0)); } } public bool IsLiteral { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x40) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFFBF) | (value ? 64 : 0)); } } public bool IsNotSerialized { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x80) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFF7F) | (value ? 128 : 0)); } } public bool IsSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x200) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFDFF) | (value ? 512 : 0)); } } public bool IsPInvokeImpl { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x2000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xDFFF) | (value ? 8192 : 0)); } } public bool IsRuntimeSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x400) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFBFF) | (value ? 1024 : 0)); } } public bool HasFieldMarshal { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x1000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xEFFF) | (value ? 4096 : 0)); } } public bool HasDefault { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x8000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0x7FFF) | (value ? 32768 : 0)); } } public bool HasFieldRva { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x100) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (FieldAttributes)((Attributes & 0xFEFF) | (value ? 256 : 0)); } } public ModuleDefinition? Module => DeclaringType?.Module; public TypeDefinition? DeclaringType { get { return _declaringType.Value; } private set { _declaringType.Value = value; } } TypeDefinition? IOwnedCollectionElement.Owner { get { return DeclaringType; } set { DeclaringType = value; } } ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } public Constant? Constant { get { return _constant.Value; } set { _constant.Value = value; } } public MarshalDescriptor? MarshalDescriptor { get { return _marshalDescriptor.Value; } set { _marshalDescriptor.Value = value; } } public ImplementationMap? ImplementationMap { get { return _implementationMap.Value; } set { if (value?.MemberForwarded != null) { throw new ArgumentException("Cannot add an implementation map that was already added to another member."); } if (_implementationMap.Value != null) { _implementationMap.Value.MemberForwarded = null; } _implementationMap.Value = value; if (value != null) { value.MemberForwarded = this; } } } public ISegment? FieldRva { get { return _fieldRva.Value; } set { _fieldRva.Value = value; } } public int? FieldOffset { get { return _fieldOffset.Value; } set { _fieldOffset.Value = value; } } protected FieldDefinition(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _signature = new LazyVariable((Func)GetSignature); _declaringType = new LazyVariable((Func)GetDeclaringType); _constant = new LazyVariable((Func)GetConstant); _marshalDescriptor = new LazyVariable((Func)GetMarshalDescriptor); _implementationMap = new LazyVariable((Func)GetImplementationMap); _fieldRva = new LazyVariable((Func)GetFieldRva); _fieldOffset = new LazyVariable((Func)GetFieldOffset); } public FieldDefinition(Utf8String? name, FieldAttributes attributes, FieldSignature? signature) : this(new MetadataToken((TableIndex)4, 0u)) { //IL_0003: 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) Name = name; Attributes = attributes; Signature = signature; } public FieldDefinition(Utf8String name, FieldAttributes attributes, TypeSignature? fieldType) : this(new MetadataToken((TableIndex)4, 0u)) { //IL_0003: 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) Name = name; Attributes = attributes; Signature = ((fieldType != null) ? new FieldSignature(fieldType) : null); } FieldDefinition IFieldDescriptor.Resolve() { return this; } public bool IsImportedInModule(ModuleDefinition module) { if (Module == module) { return Signature?.IsImportedInModule(module) ?? false; } return false; } public IFieldDescriptor ImportWith(ReferenceImporter importer) { return importer.ImportField(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } IMemberDefinition IMemberDescriptor.Resolve() { return this; } public bool IsAccessibleFromType(TypeDefinition type) { TypeDefinition declaringType = DeclaringType; if (declaringType == null || !declaringType.IsAccessibleFromType(type)) { return false; } SignatureComparer signatureComparer = new SignatureComparer(); bool flag = signatureComparer.Equals(declaringType.Module, type.Module); if (!IsPublic && (!flag || !IsAssembly)) { return signatureComparer.Equals(DeclaringType, type); } return true; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } protected virtual Utf8String? GetName() { return null; } protected virtual FieldSignature? GetSignature() { return null; } protected virtual TypeDefinition? GetDeclaringType() { return null; } protected virtual Constant? GetConstant() { return null; } protected virtual MarshalDescriptor? GetMarshalDescriptor() { return null; } protected virtual ImplementationMap? GetImplementationMap() { return null; } protected virtual ISegment? GetFieldRva() { return null; } protected virtual int? GetFieldOffset() { return null; } public override string ToString() { return FullName; } } public class FileReference : MetadataMember, IImplementation, IFullNameProvider, INameProvider, IModuleProvider, IHasCustomAttribute, IMetadataMember, IImportable, IManagedEntryPoint, IOwnedCollectionElement { private readonly LazyVariable _name; private readonly LazyVariable _hashValue; private IList? _customAttributes; public FileAttributes Attributes { get; set; } public bool ContainsMetadata { get { return !ContainsNoMetadata; } set { ContainsNoMetadata = !value; } } public bool ContainsNoMetadata { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 return (int)Attributes == 1; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (FileAttributes)((Attributes & -2) | (value ? 1 : 0)); } } public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public string FullName => Utf8String.op_Implicit(Name ?? MetadataMember.NullName); public ModuleDefinition? Module { get; private set; } ModuleDefinition? IOwnedCollectionElement.Owner { get { return Module; } set { Module = value; } } public byte[]? HashValue { get { return _hashValue.Value; } set { _hashValue.Value = value; } } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected FileReference(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _hashValue = new LazyVariable((Func)GetHashValue); } public FileReference(Utf8String? name, FileAttributes attributes) : this(new MetadataToken((TableIndex)38, 0u)) { //IL_0004: 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) Name = name; Attributes = attributes; } public bool IsImportedInModule(ModuleDefinition module) { return Module == module; } public FileReference ImportWith(ReferenceImporter importer) { return (FileReference)importer.ImportImplementation(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } protected virtual Utf8String? GetName() { return null; } protected virtual byte[]? GetHashValue() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } } public readonly struct GacDirectory { private readonly string _basePath; private readonly string? _prefix; private bool IsPrefixed => !string.IsNullOrEmpty(_prefix); public GacDirectory(string basePath, string? prefix = null) { _basePath = basePath ?? throw new ArgumentNullException("basePath"); _prefix = prefix; } public string? Probe(AssemblyDescriptor assembly) { if (string.IsNullOrEmpty(Utf8String.op_Implicit(assembly.Name))) { return null; } byte[] publicKeyToken = assembly.GetPublicKeyToken(); if (publicKeyToken == null) { throw new ArgumentException("Only signed assemblies can be looked up in the GAC."); } string text = Path.Combine(_basePath, Utf8String.op_Implicit(assembly.Name)); if (Directory.Exists(text)) { string value = string.Join(string.Empty, publicKeyToken.Select((byte x) => x.ToString("x2"))); string text2 = $"{assembly.Version}__{value}"; if (IsPrefixed) { text2 = _prefix + text2; } string text3 = AssemblyResolverBase.ProbeFileFromFilePathWithoutExtension(Path.Combine(text, text2, Utf8String.op_Implicit(assembly.Name))); if (!string.IsNullOrEmpty(text3)) { return text3; } } return null; } public override string ToString() { return _basePath; } } public class GenericParameter : MetadataMember, INameProvider, IHasCustomAttribute, IMetadataMember, IModuleProvider, IOwnedCollectionElement { private readonly LazyVariable _name; private readonly LazyVariable _owner; private IList? _constraints; private IList? _customAttributes; public IHasGenericParameters? Owner { get { return _owner.Value; } private set { _owner.Value = value; } } IHasGenericParameters? IOwnedCollectionElement.Owner { get { return Owner; } set { Owner = value; } } public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public GenericParameterAttributes Attributes { get; set; } public ushort Number { get { if (Owner != null) { return (ushort)Owner.GenericParameters.IndexOf(this); } return 0; } } public ModuleDefinition? Module => Owner?.Module; public IList Constraints { get { if (_constraints == null) { Interlocked.CompareExchange(ref _constraints, GetConstraints(), null); } return _constraints; } } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected GenericParameter(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _owner = new LazyVariable((Func)GetOwner); } public GenericParameter(Utf8String? name) : this(new MetadataToken((TableIndex)42, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Name = name; } public GenericParameter(Utf8String? name, GenericParameterAttributes attributes) : this(new MetadataToken((TableIndex)42, 0u)) { //IL_0004: 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) Name = name; Attributes = attributes; } protected virtual Utf8String? GetName() { return null; } protected virtual IHasGenericParameters? GetOwner() { return null; } protected virtual IList GetConstraints() { return (IList)new OwnedCollection(this); } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } public override string ToString() { return Utf8String.op_Implicit(Name ?? MetadataMember.NullName); } } public class GenericParameterConstraint : MetadataMember, IHasCustomAttribute, IMetadataMember, IModuleProvider, IOwnedCollectionElement { private readonly LazyVariable _owner; private readonly LazyVariable _constraint; private IList? _customAttributes; public GenericParameter? Owner { get { return _owner.Value; } private set { _owner.Value = value; } } GenericParameter? IOwnedCollectionElement.Owner { get { return Owner; } set { Owner = value; } } public ITypeDefOrRef? Constraint { get { return _constraint.Value; } set { _constraint.Value = value; } } public ModuleDefinition? Module => Owner?.Module; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected GenericParameterConstraint(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _owner = new LazyVariable((Func)GetOwner); _constraint = new LazyVariable((Func)GetConstraint); } public GenericParameterConstraint(ITypeDefOrRef? constraint) : this(new MetadataToken((TableIndex)44, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Constraint = constraint; } protected virtual GenericParameter? GetOwner() { return null; } protected virtual ITypeDefOrRef? GetConstraint() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } } public static class HasCustomAttributeExtensions { public static bool HasCustomAttribute(this IHasCustomAttribute self, string? ns, string? name) { for (int i = 0; i < self.CustomAttributes.Count; i++) { ITypeDefOrRef typeDefOrRef = self.CustomAttributes[i].Constructor?.DeclaringType; if (typeDefOrRef != null && typeDefOrRef.IsTypeOf(ns, name)) { return true; } } return false; } public static IEnumerable FindCustomAttributes(this IHasCustomAttribute self, string? ns, string? name) { for (int i = 0; i < self.CustomAttributes.Count; i++) { CustomAttribute customAttribute = self.CustomAttributes[i]; ITypeDefOrRef typeDefOrRef = customAttribute.Constructor?.DeclaringType; if (typeDefOrRef != null && typeDefOrRef.IsTypeOf(ns, name)) { yield return customAttribute; } } } public static bool IsCompilerGenerated(this IHasCustomAttribute self) { return self.HasCustomAttribute("System.Runtime.CompilerServices", "CompilerGeneratedAttribute"); } } public interface IAssemblyResolver { AssemblyDefinition? Resolve(AssemblyDescriptor assembly); void AddToCache(AssemblyDescriptor descriptor, AssemblyDefinition definition); bool RemoveFromCache(AssemblyDescriptor descriptor); bool HasCached(AssemblyDescriptor descriptor); void ClearCache(); } public interface ICustomAttributeType : IMethodDefOrRef, IMethodDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember, IHasCustomAttribute { } public interface IFieldDescriptor : IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember { new Utf8String? Name { get; } FieldSignature? Signature { get; } new FieldDefinition? Resolve(); } public interface IFullNameProvider : INameProvider { string FullName { get; } } public interface IHasConstant : IMetadataMember, INameProvider, IModuleProvider { Constant? Constant { get; set; } } public interface IHasCustomAttribute : IMetadataMember { IList CustomAttributes { get; } } public interface IHasFieldMarshal : IMetadataMember, INameProvider, IModuleProvider { MarshalDescriptor? MarshalDescriptor { get; set; } } public interface IHasGenericParameters : IMetadataMember, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable { IList GenericParameters { get; } } public interface IHasSecurityDeclaration : IMetadataMember { IList SecurityDeclarations { get; } } public interface IHasSemantics : IMetadataMember, IMemberDefinition, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable { IList Semantics { get; } } public interface IImplementation : IFullNameProvider, INameProvider, IModuleProvider, IHasCustomAttribute, IMetadataMember, IImportable { } public interface IImportable { bool IsImportedInModule(ModuleDefinition module); IImportable ImportWith(ReferenceImporter importer); } public interface IManagedEntryPoint : IMetadataMember { } public interface IMemberDefinition : IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember { new TypeDefinition? DeclaringType { get; } bool IsAccessibleFromType(TypeDefinition type); } public interface IMemberDescriptor : IFullNameProvider, INameProvider, IModuleProvider, IImportable { ITypeDescriptor? DeclaringType { get; } IMemberDefinition? Resolve(); } public interface IMemberForwarded : IMetadataMember, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable { ImplementationMap? ImplementationMap { get; set; } } public interface IMemberRefParent : IMetadataMember, INameProvider, IModuleProvider { } public interface IMetadataMember { MetadataToken MetadataToken { get; } } public interface IMetadataResolver { IAssemblyResolver AssemblyResolver { get; } TypeDefinition? ResolveType(ITypeDescriptor? type); MethodDefinition? ResolveMethod(IMethodDescriptor? method); FieldDefinition? ResolveField(IFieldDescriptor? field); } public interface IMethodDefOrRef : IMethodDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember, IHasCustomAttribute { new ITypeDefOrRef? DeclaringType { get; } } public interface IMethodDescriptor : IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember { new Utf8String? Name { get; } MethodSignature? Signature { get; } new MethodDefinition? Resolve(); } public interface IModuleProvider { ModuleDefinition? Module { get; } } public class ImplementationMap : MetadataMember, IFullNameProvider, INameProvider { private readonly LazyVariable _name; private readonly LazyVariable _scope; private readonly LazyVariable _memberForwarded; public ImplementationMapAttributes Attributes { get; set; } public IMemberForwarded? MemberForwarded { get { return _memberForwarded.Value; } internal set { _memberForwarded.Value = value; } } public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public string FullName { get { if (Scope != null) { return $"{Scope.Name}!{Name}"; } return Utf8String.op_Implicit(Name ?? MetadataMember.NullName); } } public ModuleReference? Scope { get { return _scope.Value; } set { _scope.Value = value; } } protected ImplementationMap(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _scope = new LazyVariable((Func)GetScope); _memberForwarded = new LazyVariable((Func)GetMemberForwarded); } public ImplementationMap(ModuleReference? scope, Utf8String? name, ImplementationMapAttributes attributes) : this(new MetadataToken((TableIndex)28, 0u)) { //IL_0004: 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) Scope = scope; Name = name; Attributes = attributes; } protected virtual Utf8String? GetName() { return null; } protected virtual ModuleReference? GetScope() { return null; } protected virtual IMemberForwarded? GetMemberForwarded() { return null; } } public interface INameProvider { string? Name { get; } } public class InterfaceImplementation : MetadataMember, IModuleProvider, IOwnedCollectionElement, IHasCustomAttribute, IMetadataMember { private readonly LazyVariable _class; private readonly LazyVariable _interface; private IList? _customAttributes; public TypeDefinition? Class { get { return _class.Value; } private set { _class.Value = value; } } TypeDefinition? IOwnedCollectionElement.Owner { get { return Class; } set { Class = value; } } public ITypeDefOrRef? Interface { get { return _interface.Value; } set { _interface.Value = value; } } public ModuleDefinition? Module => Class?.Module; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected InterfaceImplementation(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _class = new LazyVariable((Func)GetClass); _interface = new LazyVariable((Func)GetInterface); } public InterfaceImplementation(ITypeDefOrRef? interfaceType) : this(new MetadataToken((TableIndex)9, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Interface = interfaceType; } protected virtual TypeDefinition? GetClass() { return null; } protected virtual ITypeDefOrRef? GetInterface() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } } public sealed class InvalidTypeDefOrRef : MetadataMember, ITypeDefOrRef, ITypeDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMemberRefParent, IMetadataMember, IHasCustomAttribute { private static readonly IDictionary Instances = new Dictionary(); private readonly Utf8String _name; public InvalidTypeSignatureError Error { get; } Utf8String ITypeDefOrRef.Name => _name; string INameProvider.Name => Utf8String.op_Implicit(_name); Utf8String? ITypeDefOrRef.Namespace => null; string? ITypeDescriptor.Namespace => null; string IFullNameProvider.FullName => ((INameProvider)this).Name; ModuleDefinition? IModuleProvider.Module => null; IResolutionScope? ITypeDescriptor.Scope => null; bool ITypeDescriptor.IsValueType => false; ITypeDescriptor? IMemberDescriptor.DeclaringType => null; ITypeDefOrRef? ITypeDefOrRef.DeclaringType => null; public IList CustomAttributes { get; } = new List(); private InvalidTypeDefOrRef(InvalidTypeSignatureError error) : base(new MetadataToken((TableIndex)1, 0u)) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) Error = error; _name = Utf8String.op_Implicit($"<<<{Error}>>>".ToUpperInvariant()); } public static InvalidTypeDefOrRef Get(InvalidTypeSignatureError error) { if (!Instances.TryGetValue(error, out InvalidTypeDefOrRef value)) { value = new InvalidTypeDefOrRef(error); Instances.Add(error, value); } return value; } public bool IsImportedInModule(ModuleDefinition module) { return false; } ITypeDefOrRef ITypeDefOrRef.ImportWith(ReferenceImporter importer) { throw new InvalidOperationException(); } IImportable IImportable.ImportWith(ReferenceImporter importer) { throw new InvalidOperationException(); } IMemberDefinition? IMemberDescriptor.Resolve() { return null; } TypeDefinition? ITypeDescriptor.Resolve() { return null; } ITypeDefOrRef ITypeDescriptor.ToTypeDefOrRef() { return this; } TypeSignature ITypeDescriptor.ToTypeSignature() { throw new InvalidOperationException(); } TypeSignature ITypeDefOrRef.ToTypeSignature(bool isValueType) { throw new InvalidOperationException(); } public override string ToString() { return ((INameProvider)this).Name; } } public enum InvalidTypeSignatureError { BlobTooShort, InvalidCodedIndex, MetadataLoop, IllegalTypeSpec, InvalidFieldOrProptype } public interface IResolutionScope : IMetadataMember, INameProvider, IModuleProvider, IImportable { AssemblyDescriptor? GetAssembly(); } public interface ITypeDefOrRef : ITypeDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMemberRefParent, IMetadataMember, IHasCustomAttribute { new Utf8String? Name { get; } new Utf8String? Namespace { get; } new ITypeDefOrRef? DeclaringType { get; } new ITypeDefOrRef ImportWith(ReferenceImporter importer); TypeSignature ToTypeSignature(bool isValueType); } public interface ITypeDescriptor : IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable { string? Namespace { get; } IResolutionScope? Scope { get; } bool IsValueType { get; } new TypeDefinition? Resolve(); ITypeDefOrRef ToTypeDefOrRef(); TypeSignature ToTypeSignature(); } public static class KnownCorLibs { public static readonly ICollection KnownCorLibReferences; public static readonly ICollection KnownCorLibNames; public static readonly AssemblyReference MsCorLib_v2_0_0_0; public static readonly AssemblyReference MsCorLib_v4_0_0_0; public static readonly AssemblyReference SystemPrivateCoreLib_v4_0_0_0; public static readonly AssemblyReference SystemPrivateCoreLib_v5_0_0_0; public static readonly AssemblyReference SystemPrivateCoreLib_v6_0_0_0; public static readonly AssemblyReference SystemPrivateCoreLib_v7_0_0_0; public static readonly AssemblyReference SystemRuntime_v4_0_20_0; public static readonly AssemblyReference SystemRuntime_v4_1_0_0; public static readonly AssemblyReference SystemRuntime_v4_2_1_0; public static readonly AssemblyReference SystemRuntime_v4_2_2_0; public static readonly AssemblyReference SystemRuntime_v5_0_0_0; public static readonly AssemblyReference SystemRuntime_v6_0_0_0; public static readonly AssemblyReference SystemRuntime_v7_0_0_0; public static readonly AssemblyReference NetStandard_v2_0_0_0; public static readonly AssemblyReference NetStandard_v2_1_0_0; static KnownCorLibs() { MsCorLib_v2_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("mscorlib"), new Version(2, 0, 0, 0), publicKey: false, new byte[8] { 183, 122, 92, 86, 25, 52, 224, 137 }); MsCorLib_v4_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("mscorlib"), new Version(4, 0, 0, 0), publicKey: false, new byte[8] { 183, 122, 92, 86, 25, 52, 224, 137 }); SystemPrivateCoreLib_v4_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("System.Private.CoreLib"), new Version(4, 0, 0, 0), publicKey: false, new byte[8] { 124, 236, 133, 215, 190, 167, 121, 142 }); SystemPrivateCoreLib_v5_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("System.Private.CoreLib"), new Version(5, 0, 0, 0), publicKey: false, new byte[8] { 124, 236, 133, 215, 190, 167, 121, 142 }); SystemPrivateCoreLib_v6_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("System.Private.CoreLib"), new Version(6, 0, 0, 0), publicKey: false, new byte[8] { 124, 236, 133, 215, 190, 167, 121, 142 }); SystemPrivateCoreLib_v7_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("System.Private.CoreLib"), new Version(7, 0, 0, 0), publicKey: false, new byte[8] { 124, 236, 133, 215, 190, 167, 121, 142 }); SystemRuntime_v4_0_20_0 = new AssemblyReference(Utf8String.op_Implicit("System.Runtime"), new Version(4, 0, 20, 0), publicKey: false, new byte[8] { 176, 63, 95, 127, 17, 213, 10, 58 }); SystemRuntime_v4_1_0_0 = new AssemblyReference(Utf8String.op_Implicit("System.Runtime"), new Version(4, 1, 0, 0), publicKey: false, new byte[8] { 176, 63, 95, 127, 17, 213, 10, 58 }); SystemRuntime_v4_2_1_0 = new AssemblyReference(Utf8String.op_Implicit("System.Runtime"), new Version(4, 2, 1, 0), publicKey: false, new byte[8] { 176, 63, 95, 127, 17, 213, 10, 58 }); SystemRuntime_v4_2_2_0 = new AssemblyReference(Utf8String.op_Implicit("System.Runtime"), new Version(4, 2, 2, 0), publicKey: false, new byte[8] { 176, 63, 95, 127, 17, 213, 10, 58 }); SystemRuntime_v5_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("System.Runtime"), new Version(5, 0, 0, 0), publicKey: false, new byte[8] { 176, 63, 95, 127, 17, 213, 10, 58 }); SystemRuntime_v6_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("System.Runtime"), new Version(6, 0, 0, 0), publicKey: false, new byte[8] { 176, 63, 95, 127, 17, 213, 10, 58 }); SystemRuntime_v7_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("System.Runtime"), new Version(7, 0, 0, 0), publicKey: false, new byte[8] { 176, 63, 95, 127, 17, 213, 10, 58 }); NetStandard_v2_0_0_0 = new AssemblyReference(Utf8String.op_Implicit("netstandard"), new Version(2, 0, 0, 0), publicKey: false, new byte[8] { 204, 123, 19, 255, 205, 45, 221, 81 }); NetStandard_v2_1_0_0 = new AssemblyReference(Utf8String.op_Implicit("netstandard"), new Version(2, 1, 0, 0), publicKey: false, new byte[8] { 204, 123, 19, 255, 205, 45, 221, 81 }); KnownCorLibReferences = new HashSet(new SignatureComparer()) { NetStandard_v2_0_0_0, NetStandard_v2_1_0_0, MsCorLib_v2_0_0_0, MsCorLib_v4_0_0_0, SystemRuntime_v4_0_20_0, SystemRuntime_v4_1_0_0, SystemRuntime_v4_2_1_0, SystemRuntime_v4_2_2_0, SystemRuntime_v5_0_0_0, SystemRuntime_v6_0_0_0, SystemRuntime_v7_0_0_0, SystemPrivateCoreLib_v4_0_0_0, SystemPrivateCoreLib_v5_0_0_0, SystemPrivateCoreLib_v6_0_0_0, SystemPrivateCoreLib_v7_0_0_0 }; KnownCorLibNames = new HashSet(KnownCorLibReferences.Select((AssemblyReference r) => r.Name.Value)); } } public static class KnownRuntimeNames { public const string NetCoreApp = "Microsoft.NETCore.App"; public const string WindowsDesktopApp = "Microsoft.WindowsDesktop.App"; } public static class KnownRuntimeVersions { public const string Ecma2002 = "Standard CLI 2002"; public const string Ecma2005 = "Standard CLI 2005"; public const string Clr10 = "v1.0.3705"; public const string Clr11 = "v1.1.4322"; public const string Clr20 = "v2.0.50727"; public const string Clr40 = "v4.0.30319"; } public class ManifestResource : MetadataMember, INameProvider, IHasCustomAttribute, IMetadataMember, IOwnedCollectionElement { private readonly LazyVariable _name; private readonly LazyVariable _implementation; private readonly LazyVariable _embeddedData; private IList? _customAttributes; public uint Offset { get; set; } public ManifestResourceAttributes Attributes { get; set; } public bool IsPublic { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 return (int)Attributes == 1; } set { Attributes = (ManifestResourceAttributes)(value ? 1 : 2); } } public bool IsPrivate { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 return (int)Attributes == 2; } set { Attributes = (ManifestResourceAttributes)((!value) ? 1 : 2); } } public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public IImplementation? Implementation { get { return _implementation.Value; } set { _implementation.Value = value; } } public bool IsEmbedded => Implementation == null; public ISegment? EmbeddedDataSegment { get { return _embeddedData.Value; } set { _embeddedData.Value = value; } } public ModuleDefinition? Module { get; private set; } ModuleDefinition? IOwnedCollectionElement.Owner { get { return Module; } set { Module = value; } } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected ManifestResource(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _implementation = new LazyVariable((Func)GetImplementation); _embeddedData = new LazyVariable((Func)GetEmbeddedDataSegment); } public ManifestResource(Utf8String? name, ManifestResourceAttributes attributes, IImplementation? implementation, uint offset) : this(new MetadataToken((TableIndex)40, 0u)) { //IL_0004: 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) Name = name; Attributes = attributes; Implementation = implementation; Offset = offset; } public ManifestResource(Utf8String? name, ManifestResourceAttributes attributes, ISegment? data) : this(new MetadataToken((TableIndex)40, 0u)) { //IL_0004: 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) Name = name; Attributes = attributes; EmbeddedDataSegment = data; } public byte[]? GetData() { ISegment? embeddedDataSegment = EmbeddedDataSegment; IReadableSegment val = (IReadableSegment)(object)((embeddedDataSegment is IReadableSegment) ? embeddedDataSegment : null); if (val == null) { return null; } return Extensions.ToArray(val); } [Obsolete("Use TryGetReader instead.")] public BinaryStreamReader? GetReader() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) ISegment? embeddedDataSegment = EmbeddedDataSegment; IReadableSegment val = (IReadableSegment)(object)((embeddedDataSegment is IReadableSegment) ? embeddedDataSegment : null); if (val == null) { return null; } return Extensions.CreateReader(val); } public bool TryGetReader(out BinaryStreamReader reader) { //IL_001e: 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_0016: Unknown result type (might be due to invalid IL or missing references) ISegment? embeddedDataSegment = EmbeddedDataSegment; IReadableSegment val = (IReadableSegment)(object)((embeddedDataSegment is IReadableSegment) ? embeddedDataSegment : null); if (val != null) { reader = Extensions.CreateReader(val); return true; } reader = default(BinaryStreamReader); return false; } protected virtual Utf8String? GetName() { return null; } protected virtual IImplementation? GetImplementation() { return null; } protected virtual ISegment? GetEmbeddedDataSegment() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } public override string ToString() { return Utf8String.op_Implicit(Name ?? MetadataMember.NullName); } } public sealed class MemberNameGenerator : ITypeSignatureVisitor { [ThreadStatic] private static StringBuilder? _builder; private static MemberNameGenerator Instance { get; } = new MemberNameGenerator(); private MemberNameGenerator() { } private static StringBuilder GetBuilder() { if (_builder == null) { _builder = new StringBuilder(); } _builder.Clear(); return _builder; } public static string GetTypeFullName(ITypeDescriptor type) { return AppendTypeFullName(GetBuilder(), type).ToString(); } public static string GetFieldFullName(IFieldDescriptor descriptor) { StringBuilder builder = GetBuilder(); AppendTypeFullName(builder, descriptor.Signature?.FieldType); builder.Append(' '); AppendMemberDeclaringType(builder, descriptor.DeclaringType); return builder.Append(Utf8String.op_Implicit(descriptor.Name ?? MetadataMember.NullName)).ToString(); } public static string GetMethodFullName(MemberReference reference) { StringBuilder builder = GetBuilder(); MethodSignature methodSignature = reference.Signature as MethodSignature; AppendTypeFullName(builder, methodSignature?.ReturnType); builder.Append(' '); AppendMemberDeclaringType(builder, reference.DeclaringType); builder.Append(Utf8String.op_Implicit(reference.Name ?? MetadataMember.NullName)); AppendTypeArgumentPlaceholders(builder, methodSignature); builder.Append('('); AppendSignatureParameterTypes(builder, methodSignature); builder.Append(')'); return builder.ToString(); } public static string GetMethodFullName(MethodDefinition definition) { StringBuilder builder = GetBuilder(); MethodSignature signature = definition.Signature; AppendTypeFullName(builder, signature?.ReturnType); builder.Append(' '); AppendMemberDeclaringType(builder, definition.DeclaringType); builder.Append(Utf8String.op_Implicit(definition.Name ?? MetadataMember.NullName)); AppendTypeParameters(builder, definition.GenericParameters); builder.Append('('); AppendSignatureParameterTypes(builder, signature); builder.Append(')'); return builder.ToString(); } public static string GetMethodFullName(MethodSpecification specification) { StringBuilder builder = GetBuilder(); MethodSignature methodSignature = specification.Method?.Signature; AppendTypeFullName(builder, methodSignature?.ReturnType); builder.Append(' '); AppendMemberDeclaringType(builder, specification.DeclaringType); builder.Append(Utf8String.op_Implicit(specification.Name)); AppendTypeParameters(builder, specification.Signature?.TypeArguments ?? Array.Empty()); builder.Append('('); AppendSignatureParameterTypes(builder, methodSignature); builder.Append(')'); return builder.ToString(); } public static string GetPropertyFullName(PropertyDefinition definition) { StringBuilder builder = GetBuilder(); PropertySignature signature = definition.Signature; AppendTypeFullName(builder, signature?.ReturnType); builder.Append(' '); AppendMemberDeclaringType(builder, definition.DeclaringType); builder.Append(Utf8String.op_Implicit(definition.Name ?? MetadataMember.NullName)); if (signature != null && signature.ParameterTypes.Count > 0) { builder.Append('['); AppendSignatureParameterTypes(builder, signature); builder.Append(']'); } return builder.ToString(); } public static string GetEventFullName(EventDefinition definition) { StringBuilder builder = GetBuilder(); AppendTypeFullName(builder, definition.EventType); builder.Append(' '); AppendMemberDeclaringType(builder, definition.DeclaringType); builder.Append(Utf8String.op_Implicit(definition.Name)); return builder.ToString(); } private static StringBuilder AppendMemberDeclaringType(StringBuilder state, ITypeDescriptor? declaringType) { if (declaringType != null) { AppendTypeFullName(state, declaringType); state.Append("::"); } return state; } private static StringBuilder AppendSignatureParameterTypes(StringBuilder state, MethodSignatureBase? signature) { if (signature == null) { return state; } for (int i = 0; i < signature.ParameterTypes.Count; i++) { signature.ParameterTypes[i].AcceptVisitor(Instance, state); if (i < signature.ParameterTypes.Count - 1) { state.Append(", "); } } if (signature.IsSentinel) { state.Append("..."); } return state; } private static StringBuilder AppendTypeParameters(StringBuilder state, IList typeArguments) { if (typeArguments.Count > 0) { state.Append('<'); AppendCommaSeparatedCollection(state, typeArguments, delegate(StringBuilder s, GenericParameter t) { s.Append(Utf8String.op_Implicit(t.Name)); }); state.Append('>'); } return state; } private static StringBuilder AppendTypeParameters(StringBuilder state, IList typeArguments) { if (typeArguments.Count > 0) { state.Append('<'); AppendCommaSeparatedCollection(state, typeArguments, delegate(StringBuilder s, TypeSignature t) { t.AcceptVisitor(Instance, s); }); state.Append('>'); } return state; } private static StringBuilder AppendTypeFullName(StringBuilder state, ITypeDescriptor? type) { if (!(type is TypeSignature typeSignature)) { if (!(type is ITypeDefOrRef type2)) { if (type == null) { return state.Append("<>"); } throw new ArgumentOutOfRangeException("type"); } return AppendTypeFullName(state, type2); } return typeSignature.AcceptVisitor(Instance, state); } private static StringBuilder AppendTypeFullName(StringBuilder state, ITypeDefOrRef? type) { if (type == null) { return state.Append("<>"); } if (type is TypeSpecification typeSpecification) { return AppendTypeFullName(state, typeSpecification.Signature); } ITypeDefOrRef declaringType = type.DeclaringType; if (declaringType != null) { AppendTypeFullName(state, declaringType); state.Append('+'); } else if (!string.IsNullOrEmpty(Utf8String.op_Implicit(type.Namespace))) { state.Append(Utf8String.op_Implicit(type.Namespace)); state.Append('.'); } return state.Append(Utf8String.op_Implicit(type.Name ?? MetadataMember.NullName)); } private static StringBuilder AppendTypeArgumentPlaceholders(StringBuilder state, MethodSignature? signature) { if (signature != null && signature.GenericParameterCount > 0) { state.Append('<'); for (int i = 0; i < signature.GenericParameterCount; i++) { state.Append('?'); if (i < signature.GenericParameterCount - 1) { state.Append(", "); } } state.Append('>'); } return state; } private static StringBuilder AppendMethodSignature(StringBuilder state, MethodSignature signature) { if (signature.HasThis) { state.Append("instance "); } signature.ReturnType.AcceptVisitor(Instance, state); state.Append(" *"); AppendTypeArgumentPlaceholders(state, signature); state.Append('('); AppendSignatureParameterTypes(state, signature); return state.Append(')'); } private static StringBuilder AppendCommaSeparatedCollection(StringBuilder state, IList collection, Action action) { for (int i = 0; i < collection.Count; i++) { action(state, collection[i]); if (i < collection.Count - 1) { state.Append(", "); } } return state; } StringBuilder ITypeSignatureVisitor.VisitArrayType(ArrayTypeSignature signature, StringBuilder state) { signature.BaseType.AcceptVisitor(this, state); state.Append('['); AppendCommaSeparatedCollection(state, signature.Dimensions, delegate(StringBuilder s, ArrayDimension d) { if (d.LowerBound.HasValue) { if (d.Size.HasValue) { AppendDimensionBound(s, d.LowerBound.Value, d.Size.Value); } else { s.Append(d.LowerBound.Value).Append("..."); } } if (d.Size.HasValue) { AppendDimensionBound(s, 0, d.Size.Value); } }); return state.Append(']'); static void AppendDimensionBound(StringBuilder state, int low, int size) { state.Append(low).Append("...").Append(low + size - 1); } } StringBuilder ITypeSignatureVisitor.VisitBoxedType(BoxedTypeSignature signature, StringBuilder state) { return signature.BaseType.AcceptVisitor(this, state); } StringBuilder ITypeSignatureVisitor.VisitByReferenceType(ByReferenceTypeSignature signature, StringBuilder state) { return signature.BaseType.AcceptVisitor(this, state).Append('&'); } StringBuilder ITypeSignatureVisitor.VisitCorLibType(CorLibTypeSignature signature, StringBuilder state) { return state.Append("System.").Append(signature.Name); } StringBuilder ITypeSignatureVisitor.VisitCustomModifierType(CustomModifierTypeSignature signature, StringBuilder state) { signature.BaseType.AcceptVisitor(this, state); state.Append(signature.IsRequired ? " modreq(" : " modopt("); AppendTypeFullName(state, signature.ModifierType); return state.Append(')'); } StringBuilder ITypeSignatureVisitor.VisitGenericInstanceType(GenericInstanceTypeSignature signature, StringBuilder state) { AppendTypeFullName(state, signature.GenericType); return AppendTypeParameters(state, signature.TypeArguments); } StringBuilder ITypeSignatureVisitor.VisitGenericParameter(GenericParameterSignature signature, StringBuilder state) { state.Append(signature.ParameterType switch { GenericParameterType.Type => "!", GenericParameterType.Method => "!!", _ => throw new ArgumentOutOfRangeException(), }); return state.Append(signature.Index); } StringBuilder ITypeSignatureVisitor.VisitPinnedType(PinnedTypeSignature signature, StringBuilder state) { return signature.BaseType.AcceptVisitor(this, state); } StringBuilder ITypeSignatureVisitor.VisitPointerType(PointerTypeSignature signature, StringBuilder state) { return signature.BaseType.AcceptVisitor(this, state).Append('*'); } StringBuilder ITypeSignatureVisitor.VisitSentinelType(SentinelTypeSignature signature, StringBuilder state) { return state.Append("<<>>"); } StringBuilder ITypeSignatureVisitor.VisitSzArrayType(SzArrayTypeSignature signature, StringBuilder state) { return signature.BaseType.AcceptVisitor(this, state).Append("[]"); } StringBuilder ITypeSignatureVisitor.VisitTypeDefOrRef(TypeDefOrRefSignature signature, StringBuilder state) { return AppendTypeFullName(state, signature.Type); } StringBuilder ITypeSignatureVisitor.VisitFunctionPointerType(FunctionPointerTypeSignature signature, StringBuilder state) { state.Append("method "); return AppendMethodSignature(state, signature.Signature); } } public class MemberReference : MetadataMember, ICustomAttributeType, IMethodDefOrRef, IMethodDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember, IHasCustomAttribute, IFieldDescriptor { private readonly LazyVariable _parent; private readonly LazyVariable _name; private readonly LazyVariable _signature; private IList? _customAttributes; public IMemberRefParent? Parent { get { return _parent.Value; } set { _parent.Value = value; } } public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public CallingConventionSignature? Signature { get { return _signature.Value; } set { _signature.Value = value; } } MethodSignature? IMethodDescriptor.Signature => Signature as MethodSignature; FieldSignature? IFieldDescriptor.Signature => Signature as FieldSignature; [MemberNotNullWhen(true, "Signature")] public bool IsField { [MemberNotNullWhen(true, "Signature")] get { return Signature is FieldSignature; } } [MemberNotNullWhen(true, "Signature")] public bool IsMethod { [MemberNotNullWhen(true, "Signature")] get { return Signature is MethodSignature; } } public string FullName { get { if (IsField) { return MemberNameGenerator.GetFieldFullName(this); } if (IsMethod) { return MemberNameGenerator.GetMethodFullName(this); } return Utf8String.op_Implicit(Name ?? MetadataMember.NullName); } } public ModuleDefinition? Module => Parent?.Module; public ITypeDefOrRef? DeclaringType { get { IMemberRefParent parent = Parent; if (!(parent is ITypeDefOrRef result)) { if (parent is MethodDefinition methodDefinition) { return methodDefinition.DeclaringType; } return null; } return result; } } ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected MemberReference(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _parent = new LazyVariable((Func)GetParent); _name = new LazyVariable((Func)GetName); _signature = new LazyVariable((Func)GetSignature); } public MemberReference(IMemberRefParent? parent, Utf8String? name, MemberSignature? signature) : this(new MetadataToken((TableIndex)10, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Parent = parent; Name = name; Signature = signature; } public IMemberDefinition? Resolve() { if (IsMethod) { return ((IMethodDescriptor)this).Resolve(); } if (IsField) { return ((IFieldDescriptor)this).Resolve(); } throw new ArgumentOutOfRangeException(); } public bool IsImportedInModule(ModuleDefinition module) { if (Module == module) { return Signature?.IsImportedInModule(module) ?? false; } return false; } public MemberReference ImportWith(ReferenceImporter importer) { if (!IsMethod) { return (MemberReference)importer.ImportField(this); } return (MemberReference)importer.ImportMethod(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } FieldDefinition? IFieldDescriptor.Resolve() { if (!IsField) { throw new InvalidOperationException("Member reference must reference a field."); } return Module?.MetadataResolver.ResolveField(this); } MethodDefinition? IMethodDescriptor.Resolve() { if (!IsMethod) { throw new InvalidOperationException("Member reference must reference a method."); } return Module?.MetadataResolver.ResolveMethod(this); } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } protected virtual IMemberRefParent? GetParent() { return null; } protected virtual Utf8String? GetName() { return null; } protected virtual CallingConventionSignature? GetSignature() { return null; } public override string ToString() { return FullName; } } public abstract class MetadataMember : IMetadataMember { internal static readonly Utf8String NullName = Utf8String.op_Implicit("<<>>"); public MetadataToken MetadataToken { get; internal set; } protected MetadataMember(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) MetadataToken = token; } } public class MethodDefinition : MetadataMember, IMemberDefinition, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember, IOwnedCollectionElement, IMemberRefParent, ICustomAttributeType, IMethodDefOrRef, IMethodDescriptor, IHasCustomAttribute, IHasGenericParameters, IMemberForwarded, IHasSecurityDeclaration, IManagedEntryPoint { private readonly LazyVariable _name; private readonly LazyVariable _declaringType; private readonly LazyVariable _signature; private readonly LazyVariable _methodBody; private readonly LazyVariable _implementationMap; private readonly LazyVariable _semantics; private readonly LazyVariable _exportInfo; private IList? _parameterDefinitions; private ParameterCollection? _parameters; private IList? _customAttributes; private IList? _securityDeclarations; private IList? _genericParameters; public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public MethodSignature? Signature { get { return _signature.Value; } set { _signature.Value = value; } } public string FullName => MemberNameGenerator.GetMethodFullName(this); public MethodAttributes Attributes { get; set; } public bool IsCompilerControlled { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 0; } set { //IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)(value ? (Attributes & 0xFFF8) : Attributes); } } public bool IsPrivate { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 1; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFF8) | (value ? 1 : 0)); } } public bool IsFamilyAndAssembly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 2; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFF8) | (value ? 2 : 0)); } } public bool IsAssembly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 3; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFF8) | (value ? 3 : 0)); } } public bool IsFamily { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 4; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFF8) | (value ? 4 : 0)); } } public bool IsFamilyOrAssembly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 5; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFF8) | (value ? 5 : 0)); } } public bool IsPublic { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 6; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFF8) | (value ? 6 : 0)); } } public bool IsUnmanagedExport { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 8) > 0; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFF7) | (value ? 8 : 0)); } } public bool IsStatic { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x10) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFEF) | (value ? 16 : 0)); } } public bool IsFinal { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x20) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFDF) | (value ? 32 : 0)); } } public bool IsVirtual { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x40) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFFBF) | (value ? 64 : 0)); } } public bool IsHideBySig { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x80) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFF7F) | (value ? 128 : 0)); } } public bool IsReuseSlot { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x100) == 0; } set { //IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)(value ? (Attributes & 0xFEFF) : Attributes); } } public bool IsNewSlot { get { //IL_0001: 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_0011: Invalid comparison between Unknown and I4 return (Attributes & 0x100) == 256; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFEFF) | (value ? 256 : 0)); } } public bool CheckAccessOnOverride { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x200) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFDFF) | (value ? 512 : 0)); } } public bool IsAbstract { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x400) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xFBFF) | (value ? 1024 : 0)); } } public bool IsSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x800) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xF7FF) | (value ? 2048 : 0)); } } public bool IsRuntimeSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x1000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xEFFF) | (value ? 4096 : 0)); } } public bool IsPInvokeImpl { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x2000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xDFFF) | (value ? 8192 : 0)); } } public bool HasSecurity { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x4000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0xBFFF) | (value ? 16384 : 0)); } } public bool RequireSecObject { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x8000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (MethodAttributes)((Attributes & 0x7FFF) | (value ? 32768 : 0)); } } public MethodImplAttributes ImplAttributes { get; set; } public bool IsIL { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (ImplAttributes & 3) == 0; } set { //IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)(value ? (ImplAttributes & 0xFFFC) : ImplAttributes); } } public bool IsNative { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (ImplAttributes & 3) == 1; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xFFFC) | (value ? 1 : 0)); } } public bool IsOPTIL { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (ImplAttributes & 3) == 2; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xFFFC) | (value ? 2 : 0)); } } public bool IsRuntime { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (ImplAttributes & 3) == 3; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xFFFC) | (value ? 3 : 0)); } } public bool Managed { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (ImplAttributes & 4) == 0; } set { //IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)(value ? (ImplAttributes & 0xFFFB) : ImplAttributes); } } public bool Unmanaged { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (ImplAttributes & 4) == 4; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xFFFB) | (value ? 4 : 0)); } } public bool IsForwardReference { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (ImplAttributes & 0x10) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xFFEF) | (value ? 16 : 0)); } } public bool IsNoOptimization { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (ImplAttributes & 0x40) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xFFBF) | (value ? 64 : 0)); } } public bool PreserveSignature { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (ImplAttributes & 0x80) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xFF7F) | (value ? 128 : 0)); } } public bool IsInternalCall { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (ImplAttributes & 0x1000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xEFFF) | (value ? 4096 : 0)); } } public bool IsSynchronized { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (ImplAttributes & 0x20) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xFFDF) | (value ? 32 : 0)); } } public bool NoInlining { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (ImplAttributes & 8) > 0; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) ImplAttributes = (MethodImplAttributes)((ImplAttributes & 0xFFF7) | (value ? 8 : 0)); } } public virtual ModuleDefinition? Module => DeclaringType?.Module; public TypeDefinition? DeclaringType { get { return _declaringType.Value; } set { _declaringType.Value = value; } } ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; ITypeDefOrRef? IMethodDefOrRef.DeclaringType => DeclaringType; TypeDefinition? IOwnedCollectionElement.Owner { get { return DeclaringType; } set { DeclaringType = value; } } public IList ParameterDefinitions { get { if (_parameterDefinitions == null) { Interlocked.CompareExchange(ref _parameterDefinitions, GetParameterDefinitions(), null); } return _parameterDefinitions; } } public ParameterCollection Parameters { get { if (_parameters == null) { Interlocked.CompareExchange(ref _parameters, new ParameterCollection(this), null); } return _parameters; } } [MemberNotNullWhen(true, "MethodBody")] public bool HasMethodBody { [MemberNotNullWhen(true, "MethodBody")] get { return MethodBody != null; } } public AsmResolver.DotNet.Code.MethodBody? MethodBody { get { return _methodBody.Value; } set { _methodBody.Value = value; } } public CilMethodBody? CilMethodBody { get { return MethodBody as CilMethodBody; } set { MethodBody = value; } } public NativeMethodBody? NativeMethodBody { get { return MethodBody as NativeMethodBody; } set { MethodBody = value; } } public ImplementationMap? ImplementationMap { get { return _implementationMap.Value; } set { if (value?.MemberForwarded != null) { throw new ArgumentException("Cannot add an implementation map that was already added to another member."); } if (_implementationMap.Value != null) { _implementationMap.Value.MemberForwarded = null; } _implementationMap.Value = value; if (value != null) { value.MemberForwarded = this; } } } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } public IList SecurityDeclarations { get { if (_securityDeclarations == null) { Interlocked.CompareExchange(ref _securityDeclarations, GetSecurityDeclarations(), null); } return _securityDeclarations; } } public IList GenericParameters { get { if (_genericParameters == null) { Interlocked.CompareExchange(ref _genericParameters, GetGenericParameters(), null); } return _genericParameters; } } public MethodSemantics? Semantics { get { return _semantics.Value; } set { _semantics.Value = value; } } public bool IsGetMethod { get { //IL_000e: 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_0016: Invalid comparison between Unknown and I4 if (Semantics != null) { return (Semantics.Attributes & 2) > 0; } return false; } } public bool IsSetMethod { get { //IL_000e: 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_0016: Invalid comparison between Unknown and I4 if (Semantics != null) { return (Semantics.Attributes & 1) > 0; } return false; } } public bool IsAddMethod { get { //IL_000e: 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_0016: Invalid comparison between Unknown and I4 if (Semantics != null) { return (Semantics.Attributes & 8) > 0; } return false; } } public bool IsRemoveMethod { get { //IL_000e: 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_0017: Invalid comparison between Unknown and I4 if (Semantics != null) { return (Semantics.Attributes & 0x10) > 0; } return false; } } public bool IsFireMethod { get { //IL_000e: 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_0017: Invalid comparison between Unknown and I4 if (Semantics != null) { return (Semantics.Attributes & 0x20) > 0; } return false; } } public bool IsConstructor { get { if (IsSpecialName && IsRuntimeSpecialName) { Utf8String? name = Name; string text = ((name != null) ? name.Value : null); return text == ".cctor" || text == ".ctor"; } return false; } } public UnmanagedExportInfo? ExportInfo { get { return _exportInfo.Value; } set { _exportInfo.Value = value; } } protected MethodDefinition(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _declaringType = new LazyVariable((Func)GetDeclaringType); _signature = new LazyVariable((Func)GetSignature); _methodBody = new LazyVariable((Func)GetBody); _implementationMap = new LazyVariable((Func)GetImplementationMap); _semantics = new LazyVariable((Func)GetSemantics); _exportInfo = new LazyVariable((Func)GetExportInfo); } public MethodDefinition(Utf8String? name, MethodAttributes attributes, MethodSignature? signature) : this(new MetadataToken((TableIndex)6, 0u)) { //IL_0003: 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) Name = name; Attributes = attributes; Signature = signature; } MethodDefinition IMethodDescriptor.Resolve() { return this; } public bool IsImportedInModule(ModuleDefinition module) { if (Module == module) { return Signature?.IsImportedInModule(module) ?? false; } return false; } public IMethodDefOrRef ImportWith(ReferenceImporter importer) { return importer.ImportMethod(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } IMemberDefinition IMemberDescriptor.Resolve() { return this; } public bool IsAccessibleFromType(TypeDefinition type) { TypeDefinition declaringType = DeclaringType; if (declaringType == null || !declaringType.IsAccessibleFromType(type)) { return false; } SignatureComparer signatureComparer = new SignatureComparer(); bool flag = signatureComparer.Equals(declaringType.Module, type.Module); if (!IsPublic && (!flag || !IsAssembly)) { return signatureComparer.Equals(DeclaringType, type); } return true; } protected virtual Utf8String? GetName() { return null; } protected virtual TypeDefinition? GetDeclaringType() { return null; } protected virtual MethodSignature? GetSignature() { return null; } protected virtual IList GetParameterDefinitions() { return (IList)new OwnedCollection(this); } protected virtual AsmResolver.DotNet.Code.MethodBody? GetBody() { return null; } protected virtual ImplementationMap? GetImplementationMap() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } protected virtual IList GetSecurityDeclarations() { return (IList)new OwnedCollection((IHasSecurityDeclaration)this); } protected virtual IList GetGenericParameters() { return (IList)new OwnedCollection((IHasGenericParameters)this); } protected virtual MethodSemantics? GetSemantics() { return null; } protected virtual UnmanagedExportInfo? GetExportInfo() { return null; } public override string ToString() { return FullName; } } public static class MethodExtensions { public static MethodSpecification MakeGenericInstanceMethod(this IMethodDefOrRef self, params TypeSignature[] arguments) { if (self.Signature == null) { throw new ArgumentException("Method does not have a signature."); } if (self.Signature.GenericParameterCount != arguments.Length) { throw new ArgumentException($"Expected {self.Signature.GenericParameterCount} type arguments but {arguments.Length} were given."); } return new MethodSpecification(self, new GenericInstanceMethodSignature(arguments)); } } public readonly struct MethodImplementation : IEquatable { public IMethodDefOrRef? Declaration { get; } public IMethodDefOrRef? Body { get; } public MethodImplementation(IMethodDefOrRef? declaration, IMethodDefOrRef? body) { Declaration = declaration; Body = body; } public override string ToString() { return $".override {Declaration} with {Body}"; } public bool Equals(MethodImplementation other) { if (object.Equals(Declaration, other.Declaration)) { return object.Equals(Body, other.Body); } return false; } public override bool Equals(object? obj) { if (obj is MethodImplementation other) { return Equals(other); } return false; } public override int GetHashCode() { return (((Declaration != null) ? Declaration.GetHashCode() : 0) * 397) ^ ((Body != null) ? Body.GetHashCode() : 0); } } public class MethodSemantics : MetadataMember, IOwnedCollectionElement { private readonly LazyVariable _method; private readonly LazyVariable _association; public MethodSemanticsAttributes Attributes { get; set; } public MethodDefinition? Method { get { return _method.Value; } private set { _method.Value = value; } } public IHasSemantics? Association { get { return _association.Value; } private set { _association.Value = value; } } IHasSemantics? IOwnedCollectionElement.Owner { get { return Association; } set { Association = value; } } protected MethodSemantics(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _method = new LazyVariable((Func)GetMethod); _association = new LazyVariable((Func)GetAssociation); } public MethodSemantics(MethodDefinition? method, MethodSemanticsAttributes attributes) : this(new MetadataToken((TableIndex)24, 0u)) { //IL_0004: 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) Method = method ?? throw new ArgumentNullException("method"); Attributes = attributes; } protected virtual MethodDefinition? GetMethod() { return null; } protected virtual IHasSemantics? GetAssociation() { return null; } public override string ToString() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return $"{Attributes} {Method?.FullName}"; } } public class MethodSpecification : MetadataMember, IMethodDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember, IHasCustomAttribute { private readonly LazyVariable _method; private readonly LazyVariable _signature; private IList? _customAttributes; public IMethodDefOrRef? Method { get { return _method.Value; } set { _method.Value = value; } } MethodSignature? IMethodDescriptor.Signature => Method?.Signature; public GenericInstanceMethodSignature? Signature { get { return _signature.Value; } set { _signature.Value = value; } } public Utf8String Name => Method?.Name ?? MetadataMember.NullName; string? INameProvider.Name => Utf8String.op_Implicit(Name); public string FullName => MemberNameGenerator.GetMethodFullName(this); public ModuleDefinition? Module => Method?.Module; public ITypeDefOrRef? DeclaringType => Method?.DeclaringType; ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected MethodSpecification(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _method = new LazyVariable((Func)GetMethod); _signature = new LazyVariable((Func)GetSignature); } public MethodSpecification(IMethodDefOrRef? method, GenericInstanceMethodSignature? signature) : this(new MetadataToken((TableIndex)43, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Method = method; Signature = signature; } public MethodDefinition? Resolve() { return Method?.Resolve(); } public bool IsImportedInModule(ModuleDefinition module) { IMethodDefOrRef? method = Method; if (method != null && method.IsImportedInModule(module)) { return Signature?.IsImportedInModule(module) ?? false; } return false; } public MethodSpecification ImportWith(ReferenceImporter importer) { return importer.ImportMethod(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } IMemberDefinition? IMemberDescriptor.Resolve() { return Resolve(); } protected virtual IMethodDefOrRef? GetMethod() { return null; } protected virtual GenericInstanceMethodSignature? GetSignature() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } public override string ToString() { return FullName; } } public class ModuleDefinition : MetadataMember, IResolutionScope, IMetadataMember, INameProvider, IModuleProvider, IImportable, IHasCustomAttribute, IOwnedCollectionElement { private static MethodInfo? GetHINSTANCEMethod; private readonly LazyVariable _name; private readonly LazyVariable _mvid; private readonly LazyVariable _encId; private readonly LazyVariable _encBaseId; private IList? _topLevelTypes; private IList? _assemblyReferences; private IList? _customAttributes; private readonly LazyVariable _managedEntryPoint; private IList? _moduleReferences; private IList? _fileReferences; private IList? _resources; private IList? _exportedTypes; private TokenAllocator? _tokenAllocator; private readonly LazyVariable _runtimeVersion; private readonly LazyVariable _nativeResources; private IList? _debugData; private ReferenceImporter? _defaultImporter; public string? FilePath { get; internal set; } public virtual IDotNetDirectory? DotNetDirectory { get; } public DotNetRuntimeInfo OriginalTargetRuntime { get; protected set; } public AssemblyDefinition? Assembly { get; internal set; } AssemblyDefinition? IOwnedCollectionElement.Owner { get { return Assembly; } set { Assembly = value; } } ModuleDefinition IModuleProvider.Module => this; public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public ushort Generation { get; set; } public Guid Mvid { get { return _mvid.Value; } set { _mvid.Value = value; } } public Guid EncId { get { return _encId.Value; } set { _encId.Value = value; } } public Guid EncBaseId { get { return _encBaseId.Value; } set { _encBaseId.Value = value; } } public DotNetDirectoryFlags Attributes { get; set; } public TokenAllocator TokenAllocator { get { if (_tokenAllocator == null) { Interlocked.CompareExchange(ref _tokenAllocator, new TokenAllocator(this), null); } return _tokenAllocator; } } public bool IsILOnly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 1) > 0; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (DotNetDirectoryFlags)((Attributes & -2) | (value ? 1 : 0)); } } public bool IsBit32Required { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 2) > 0; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (DotNetDirectoryFlags)((Attributes & -3) | (value ? 2 : 0)); } } public bool IsILLibrary { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 4) > 0; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (DotNetDirectoryFlags)((Attributes & -5) | (value ? 4 : 0)); } } public bool IsStrongNameSigned { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 8) > 0; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (DotNetDirectoryFlags)((Attributes & -9) | (value ? 8 : 0)); } } public bool HasNativeEntryPoint { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x10) > 0; } set { //IL_0002: 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_0012: Unknown result type (might be due to invalid IL or missing references) Attributes = (DotNetDirectoryFlags)((Attributes & -17) | (value ? 16 : 0)); } } public bool TrackDebugData { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x10000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (DotNetDirectoryFlags)((Attributes & -65537) | (value ? 65536 : 0)); } } public bool IsBit32Preferred { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x20000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (DotNetDirectoryFlags)((Attributes & -131073) | (value ? 131072 : 0)); } } public MachineType MachineType { get; set; } = (MachineType)332; public DateTime TimeDateStamp { get; set; } public Characteristics FileCharacteristics { get; set; } = (Characteristics)34; public OptionalHeaderMagic PEKind { get; set; } = (OptionalHeaderMagic)267; public SubSystem SubSystem { get; set; } = (SubSystem)3; public DllCharacteristics DllCharacteristics { get; set; } = (DllCharacteristics)34112; public IList DebugData { get { if (_debugData == null) { Interlocked.CompareExchange(ref _debugData, GetDebugData(), null); } return _debugData; } } public string RuntimeVersion { get { return _runtimeVersion.Value; } set { _runtimeVersion.Value = value; } } public IResourceDirectory? NativeResourceDirectory { get { return _nativeResources.Value; } set { _nativeResources.Value = value; } } public IList TopLevelTypes { get { if (_topLevelTypes == null) { Interlocked.CompareExchange(ref _topLevelTypes, GetTopLevelTypes(), null); } return _topLevelTypes; } } public IList AssemblyReferences { get { if (_assemblyReferences == null) { Interlocked.CompareExchange(ref _assemblyReferences, GetAssemblyReferences(), null); } return _assemblyReferences; } } public IList ModuleReferences { get { if (_moduleReferences == null) { Interlocked.CompareExchange(ref _moduleReferences, GetModuleReferences(), null); } return _moduleReferences; } } public IList FileReferences { get { if (_fileReferences == null) { Interlocked.CompareExchange(ref _fileReferences, GetFileReferences(), null); } return _fileReferences; } } public IList Resources { get { if (_resources == null) { Interlocked.CompareExchange(ref _resources, GetResources(), null); } return _resources; } } public IList ExportedTypes { get { if (_exportedTypes == null) { Interlocked.CompareExchange(ref _exportedTypes, GetExportedTypes(), null); } return _exportedTypes; } } public CorLibTypeFactory CorLibTypeFactory { get; protected set; } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } public IMetadataResolver MetadataResolver { get; set; } public MethodDefinition? ManagedEntryPointMethod { get { return ManagedEntryPoint as MethodDefinition; } set { ManagedEntryPoint = value; } } public IManagedEntryPoint? ManagedEntryPoint { get { return _managedEntryPoint.Value; } set { _managedEntryPoint.Value = value; } } public ReferenceImporter DefaultImporter { get { if (_defaultImporter == null) { Interlocked.CompareExchange(ref _defaultImporter, GetDefaultImporter(), null); } return _defaultImporter; } } public static ModuleDefinition FromBytes(byte[] buffer) { return FromImage(PEImage.FromBytes(buffer)); } public static ModuleDefinition FromBytes(byte[] buffer, ModuleReaderParameters readerParameters) { return FromImage(PEImage.FromBytes(buffer, readerParameters.PEReaderParameters)); } public static ModuleDefinition FromFile(string filePath) { return FromFile(filePath, new ModuleReaderParameters(Path.GetDirectoryName(filePath))); } public static ModuleDefinition FromFile(string filePath, ModuleReaderParameters readerParameters) { return FromImage(PEImage.FromFile(filePath, readerParameters.PEReaderParameters), readerParameters); } public static ModuleDefinition FromFile(IInputFile file) { return FromImage(PEImage.FromFile(file)); } public static ModuleDefinition FromFile(IPEFile file) { return FromImage(PEImage.FromFile(file)); } public static ModuleDefinition FromFile(IPEFile file, ModuleReaderParameters readerParameters) { return FromImage(PEImage.FromFile(file, readerParameters.PEReaderParameters), readerParameters); } public static ModuleDefinition FromModuleBaseAddress(IntPtr hInstance) { return FromModuleBaseAddress(hInstance, new ModuleReaderParameters()); } public static ModuleDefinition FromModuleBaseAddress(IntPtr hInstance, ModuleReaderParameters readerParameters) { return FromImage(PEImage.FromModuleBaseAddress(hInstance, readerParameters.PEReaderParameters), readerParameters); } public static ModuleDefinition FromModuleBaseAddress(IntPtr hInstance, PEMappingMode mode, ModuleReaderParameters readerParameters) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return FromImage(PEImage.FromModuleBaseAddress(hInstance, mode, readerParameters.PEReaderParameters), readerParameters); } public static ModuleDefinition FromModule(Module module) { return FromModule(module, new ModuleReaderParameters()); } public static ModuleDefinition FromModule(Module module, ModuleReaderParameters readerParameters) { //IL_00ad: 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) if ((object)GetHINSTANCEMethod == null) { GetHINSTANCEMethod = typeof(Marshal).GetMethod("GetHINSTANCE", new Type[1] { typeof(Module) }); } IntPtr intPtr = (IntPtr)(GetHINSTANCEMethod?.Invoke(null, new object[1] { module })); if (intPtr == IntPtr.Zero) { throw new NotSupportedException("The current platform does not support getting the base address of an instance of System.Reflection.Module."); } if (intPtr == (IntPtr)(-1)) { throw new NotSupportedException("Provided module does not have a module base address."); } string fullyQualifiedName = module.FullyQualifiedName; PEMappingMode mode = (PEMappingMode)((fullyQualifiedName[0] != '<' || fullyQualifiedName[fullyQualifiedName.Length - 1] != '>') ? 1 : 0); return FromModuleBaseAddress(intPtr, mode, readerParameters); } public static ModuleDefinition FromDataSource(IDataSource dataSource, PEMappingMode mode = 0) { //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_0017: Unknown result type (might be due to invalid IL or missing references) BinaryStreamReader reader = new BinaryStreamReader(dataSource, dataSource.BaseAddress, 0u, (uint)dataSource.Length); return FromReader(in reader, mode); } public static ModuleDefinition FromDataSource(IDataSource dataSource, PEMappingMode mode, ModuleReaderParameters readerParameters) { //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_0017: Unknown result type (might be due to invalid IL or missing references) BinaryStreamReader reader = new BinaryStreamReader(dataSource, dataSource.BaseAddress, 0u, (uint)dataSource.Length); return FromReader(in reader, mode, readerParameters); } public static ModuleDefinition FromReader(in BinaryStreamReader reader, PEMappingMode mode = 0) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return FromFile((IPEFile)(object)PEFile.FromReader(ref reader, mode)); } public static ModuleDefinition FromReader(in BinaryStreamReader reader, PEMappingMode mode, ModuleReaderParameters readerParameters) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return FromImage(PEImage.FromReader(ref reader, mode, readerParameters.PEReaderParameters), readerParameters); } public static ModuleDefinition FromImage(IPEImage peImage) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) ModuleReaderParameters moduleReaderParameters = new ModuleReaderParameters(Path.GetDirectoryName(peImage.FilePath)); SerializedPEImage val = (SerializedPEImage)(object)((peImage is SerializedPEImage) ? peImage : null); moduleReaderParameters.PEReaderParameters = (PEReaderParameters)((val != null) ? ((object)val.ReaderContext.Parameters) : ((object)new PEReaderParameters())); ModuleReaderParameters readerParameters = moduleReaderParameters; return FromImage(peImage, readerParameters); } public static ModuleDefinition FromImage(IPEImage peImage, ModuleReaderParameters readerParameters) { return new SerializedModuleDefinition(peImage, readerParameters); } protected ModuleDefinition(MetadataToken token) : base(token) { //IL_0006: 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_0019: 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_002b: 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) _name = new LazyVariable((Func)GetName); _mvid = new LazyVariable((Func)GetMvid); _encId = new LazyVariable((Func)GetEncId); _encBaseId = new LazyVariable((Func)GetEncBaseId); _managedEntryPoint = new LazyVariable((Func)GetManagedEntryPoint); _runtimeVersion = new LazyVariable((Func)GetRuntimeVersion); _nativeResources = new LazyVariable((Func)GetNativeResources); Attributes = (DotNetDirectoryFlags)1; } public ModuleDefinition(string? name) : this(Utf8String.op_Implicit(name)) { } public ModuleDefinition(Utf8String? name) : this(new MetadataToken((TableIndex)0, 0u)) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) Name = name; CorLibTypeFactory = AsmResolver.DotNet.Signatures.Types.CorLibTypeFactory.CreateMscorlib40TypeFactory(this); AssemblyReferences.Add((AssemblyReference)CorLibTypeFactory.CorLibScope); MetadataResolver = new DefaultMetadataResolver(new DotNetFrameworkAssemblyResolver()); TopLevelTypes.Add(new TypeDefinition(null, TypeDefinition.ModuleTypeName, (TypeAttributes)0)); } public ModuleDefinition(string? name, AssemblyReference corLib) : this(new MetadataToken((TableIndex)0, 0u)) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) Name = Utf8String.op_Implicit(name); corLib = (AssemblyReference)new ReferenceImporter(this).ImportScope(corLib); CorLibTypeFactory = new CorLibTypeFactory(corLib); OriginalTargetRuntime = DetectTargetRuntime(); MetadataResolver = new DefaultMetadataResolver(CreateAssemblyResolver((IFileService)(object)UncachedFileService.Instance)); TopLevelTypes.Add(new TypeDefinition(null, TypeDefinition.ModuleTypeName, (TypeAttributes)0)); } public virtual IMetadataMember LookupMember(MetadataToken token) { throw new InvalidOperationException("Cannot lookup members by tokens from a non-serialized module."); } public T LookupMember(MetadataToken token) where T : class, IMetadataMember { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return (T)LookupMember(token); } public virtual bool TryLookupMember(MetadataToken token, [NotNullWhen(true)] out IMetadataMember? member) { member = null; return false; } public bool TryLookupMember(MetadataToken token, [NotNullWhen(true)] out T? member) where T : class, IMetadataMember { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (TryLookupMember(token, out IMetadataMember member2) && member2 is T val) { member = val; return true; } member = null; return false; } public virtual string LookupString(MetadataToken token) { throw new InvalidOperationException("Cannot lookup strings by tokens from a non-serialized module."); } public virtual bool TryLookupString(MetadataToken token, [NotNullWhen(true)] out string? value) { value = null; return false; } public virtual IndexEncoder GetIndexEncoder(CodedIndex codedIndex) { throw new InvalidOperationException("Cannot get an index encoder from a non-serialized module."); } public virtual IEnumerable GetImportedTypeReferences() { return Enumerable.Empty(); } public virtual IEnumerable GetImportedMemberReferences() { return Enumerable.Empty(); } public IEnumerable GetAllTypes() { Queue agenda = new Queue(); foreach (TypeDefinition topLevelType in TopLevelTypes) { agenda.Enqueue(topLevelType); } while (agenda.Count > 0) { TypeDefinition currentType = agenda.Dequeue(); yield return currentType; foreach (TypeDefinition nestedType in currentType.NestedTypes) { agenda.Enqueue(nestedType); } } } public MethodDefinition? GetModuleConstructor() { return GetModuleType()?.GetStaticConstructor(); } public MethodDefinition GetOrCreateModuleConstructor() { return GetOrCreateModuleType().GetOrCreateStaticConstructor(); } public TypeDefinition? GetModuleType() { if (TopLevelTypes.Count == 0) { return null; } TypeDefinition typeDefinition = TopLevelTypes[0]; if (!OriginalTargetRuntime.IsNetFramework && !typeDefinition.IsTypeOfUtf8(null, TypeDefinition.ModuleTypeName)) { return null; } return typeDefinition; } public TypeDefinition GetOrCreateModuleType() { TypeDefinition typeDefinition = GetModuleType(); if (typeDefinition == null) { typeDefinition = new TypeDefinition(null, TypeDefinition.ModuleTypeName, (TypeAttributes)0); TopLevelTypes.Insert(0, typeDefinition); } return typeDefinition; } protected virtual Utf8String? GetName() { return null; } protected virtual Guid GetMvid() { return Guid.NewGuid(); } protected virtual Guid GetEncId() { return Guid.Empty; } protected virtual Guid GetEncBaseId() { return Guid.Empty; } protected virtual IList GetTopLevelTypes() { return (IList)new OwnedCollection(this); } protected virtual IList GetAssemblyReferences() { return (IList)new OwnedCollection(this); } protected virtual IList GetModuleReferences() { return (IList)new OwnedCollection(this); } protected virtual IList GetFileReferences() { return (IList)new OwnedCollection(this); } protected virtual IList GetResources() { return (IList)new OwnedCollection(this); } protected virtual IList GetExportedTypes() { return (IList)new OwnedCollection(this); } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } AssemblyDescriptor? IResolutionScope.GetAssembly() { return Assembly; } protected virtual string GetRuntimeVersion() { return "v4.0.30319"; } protected virtual IManagedEntryPoint? GetManagedEntryPoint() { return null; } protected virtual IResourceDirectory? GetNativeResources() { return null; } protected virtual IList GetDebugData() { return new List(); } protected virtual ReferenceImporter GetDefaultImporter() { return new ReferenceImporter(this); } protected DotNetRuntimeInfo DetectTargetRuntime() { if (Assembly == null || !Assembly.TryGetTargetFramework(out var info)) { return CorLibTypeFactory.ExtractDotNetRuntimeInfo(); } return info; } protected IAssemblyResolver CreateAssemblyResolver(IFileService fileService) { string text = ((!string.IsNullOrEmpty(FilePath)) ? Path.GetDirectoryName(FilePath) : null); DotNetRuntimeInfo originalTargetRuntime = OriginalTargetRuntime; AssemblyResolverBase assemblyResolverBase; switch (originalTargetRuntime.Name) { case ".NETStandard": { if (string.IsNullOrEmpty(DotNetCorePathProvider.DefaultInstallationPath)) { goto case ".NETFramework"; } if (DotNetCorePathProvider.Default.TryGetLatestStandardCompatibleVersion(originalTargetRuntime.Version, out Version coreVersion)) { assemblyResolverBase = new DotNetCoreAssemblyResolver(fileService, coreVersion); break; } goto default; } case ".NETFramework": assemblyResolverBase = new DotNetFrameworkAssemblyResolver(fileService); break; case ".NETCoreApp": assemblyResolverBase = new DotNetCoreAssemblyResolver(fileService, originalTargetRuntime.Version); break; default: assemblyResolverBase = new DotNetFrameworkAssemblyResolver(fileService); break; } if (!string.IsNullOrEmpty(text)) { assemblyResolverBase.SearchDirectories.Add(text); } return assemblyResolverBase; } public override string ToString() { return Utf8String.op_Implicit(Name ?? Utf8String.op_Implicit(string.Empty)); } bool IImportable.IsImportedInModule(ModuleDefinition module) { return this == module; } public ModuleReference ImportWith(ReferenceImporter importer) { return importer.ImportModule(new ModuleReference(Name)); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } public void Write(string filePath) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown Write(filePath, new ManagedPEImageBuilder(), (IPEFileBuilder)new ManagedPEFileBuilder()); } public void Write(Stream outputStream) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown Write(outputStream, new ManagedPEImageBuilder(), (IPEFileBuilder)new ManagedPEFileBuilder()); } public void Write(string filePath, IPEImageBuilder imageBuilder) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown Write(filePath, imageBuilder, (IPEFileBuilder)new ManagedPEFileBuilder()); } public void Write(Stream outputStream, IPEImageBuilder imageBuilder) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown Write(outputStream, imageBuilder, (IPEFileBuilder)new ManagedPEFileBuilder()); } public void Write(string filePath, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder) { using FileStream outputStream = File.Create(filePath); Write((Stream)outputStream, imageBuilder, fileBuilder); } public void Write(Stream outputStream, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown Write((IBinaryStreamWriter)new BinaryStreamWriter(outputStream), imageBuilder, fileBuilder); } public void Write(IBinaryStreamWriter writer, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder) { fileBuilder.CreateFile(ToPEImage(imageBuilder)).Write(writer); } public IPEImage ToPEImage() { return ToPEImage(new ManagedPEImageBuilder()); } public IPEImage ToPEImage(IPEImageBuilder imageBuilder) { PEImageBuildResult pEImageBuildResult = imageBuilder.CreateImage(this); if (pEImageBuildResult.DiagnosticBag.HasErrors) { throw new AggregateException("Construction of the PE image failed with one or more errors.", pEImageBuildResult.DiagnosticBag.Exceptions); } return pEImageBuildResult.ConstructedImage; } } public class ModuleReference : MetadataMember, IResolutionScope, IMetadataMember, INameProvider, IModuleProvider, IImportable, IMemberRefParent, IHasCustomAttribute, IOwnedCollectionElement { private readonly LazyVariable _name; private IList? _customAttributes; public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public ModuleDefinition? Module { get; private set; } ModuleDefinition? IOwnedCollectionElement.Owner { get { return Module; } set { Module = value; } } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected ModuleReference(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); } public ModuleReference(Utf8String? name) : this(new MetadataToken((TableIndex)26, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Name = name; } public bool IsImportedInModule(ModuleDefinition module) { return Module == module; } public ModuleReference ImportWith(ReferenceImporter importer) { return importer.ImportModule(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } protected virtual Utf8String? GetName() { return null; } AssemblyDescriptor? IResolutionScope.GetAssembly() { return Module?.Assembly; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } public override string ToString() { return Utf8String.op_Implicit(Name ?? MetadataMember.NullName); } } public class ParameterDefinition : MetadataMember, IHasCustomAttribute, IMetadataMember, IHasConstant, INameProvider, IModuleProvider, IHasFieldMarshal, IOwnedCollectionElement { private readonly LazyVariable _name; private readonly LazyVariable _method; private readonly LazyVariable _constant; private readonly LazyVariable _marshalDescriptor; private IList? _customAttributes; public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public ushort Sequence { get; set; } public ParameterAttributes Attributes { get; set; } public bool IsIn { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 1) > 0; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (ParameterAttributes)((Attributes & 0xFFFE) | (value ? 1 : 0)); } } public bool IsOut { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 2) > 0; } set { //IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references) Attributes = (ParameterAttributes)((Attributes & 0xFFFD) | (value ? 2 : 0)); } } public bool IsOptional { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x10) > 0; } set { //IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references) Attributes = (ParameterAttributes)((Attributes & 0xFFEF) | (value ? 16 : 0)); } } public bool HasDefault { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x1000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (ParameterAttributes)((Attributes & 0xEFFF) | (value ? 4096 : 0)); } } public bool HasFieldMarshal { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x2000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (ParameterAttributes)((Attributes & 0xDFFF) | (value ? 8192 : 0)); } } public MethodDefinition? Method { get { return _method.Value; } private set { _method.Value = value; } } MethodDefinition? IOwnedCollectionElement.Owner { get { return Method; } set { Method = value; } } public ModuleDefinition? Module => Method?.Module; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } public Constant? Constant { get { return _constant.Value; } set { _constant.Value = value; } } public MarshalDescriptor? MarshalDescriptor { get { return _marshalDescriptor.Value; } set { _marshalDescriptor.Value = value; } } protected ParameterDefinition(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _method = new LazyVariable((Func)GetMethod); _constant = new LazyVariable((Func)GetConstant); _marshalDescriptor = new LazyVariable((Func)GetMarshalDescriptor); } public ParameterDefinition(Utf8String? name) : this(new MetadataToken((TableIndex)8, 0u)) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) Name = name; } public ParameterDefinition(ushort sequence, Utf8String? name, ParameterAttributes attributes) : this(new MetadataToken((TableIndex)8, 0u)) { //IL_0003: 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) Sequence = sequence; Name = name; Attributes = attributes; } protected virtual Utf8String? GetName() { return null; } protected virtual MethodDefinition? GetMethod() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } protected virtual Constant? GetConstant() { return null; } protected virtual MarshalDescriptor? GetMarshalDescriptor() { return null; } public override string ToString() { return Utf8String.op_Implicit(Name ?? Utf8String.op_Implicit(string.Empty)); } } public class PropertyDefinition : MetadataMember, IHasSemantics, IMetadataMember, IMemberDefinition, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IHasCustomAttribute, IHasConstant, IOwnedCollectionElement { private readonly LazyVariable _name; private readonly LazyVariable _declaringType; private readonly LazyVariable _signature; private readonly LazyVariable _constant; private IList? _semantics; private IList? _customAttributes; public PropertyAttributes Attributes { get; set; } public bool IsSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x200) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (PropertyAttributes)((Attributes & 0xFDFF) | (value ? 512 : 0)); } } public bool IsRuntimeSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x400) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (PropertyAttributes)((Attributes & 0xFBFF) | (value ? 1024 : 0)); } } public bool HasDefault { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x1000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (PropertyAttributes)((Attributes & 0xEFFF) | (value ? 4096 : 0)); } } public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public string FullName => MemberNameGenerator.GetPropertyFullName(this); public PropertySignature? Signature { get { return _signature.Value; } set { _signature.Value = value; } } public ModuleDefinition? Module => DeclaringType?.Module; public TypeDefinition? DeclaringType { get { return _declaringType.Value; } private set { _declaringType.Value = value; } } ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; TypeDefinition? IOwnedCollectionElement.Owner { get { return DeclaringType; } set { DeclaringType = value; } } public IList Semantics { get { if (_semantics == null) { Interlocked.CompareExchange(ref _semantics, GetSemantics(), null); } return _semantics; } } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } public Constant? Constant { get { return _constant.Value; } set { _constant.Value = value; } } public MethodDefinition? GetMethod => Semantics.FirstOrDefault((MethodSemantics s) => (int)s.Attributes == 2)?.Method; public MethodDefinition? SetMethod => Semantics.FirstOrDefault((MethodSemantics s) => (int)s.Attributes == 1)?.Method; protected PropertyDefinition(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _signature = new LazyVariable((Func)GetSignature); _declaringType = new LazyVariable((Func)GetDeclaringType); _constant = new LazyVariable((Func)GetConstant); } public PropertyDefinition(Utf8String? name, PropertyAttributes attributes, PropertySignature? signature) : this(new MetadataToken((TableIndex)23, 0u)) { //IL_0004: 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) Name = name; Attributes = attributes; Signature = signature; } public void SetSemanticMethods(MethodDefinition? getMethod, MethodDefinition? setMethod) { Semantics.Clear(); if (getMethod != null) { Semantics.Add(new MethodSemantics(getMethod, (MethodSemanticsAttributes)2)); } if (setMethod != null) { Semantics.Add(new MethodSemantics(setMethod, (MethodSemanticsAttributes)1)); } } public bool IsAccessibleFromType(TypeDefinition type) { TypeDefinition type2 = type; return Semantics.Any((MethodSemantics s) => s.Method?.IsAccessibleFromType(type2) ?? false); } IMemberDefinition IMemberDescriptor.Resolve() { return this; } public bool IsImportedInModule(ModuleDefinition module) { if (Module == module) { return Signature?.IsImportedInModule(module) ?? false; } return false; } IImportable IImportable.ImportWith(ReferenceImporter importer) { throw new NotSupportedException(); } protected virtual Utf8String? GetName() { return null; } protected virtual PropertySignature? GetSignature() { return null; } protected virtual TypeDefinition? GetDeclaringType() { return null; } protected virtual IList GetSemantics() { return (IList)new MethodSemanticsCollection(this); } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } protected virtual Constant? GetConstant() { return null; } public override string ToString() { return FullName; } } public class ReferenceImporter : ITypeSignatureVisitor { private readonly SignatureComparer _comparer = new SignatureComparer(); public ModuleDefinition TargetModule { get; } public ReferenceImporter(ModuleDefinition module) { TargetModule = module ?? throw new ArgumentNullException("module"); } private static void AssertTypeIsValid(ITypeDefOrRef? type) { if (type == null) { throw new ArgumentNullException("type"); } if (type.Scope == null) { throw new ArgumentException("Cannot import types that are not added to a module."); } } public IResolutionScope ImportScope(IResolutionScope? scope) { if (scope == null) { throw new ArgumentNullException("scope"); } if (scope.IsImportedInModule(TargetModule)) { return scope; } if (!(scope is AssemblyReference assembly)) { if (!(scope is TypeReference type)) { if (!(scope is ModuleDefinition moduleDefinition)) { if (scope is ModuleReference module) { return ImportModule(module); } throw new ArgumentOutOfRangeException("scope"); } return ImportAssembly(moduleDefinition.Assembly ?? throw new ArgumentException("Module is not added to an assembly.")); } return (IResolutionScope)ImportType(type); } return ImportAssembly(assembly); } public IImplementation ImportImplementation(IImplementation? implementation) { if (implementation == null) { throw new ArgumentNullException("implementation"); } if (implementation.IsImportedInModule(TargetModule)) { return implementation; } if (!(implementation is AssemblyReference assembly)) { if (!(implementation is ExportedType type)) { if (implementation is FileReference file) { return ImportFile(file); } throw new ArgumentOutOfRangeException("implementation"); } return ImportType(type); } return ImportAssembly(assembly); } protected virtual AssemblyReference ImportAssembly(AssemblyDescriptor assembly) { AssemblyDescriptor assembly2 = assembly; if (assembly2 == null) { throw new ArgumentNullException("assembly"); } if (assembly2 is AssemblyReference result && assembly2.IsImportedInModule(TargetModule)) { return result; } AssemblyReference assemblyReference = TargetModule.AssemblyReferences.FirstOrDefault((AssemblyReference a) => _comparer.Equals(a, assembly2)); if (assemblyReference == null) { assemblyReference = new AssemblyReference(assembly2); TargetModule.AssemblyReferences.Add(assemblyReference); } return assemblyReference; } protected virtual FileReference ImportFile(FileReference file) { //IL_006b: Unknown result type (might be due to invalid IL or missing references) FileReference file2 = file; if (file2 == null) { throw new ArgumentNullException("file"); } if (file2.IsImportedInModule(TargetModule)) { return file2; } FileReference fileReference = TargetModule.FileReferences.FirstOrDefault((FileReference a) => a.Name == file2.Name); if (fileReference == null) { fileReference = new FileReference(file2.Name, file2.Attributes); TargetModule.FileReferences.Add(fileReference); } return fileReference; } public virtual ModuleReference ImportModule(ModuleReference module) { ModuleReference module2 = module; if (module2 == null) { throw new ArgumentNullException("module"); } if (module2.IsImportedInModule(TargetModule)) { return module2; } ModuleReference moduleReference = TargetModule.ModuleReferences.FirstOrDefault((ModuleReference a) => _comparer.Equals(a, module2)); if (moduleReference == null) { moduleReference = new ModuleReference(module2.Name); TargetModule.ModuleReferences.Add(moduleReference); } return moduleReference; } public ITypeDefOrRef ImportType(ITypeDefOrRef type) { if (type != null) { if (!(type is TypeDefinition type2)) { if (!(type is TypeReference type3)) { if (type is TypeSpecification type4) { return ImportType(type4); } throw new ArgumentOutOfRangeException("type"); } return ImportType(type3); } return ImportType(type2); } throw new ArgumentNullException("type"); } public ITypeDefOrRef? ImportTypeOrNull(ITypeDefOrRef? type) { if (type == null) { return null; } return ImportType(type); } protected virtual ITypeDefOrRef ImportType(TypeDefinition type) { AssertTypeIsValid(type); if (type.IsImportedInModule(TargetModule)) { return type; } return new TypeReference(TargetModule, ImportScope(((ITypeDescriptor)type).Scope), type.Namespace, type.Name); } protected virtual ITypeDefOrRef ImportType(TypeReference type) { AssertTypeIsValid(type); if (type.IsImportedInModule(TargetModule)) { return type; } return new TypeReference(TargetModule, ImportScope(type.Scope), type.Namespace, type.Name); } protected virtual ITypeDefOrRef ImportType(TypeSpecification type) { AssertTypeIsValid(type); if (type.Signature == null) { throw new ArgumentNullException("type"); } if (type.IsImportedInModule(TargetModule)) { return type; } return new TypeSpecification(ImportTypeSignature(type.Signature)); } public virtual ExportedType ImportType(ExportedType type) { ExportedType type2 = type; if (type2 == null) { throw new ArgumentNullException("type"); } if (type2.IsImportedInModule(TargetModule)) { return type2; } ExportedType exportedType = TargetModule.ExportedTypes.FirstOrDefault((ExportedType a) => _comparer.Equals(a, type2)); if (exportedType == null) { exportedType = new ExportedType(ImportImplementation(type2.Implementation), Utf8String.op_Implicit(type2.Namespace), Utf8String.op_Implicit(type2.Name)); TargetModule.ExportedTypes.Add(exportedType); } return exportedType; } public virtual TypeSignature ImportTypeSignature(TypeSignature type) { if (type == null) { throw new ArgumentNullException("type"); } if (type.IsImportedInModule(TargetModule)) { return type; } return type.AcceptVisitor(this); } public TypeSignature? ImportTypeSignatureOrNull(TypeSignature? type) { if (type == null) { return null; } return ImportTypeSignature(type); } public virtual ITypeDefOrRef ImportType(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } TypeSignature typeSignature = ImportTypeSignature(type); if (typeSignature is TypeDefOrRefSignature || typeSignature is CorLibTypeSignature) { return typeSignature.GetUnderlyingTypeDefOrRef(); } return new TypeSpecification(typeSignature); } public virtual TypeSignature ImportTypeSignature(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (type.IsArray) { return ImportArrayType(type); } if (type.IsConstructedGenericType) { return ImportGenericType(type); } if (type.IsPointer) { return new PointerTypeSignature(ImportTypeSignature(type.GetElementType())); } if (type.IsByRef) { return new ByReferenceTypeSignature(ImportTypeSignature(type.GetElementType())); } if (type.IsGenericParameter) { return new GenericParameterSignature((!(type.DeclaringMethod != null)) ? GenericParameterType.Type : GenericParameterType.Method, type.GenericParameterPosition); } CorLibTypeSignature corLibTypeSignature = TargetModule.CorLibTypeFactory.FromName(type.Namespace, type.Name); if (corLibTypeSignature != null) { return corLibTypeSignature; } TypeReference type2; if (type.IsNested) { IResolutionScope scope = (IResolutionScope)ImportType(type.DeclaringType); type2 = new TypeReference(TargetModule, scope, null, Utf8String.op_Implicit(type.Name)); } else { AssemblyReference scope2 = ImportAssembly(new ReflectionAssemblyDescriptor(TargetModule, type.Assembly.GetName())); type2 = new TypeReference(TargetModule, scope2, Utf8String.op_Implicit(type.Namespace), Utf8String.op_Implicit(type.Name)); } return new TypeDefOrRefSignature(type2, type.IsValueType); } private TypeSignature ImportArrayType(Type type) { TypeSignature baseType = ImportTypeSignature(type.GetElementType()); int arrayRank = type.GetArrayRank(); if (arrayRank == 1) { return new SzArrayTypeSignature(baseType); } ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature(baseType); for (int i = 0; i < arrayRank; i++) { arrayTypeSignature.Dimensions.Add(default(ArrayDimension)); } return arrayTypeSignature; } private TypeSignature ImportGenericType(Type type) { GenericInstanceTypeSignature genericInstanceTypeSignature = new GenericInstanceTypeSignature(ImportType(type.GetGenericTypeDefinition()), type.IsValueType); Type[] genericArguments = type.GetGenericArguments(); foreach (Type type2 in genericArguments) { genericInstanceTypeSignature.TypeArguments.Add(ImportTypeSignature(type2)); } return genericInstanceTypeSignature; } public virtual IMethodDescriptor ImportMethod(IMethodDescriptor method) { if (method != null) { if (!(method is IMethodDefOrRef method2)) { if (method is MethodSpecification method3) { return ImportMethod(method3); } throw new ArgumentOutOfRangeException("method"); } return ImportMethod(method2); } throw new ArgumentNullException("method"); } public IMethodDescriptor? ImportMethodOrNull(IMethodDescriptor? method) { if (method != null) { return ImportMethod(method); } return null; } public virtual IMethodDefOrRef ImportMethod(IMethodDefOrRef method) { if (method == null) { throw new ArgumentNullException("method"); } if (method.DeclaringType == null) { throw new ArgumentException("Cannot import a method that is not added to a type."); } if (method.Signature == null) { throw new ArgumentException("Cannot import a method that does not have a signature."); } if (method.IsImportedInModule(TargetModule)) { return method; } return new MemberReference(ImportType(method.DeclaringType), method.Name, ImportMethodSignature(method.Signature)); } public IMethodDefOrRef? ImportMethodOrNull(IMethodDefOrRef? method) { if (method != null) { return ImportMethod(method); } return null; } public virtual MethodSignature ImportMethodSignature(MethodSignature signature) { if (signature == null) { throw new ArgumentNullException("signature"); } TypeSignature[] array = new TypeSignature[signature.ParameterTypes.Count]; for (int i = 0; i < array.Length; i++) { array[i] = ImportTypeSignature(signature.ParameterTypes[i]); } MethodSignature methodSignature = new MethodSignature(signature.Attributes, ImportTypeSignature(signature.ReturnType), array); methodSignature.GenericParameterCount = signature.GenericParameterCount; for (int j = 0; j < signature.SentinelParameterTypes.Count; j++) { methodSignature.SentinelParameterTypes.Add(ImportTypeSignature(signature.SentinelParameterTypes[j])); } return methodSignature; } public virtual GenericInstanceMethodSignature ImportGenericInstanceMethodSignature(GenericInstanceMethodSignature signature) { if (signature == null) { throw new ArgumentNullException("signature"); } TypeSignature[] array = new TypeSignature[signature.TypeArguments.Count]; for (int i = 0; i < array.Length; i++) { array[i] = ImportTypeSignature(signature.TypeArguments[i]); } return new GenericInstanceMethodSignature(signature.Attributes, array); } public virtual LocalVariablesSignature ImportLocalVariablesSignature(LocalVariablesSignature signature) { if (signature == null) { throw new ArgumentNullException("signature"); } TypeSignature[] array = new TypeSignature[signature.VariableTypes.Count]; for (int i = 0; i < array.Length; i++) { array[i] = ImportTypeSignature(signature.VariableTypes[i]); } return new LocalVariablesSignature(array); } public virtual MethodSpecification ImportMethod(MethodSpecification method) { if (method.Method == null || method.Signature == null) { throw new ArgumentNullException("method"); } if (method.DeclaringType == null) { throw new ArgumentException("Cannot import a method that is not added to a type."); } if (method.IsImportedInModule(TargetModule)) { return method; } IMethodDefOrRef method2 = ImportMethod(method.Method); GenericInstanceMethodSignature genericInstanceMethodSignature = new GenericInstanceMethodSignature(); foreach (TypeSignature typeArgument in method.Signature.TypeArguments) { genericInstanceMethodSignature.TypeArguments.Add(ImportTypeSignature(typeArgument)); } return new MethodSpecification(method2, genericInstanceMethodSignature); } [RequiresUnreferencedCode("Calls System.Reflection.Module.ResolveMethod(int)")] public virtual IMethodDescriptor ImportMethod(MethodBase method) { if ((object)method == null) { throw new ArgumentNullException("method"); } if (method.IsGenericMethod && !method.IsGenericMethodDefinition) { return ImportGenericMethod((MethodInfo)method); } Type declaringType = method.DeclaringType; if ((object)declaringType == null) { throw new ArgumentException("Method's declaring type is null."); } if (declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition) { method = method.Module.ResolveMethod(method.MetadataToken); } TypeSignature returnType = ((method is MethodInfo methodInfo) ? ImportTypeSignature(methodInfo.ReturnType) : TargetModule.CorLibTypeFactory.Void); ParameterInfo[] array = (((object)declaringType != null && declaringType.IsConstructedGenericType) ? method.Module.ResolveMethod(method.MetadataToken).GetParameters() : method.GetParameters()); TypeSignature[] array2 = new TypeSignature[array.Length]; for (int i = 0; i < array2.Length; i++) { array2[i] = ImportTypeSignature(array[i].ParameterType); } MethodSignature methodSignature = new MethodSignature((!method.IsStatic) ? CallingConventionAttributes.HasThis : CallingConventionAttributes.Default, returnType, array2); if (method.IsGenericMethodDefinition) { methodSignature.IsGeneric = true; methodSignature.GenericParameterCount = method.GetGenericArguments().Length; } return new MemberReference(ImportType(declaringType), Utf8String.op_Implicit(method.Name), methodSignature); } [RequiresUnreferencedCode("Calls AsmResolver.DotNet.ReferenceImporter.ImportMethod(System.Reflection.MethodBase)")] private IMethodDescriptor ImportGenericMethod(MethodInfo method) { IMethodDefOrRef method2 = (IMethodDefOrRef)ImportMethod(method.GetGenericMethodDefinition()); GenericInstanceMethodSignature genericInstanceMethodSignature = new GenericInstanceMethodSignature(); Type[] genericArguments = method.GetGenericArguments(); foreach (Type type in genericArguments) { genericInstanceMethodSignature.TypeArguments.Add(ImportTypeSignature(type)); } return new MethodSpecification(method2, genericInstanceMethodSignature); } public virtual IFieldDescriptor ImportField(IFieldDescriptor field) { if (field == null) { throw new ArgumentNullException("field"); } if (field.DeclaringType == null) { throw new ArgumentException("Cannot import a field that is not added to a type."); } if (field.Signature == null) { throw new ArgumentException("Cannot import a field that does not have a signature."); } if (field.IsImportedInModule(TargetModule)) { return field; } return new MemberReference(ImportType((ITypeDefOrRef)field.DeclaringType), field.Name, ImportFieldSignature(field.Signature)); } public FieldSignature ImportFieldSignature(FieldSignature signature) { if (signature == null) { throw new ArgumentNullException("signature"); } return new FieldSignature(signature.Attributes, ImportTypeSignature(signature.FieldType)); } [RequiresUnreferencedCode("Calls System.Reflection.Module.ResolveField(int)")] public MemberReference ImportField(FieldInfo field) { if ((object)field == null) { throw new ArgumentNullException("field"); } Type declaringType = field.DeclaringType; if ((object)declaringType != null && declaringType.IsConstructedGenericType) { field = field.Module.ResolveField(field.MetadataToken); } ITypeDefOrRef parent; if (!(field.DeclaringType != null)) { ITypeDefOrRef moduleType = TargetModule.GetModuleType(); parent = moduleType; } else { parent = ImportType(field.DeclaringType); } return new MemberReference(signature: new FieldSignature(ImportTypeSignature(field.FieldType)), parent: parent, name: Utf8String.op_Implicit(field.Name)); } public PropertySignature ImportPropertySignature(PropertySignature signature) { if (signature == null) { throw new ArgumentNullException("signature"); } TypeSignature[] array = new TypeSignature[signature.ParameterTypes.Count]; for (int i = 0; i < array.Length; i++) { array[i] = ImportTypeSignature(signature.ParameterTypes[i]); } return new PropertySignature(signature.Attributes, ImportTypeSignature(signature.ReturnType), array); } TypeSignature ITypeSignatureVisitor.VisitArrayType(ArrayTypeSignature signature) { ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature(signature.BaseType.AcceptVisitor(this)); foreach (ArrayDimension dimension in signature.Dimensions) { arrayTypeSignature.Dimensions.Add(new ArrayDimension(dimension.Size, dimension.LowerBound)); } return arrayTypeSignature; } TypeSignature ITypeSignatureVisitor.VisitBoxedType(BoxedTypeSignature signature) { return new BoxedTypeSignature(signature.BaseType.AcceptVisitor(this)); } TypeSignature ITypeSignatureVisitor.VisitByReferenceType(ByReferenceTypeSignature signature) { return new ByReferenceTypeSignature(signature.BaseType.AcceptVisitor(this)); } TypeSignature ITypeSignatureVisitor.VisitCorLibType(CorLibTypeSignature signature) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return TargetModule.CorLibTypeFactory.FromElementType(signature.ElementType); } TypeSignature ITypeSignatureVisitor.VisitCustomModifierType(CustomModifierTypeSignature signature) { return new CustomModifierTypeSignature(ImportType(signature.ModifierType), signature.IsRequired, signature.BaseType.AcceptVisitor(this)); } TypeSignature ITypeSignatureVisitor.VisitGenericInstanceType(GenericInstanceTypeSignature signature) { GenericInstanceTypeSignature genericInstanceTypeSignature = new GenericInstanceTypeSignature(ImportType(signature.GenericType), signature.IsValueType); foreach (TypeSignature typeArgument in signature.TypeArguments) { genericInstanceTypeSignature.TypeArguments.Add(typeArgument.AcceptVisitor(this)); } return genericInstanceTypeSignature; } TypeSignature ITypeSignatureVisitor.VisitGenericParameter(GenericParameterSignature signature) { return new GenericParameterSignature(TargetModule, signature.ParameterType, signature.Index); } TypeSignature ITypeSignatureVisitor.VisitPinnedType(PinnedTypeSignature signature) { return new PinnedTypeSignature(signature.BaseType.AcceptVisitor(this)); } TypeSignature ITypeSignatureVisitor.VisitPointerType(PointerTypeSignature signature) { return new PointerTypeSignature(signature.BaseType.AcceptVisitor(this)); } TypeSignature ITypeSignatureVisitor.VisitSentinelType(SentinelTypeSignature signature) { return new SentinelTypeSignature(); } TypeSignature ITypeSignatureVisitor.VisitSzArrayType(SzArrayTypeSignature signature) { return new SzArrayTypeSignature(signature.BaseType.AcceptVisitor(this)); } TypeSignature ITypeSignatureVisitor.VisitTypeDefOrRef(TypeDefOrRefSignature signature) { return new TypeDefOrRefSignature(ImportType(signature.Type), signature.IsValueType); } TypeSignature ITypeSignatureVisitor.VisitFunctionPointerType(FunctionPointerTypeSignature signature) { return new FunctionPointerTypeSignature(ImportMethodSignature(signature.Signature)); } } public class ReflectionAssemblyDescriptor : AssemblyDescriptor { private readonly ModuleDefinition _parentModule; private readonly AssemblyName _assemblyName; public override bool IsCorLib { get { if (base.Name != null) { return KnownCorLibs.KnownCorLibNames.Contains(Utf8String.op_Implicit(base.Name)); } return false; } } public ReflectionAssemblyDescriptor(ModuleDefinition parentModule, AssemblyName assemblyName) : base(new MetadataToken((TableIndex)35, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) _parentModule = parentModule; _assemblyName = assemblyName; base.Version = assemblyName.Version ?? new Version(); } protected override Utf8String? GetName() { return Utf8String.op_Implicit(_assemblyName.Name); } protected override Utf8String? GetCulture() { return Utf8String.op_Implicit(_assemblyName.CultureName); } public override bool IsImportedInModule(ModuleDefinition module) { return false; } public override AssemblyReference ImportWith(ReferenceImporter importer) { return (AssemblyReference)importer.ImportScope(new AssemblyReference(this)); } public override byte[]? GetPublicKeyToken() { return _assemblyName.GetPublicKeyToken(); } public override AssemblyDefinition? Resolve() { return _parentModule.MetadataResolver.AssemblyResolver.Resolve(this); } } internal static class SafeExtensions { public static string SafeToString(this IMetadataMember? self) { //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_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_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) if (self == null) { return "null"; } MetadataToken metadataToken; try { string text = self.ToString(); if (text.Length > 200) { text = text.Remove(197) + "... (truncated)"; } metadataToken = self.MetadataToken; if (((MetadataToken)(ref metadataToken)).Rid != 0) { string text2 = text; metadataToken = self.MetadataToken; text = text2 + " (0x" + ((object)(MetadataToken)(ref metadataToken)).ToString() + ")"; } return text; } catch { metadataToken = self.MetadataToken; return "0x" + ((object)(MetadataToken)(ref metadataToken)).ToString(); } } public static string SafeToString(this object? self) { if (self == null) { return "null"; } try { return self.ToString(); } catch { return self.GetType().ToString(); } } public static void MetadataBuilder(this IErrorListener listener, string message) { listener.RegisterException((Exception)new MetadataBuilderException(message)); } } public class SecurityDeclaration : MetadataMember, IOwnedCollectionElement { private readonly LazyVariable _parent; private readonly LazyVariable _permissionSet; public SecurityAction Action { get; set; } public IHasSecurityDeclaration? Parent { get { return _parent.Value; } private set { _parent.Value = value; } } IHasSecurityDeclaration? IOwnedCollectionElement.Owner { get { return Parent; } set { Parent = value; } } public PermissionSetSignature? PermissionSet { get { return _permissionSet.Value; } set { _permissionSet.Value = value; } } protected SecurityDeclaration(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _parent = new LazyVariable((Func)GetParent); _permissionSet = new LazyVariable((Func)GetPermissionSet); } public SecurityDeclaration(SecurityAction action, PermissionSetSignature? permissionSet) : this(new MetadataToken((TableIndex)14, 0u)) { //IL_0004: 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) Action = action; PermissionSet = permissionSet; } protected virtual IHasSecurityDeclaration? GetParent() { return null; } protected virtual PermissionSetSignature? GetPermissionSet() { return null; } } public class StandAloneSignature : MetadataMember, IHasCustomAttribute, IMetadataMember { private readonly LazyVariable _signature; private IList? _customAttributes; public BlobSignature? Signature { get { return _signature.Value; } set { _signature.Value = value; } } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected StandAloneSignature(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _signature = new LazyVariable((Func)GetSignature); } public StandAloneSignature(BlobSignature signature) : this(new MetadataToken((TableIndex)17, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Signature = signature; } protected virtual CallingConventionSignature? GetSignature() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } public override string ToString() { return Signature?.ToString() ?? "<<>>"; } } public sealed class TokenAllocator { private readonly struct TokenBucket { public MetadataToken BaseToken { get; } public List AssignedMembers { get; } public TokenBucket(MetadataToken baseToken) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) BaseToken = baseToken; AssignedMembers = new List(); } public MetadataToken GetNextAvailableToken() { //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_0009: 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_0014: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) MetadataToken baseToken = BaseToken; TableIndex table = ((MetadataToken)(ref baseToken)).Table; baseToken = BaseToken; return new MetadataToken(table, (uint)(((MetadataToken)(ref baseToken)).Rid + AssignedMembers.Count)); } } private readonly TokenBucket[] _buckets = new TokenBucket[56]; internal TokenAllocator(ModuleDefinition module) { if (module == null) { throw new ArgumentNullException("module"); } Initialize(module.DotNetDirectory); } private void Initialize(IDotNetDirectory? netDirectory) { if (netDirectory == null) { InitializeDefault(); } else { InitializeTable(netDirectory); } } private void InitializeDefault() { //IL_0001: 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_0024: Invalid comparison between Unknown and I4 //IL_000a: 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_000d: 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_001e: 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) TableIndex val = (TableIndex)0; while ((int)val < 56) { _buckets[val] = new TokenBucket(new MetadataToken(val, 1u)); val = (TableIndex)(byte)(val + 1); } } private void InitializeTable(IDotNetDirectory netDirectory) { //IL_000d: 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: Invalid comparison between Unknown and I4 //IL_0010: 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_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_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_0027: 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) TablesStream stream = netDirectory.Metadata.GetStream(); TableIndex val = (TableIndex)0; while ((int)val < 56) { if (TableIndexExtensions.IsValidTableIndex(val)) { IMetadataTable table = stream.GetTable(val); _buckets[val] = new TokenBucket(new MetadataToken(val, (uint)(((ICollection)table).Count + 1))); } val = (TableIndex)(byte)(val + 1); } } public MetadataToken GetNextAvailableToken(TableIndex index) { //IL_0006: 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) return _buckets[index].GetNextAvailableToken(); } public void AssignNextAvailableToken(MetadataMember member) { //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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003a: 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_004b: Unknown result type (might be due to invalid IL or missing references) if (member == null) { throw new ArgumentNullException("member"); } MetadataToken metadataToken = member.MetadataToken; if (((MetadataToken)(ref metadataToken)).Rid != 0) { throw new ArgumentException("Only new members can be assigned a new metadata token"); } metadataToken = member.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; member.MetadataToken = GetNextAvailableToken(table); _buckets[table].AssignedMembers.Add(member); } public IEnumerable GetAssignees(TableIndex table) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _buckets[table].AssignedMembers; } } public class TypeDefinition : MetadataMember, ITypeDefOrRef, ITypeDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMemberRefParent, IMetadataMember, IHasCustomAttribute, IMemberDefinition, IHasGenericParameters, IHasSecurityDeclaration, IOwnedCollectionElement, IOwnedCollectionElement { internal static readonly Utf8String ModuleTypeName = Utf8String.op_Implicit(""); private readonly LazyVariable _namespace; private readonly LazyVariable _name; private readonly LazyVariable _baseType; private readonly LazyVariable _declaringType; private readonly LazyVariable _classLayout; private IList? _nestedTypes; private ModuleDefinition? _module; private IList? _fields; private IList? _methods; private IList? _properties; private IList? _events; private IList? _customAttributes; private IList? _securityDeclarations; private IList? _genericParameters; private IList? _interfaces; private IList? _methodImplementations; public Utf8String? Namespace { get { return _namespace.Value; } set { _namespace.Value = value; } } string? ITypeDescriptor.Namespace => Utf8String.op_Implicit(Namespace); public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public string FullName => MemberNameGenerator.GetTypeFullName(this); public TypeAttributes Attributes { get; set; } public bool IsNotPublic { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 0; } set { //IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)(value ? (Attributes & -8) : Attributes); } } public bool IsPublic { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 1; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -8) | (value ? 1 : 0)); } } public bool IsNestedPublic { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 2; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -8) | (value ? 2 : 0)); } } public bool IsNestedPrivate { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 3; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -8) | (value ? 3 : 0)); } } public bool IsNestedFamily { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 4; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -8) | (value ? 4 : 0)); } } public bool IsNestedAssembly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 5; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -8) | (value ? 5 : 0)); } } public bool IsNestedFamilyAndAssembly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 6; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -8) | (value ? 6 : 0)); } } public bool IsNestedFamilyOrAssembly { get { //IL_0001: 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_0009: Invalid comparison between Unknown and I4 return (Attributes & 7) == 7; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -8) | (value ? 7 : 0)); } } public bool IsAutoLayout { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x18) == 0; } set { //IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)(value ? (Attributes & -25) : Attributes); } } public bool IsSequentialLayout { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x18) == 8; } set { //IL_0002: 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_0011: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -25) | (value ? 8 : 0)); } } public bool IsExplicitLayout { get { //IL_0001: 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_000b: Invalid comparison between Unknown and I4 return (Attributes & 0x18) == 16; } set { //IL_0002: 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_0012: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -25) | (value ? 16 : 0)); } } public bool IsClass { get { //IL_0001: 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_000a: Invalid comparison between Unknown and I4 return (Attributes & 0x60) == 0; } set { //IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)(value ? (Attributes & -97) : Attributes); } } public bool IsInterface { get { //IL_0001: 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_000b: Invalid comparison between Unknown and I4 return (Attributes & 0x60) == 32; } set { //IL_0002: 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_0012: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -97) | (value ? 32 : 0)); } } public bool IsAbstract { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x80) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -129) | (value ? 128 : 0)); } } public bool IsSealed { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x100) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -257) | (value ? 256 : 0)); } } public bool IsSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x400) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -1025) | (value ? 1024 : 0)); } } public bool IsRuntimeSpecialName { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x200000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -2097153) | (value ? 2097152 : 0)); } } public bool IsImport { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x1000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -4097) | (value ? 4096 : 0)); } } public bool IsSerializable { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x2000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -8193) | (value ? 8192 : 0)); } } public bool IsAnsiClass { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x30000) == 0; } set { //IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)(value ? (Attributes & -196609) : Attributes); } } public bool IsUnicodeClass { get { //IL_0001: 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_0011: Invalid comparison between Unknown and I4 return (Attributes & 0x30000) == 65536; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -196609) | (value ? 65536 : 0)); } } public bool IsAutoClass { get { //IL_0001: 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_0011: Invalid comparison between Unknown and I4 return (Attributes & 0x30000) == 131072; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -196609) | (value ? 131072 : 0)); } } public bool IsCustomFormatClass { get { //IL_0001: 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_0011: Invalid comparison between Unknown and I4 return (Attributes & 0x30000) == 196608; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -196609) | (value ? 196608 : 0)); } } public bool IsBeforeFieldInit { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x100000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -1048577) | (value ? 1048576 : 0)); } } public bool IsForwarder { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x200000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -2097153) | (value ? 2097152 : 0)); } } public bool HasSecurity { get { //IL_0001: 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_000d: Invalid comparison between Unknown and I4 return (Attributes & 0x40000) > 0; } set { //IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references) Attributes = (TypeAttributes)((Attributes & -262145) | (value ? 262144 : 0)); } } public ITypeDefOrRef? BaseType { get { return _baseType.Value; } set { _baseType.Value = value; } } public ModuleDefinition? Module { get { if (DeclaringType == null) { return _module; } return DeclaringType.Module; } } ModuleDefinition? IOwnedCollectionElement.Owner { get { return Module; } set { _module = value; } } public TypeDefinition? DeclaringType { get { return _declaringType.Value; } private set { _declaringType.Value = value; } } ITypeDefOrRef? ITypeDefOrRef.DeclaringType => DeclaringType; ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; TypeDefinition? IOwnedCollectionElement.Owner { get { return DeclaringType; } set { DeclaringType = value; } } public bool IsNested => DeclaringType != null; public IList NestedTypes { get { if (_nestedTypes == null) { Interlocked.CompareExchange(ref _nestedTypes, GetNestedTypes(), null); } return _nestedTypes; } } IResolutionScope? ITypeDescriptor.Scope => GetDeclaringScope(); public bool IsValueType { get { if (BaseType != null) { if (!BaseType.IsTypeOf("System", "ValueType")) { return IsEnum; } return true; } return false; } } public bool IsEnum => BaseType?.IsTypeOf("System", "Enum") ?? false; public bool IsDelegate { get { ITypeDefOrRef baseType = BaseType; if (baseType == null) { return false; } if (!baseType.IsTypeOf("System", "Delegate")) { return baseType.IsTypeOf("System", "MulticastDelegate"); } return true; } } public bool IsModuleType { get { TypeDefinition typeDefinition = Module?.GetModuleType(); if (typeDefinition != null) { return typeDefinition == this; } return false; } } public bool IsReadOnly { get { if (IsValueType) { return this.HasCustomAttribute("System.Runtime.CompilerServices", "ReadOnlyAttribute"); } return false; } } public bool IsByRefLike { get { if (IsValueType) { return this.HasCustomAttribute("System.Runtime.CompilerServices", "IsByRefLikeAttribute"); } return false; } } public IList Fields { get { if (_fields == null) { Interlocked.CompareExchange(ref _fields, GetFields(), null); } return _fields; } } public IList Methods { get { if (_methods == null) { Interlocked.CompareExchange(ref _methods, GetMethods(), null); } return _methods; } } public IList Properties { get { if (_properties == null) { Interlocked.CompareExchange(ref _properties, GetProperties(), null); } return _properties; } } public IList Events { get { if (_events == null) { Interlocked.CompareExchange(ref _events, GetEvents(), null); } return _events; } } public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } public IList SecurityDeclarations { get { if (_securityDeclarations == null) { Interlocked.CompareExchange(ref _securityDeclarations, GetSecurityDeclarations(), null); } return _securityDeclarations; } } public IList GenericParameters { get { if (_genericParameters == null) { Interlocked.CompareExchange(ref _genericParameters, GetGenericParameters(), null); } return _genericParameters; } } public IList Interfaces { get { if (_interfaces == null) { Interlocked.CompareExchange(ref _interfaces, GetInterfaces(), null); } return _interfaces; } } public IList MethodImplementations { get { if (_methodImplementations == null) { Interlocked.CompareExchange(ref _methodImplementations, GetMethodImplementations(), null); } return _methodImplementations; } } public ClassLayout? ClassLayout { get { return _classLayout.Value; } set { _classLayout.Value = value; } } protected TypeDefinition(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _namespace = new LazyVariable((Func)GetNamespace); _name = new LazyVariable((Func)GetName); _baseType = new LazyVariable((Func)GetBaseType); _declaringType = new LazyVariable((Func)GetDeclaringType); _classLayout = new LazyVariable((Func)GetClassLayout); } public TypeDefinition(Utf8String? ns, Utf8String? name, TypeAttributes attributes) : this(ns, name, attributes, null) { }//IL_0003: Unknown result type (might be due to invalid IL or missing references) public TypeDefinition(Utf8String? ns, Utf8String? name, TypeAttributes attributes, ITypeDefOrRef? baseType) : this(new MetadataToken((TableIndex)2, 0u)) { //IL_0003: 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) Namespace = ns; Name = name; Attributes = attributes; BaseType = baseType; } public bool InheritsFrom(string fullName) { TypeDefinition typeDefinition = this; do { if (typeDefinition.FullName == fullName) { return true; } TypeDefinition typeDefinition2 = typeDefinition; typeDefinition = typeDefinition.BaseType?.Resolve(); if (typeDefinition2 == typeDefinition) { return false; } } while (typeDefinition != null); return false; } public bool Implements(string fullName) { string fullName2 = fullName; TypeDefinition typeDefinition = this; do { if (typeDefinition.Interfaces.Any((InterfaceImplementation @interface) => @interface.Interface?.FullName == fullName2)) { return true; } TypeDefinition typeDefinition2 = typeDefinition; typeDefinition = typeDefinition.BaseType?.Resolve(); if (typeDefinition2 == typeDefinition) { return false; } } while (typeDefinition != null); return false; } ITypeDefOrRef ITypeDescriptor.ToTypeDefOrRef() { return this; } public TypeSignature ToTypeSignature() { return ToTypeSignature(IsValueType); } public TypeSignature ToTypeSignature(bool isValueType) { return (TypeSignature)(((object)Module?.CorLibTypeFactory.FromType(this)) ?? ((object)new TypeDefOrRefSignature(this, isValueType))); } public bool IsImportedInModule(ModuleDefinition module) { return Module == module; } public ITypeDefOrRef ImportWith(ReferenceImporter importer) { return importer.ImportType(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } public bool IsAccessibleFromType(TypeDefinition type) { if (this == type) { return true; } bool flag = new SignatureComparer().Equals(Module, type.Module); if (IsNested) { TypeDefinition declaringType = DeclaringType; if (declaringType == null || !declaringType.IsAccessibleFromType(type)) { return false; } if (!IsNestedPublic && (!flag || !IsNestedAssembly)) { return DeclaringType == type; } return true; } return IsPublic || flag; } public TypeReference ToTypeReference() { IResolutionScope resolutionScope = DeclaringType?.ToTypeReference(); IResolutionScope scope = resolutionScope ?? Module; return new TypeReference(Module, scope, Namespace, Name); } private IResolutionScope? GetDeclaringScope() { if (DeclaringType == null) { return Module; } return DeclaringType.ToTypeReference(); } TypeDefinition ITypeDescriptor.Resolve() { return this; } IMemberDefinition IMemberDescriptor.Resolve() { return this; } public TypeSignature? GetEnumUnderlyingType() { if (!IsEnum) { throw new InvalidOperationException("Type is not an enum."); } foreach (FieldDefinition field in Fields) { if (!field.IsLiteral && !field.IsStatic && field.Signature != null) { return field.Signature.FieldType; } } return null; } public MethodDefinition? GetStaticConstructor() { return Methods.FirstOrDefault((MethodDefinition m) => m.IsConstructor && m.IsStatic && m.Parameters.Count == 0); } public MethodDefinition GetOrCreateStaticConstructor() { return GetOrCreateStaticConstructor(Module); } public MethodDefinition GetOrCreateStaticConstructor(ModuleDefinition? module) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown MethodDefinition methodDefinition = GetStaticConstructor(); if (methodDefinition == null) { if (module == null) { throw new ArgumentNullException("module"); } methodDefinition = new MethodDefinition(Utf8String.op_Implicit(".cctor"), (MethodAttributes)6161, MethodSignature.CreateStatic(module.CorLibTypeFactory.Void)); methodDefinition.CilMethodBody = new CilMethodBody(methodDefinition); methodDefinition.CilMethodBody.Instructions.Add(new CilInstruction(0, CilOpCodes.Ret)); Methods.Insert(0, methodDefinition); } return methodDefinition; } protected virtual Utf8String? GetNamespace() { return null; } protected virtual Utf8String? GetName() { return null; } protected virtual ITypeDefOrRef? GetBaseType() { return null; } protected virtual IList GetNestedTypes() { return (IList)new OwnedCollection(this); } protected virtual TypeDefinition? GetDeclaringType() { return null; } protected virtual IList GetFields() { return (IList)new OwnedCollection(this); } protected virtual IList GetMethods() { return (IList)new OwnedCollection(this); } protected virtual IList GetProperties() { return (IList)new OwnedCollection(this); } protected virtual IList GetEvents() { return (IList)new OwnedCollection(this); } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } protected virtual IList GetSecurityDeclarations() { return (IList)new OwnedCollection((IHasSecurityDeclaration)this); } protected virtual IList GetGenericParameters() { return (IList)new OwnedCollection((IHasGenericParameters)this); } protected virtual IList GetInterfaces() { return (IList)new OwnedCollection(this); } protected virtual IList GetMethodImplementations() { return new List(); } protected virtual ClassLayout? GetClassLayout() { return null; } public override string ToString() { return FullName; } } public static class TypeDescriptorExtensions { public static bool IsTypeOf(this ITypeDescriptor type, string? ns, string? name) { if (type.Name == name) { return type.Namespace == ns; } return false; } public static bool IsTypeOfUtf8(this ITypeDefOrRef type, Utf8String? ns, Utf8String? name) { if (type.Name == name) { return type.Namespace == ns; } return false; } public static bool IsTypeOfUtf8(this ExportedType type, Utf8String? ns, Utf8String? name) { if (type.Name == name) { return type.Namespace == ns; } return false; } public static SzArrayTypeSignature MakeSzArrayType(this ITypeDescriptor type) { return new SzArrayTypeSignature(type.ToTypeSignature()); } public static ArrayTypeSignature MakeArrayType(this ITypeDescriptor type, int dimensionCount) { return new ArrayTypeSignature(type.ToTypeSignature(), dimensionCount); } public static ArrayTypeSignature MakeArrayType(this ITypeDescriptor type, params ArrayDimension[] dimensions) { return new ArrayTypeSignature(type.ToTypeSignature(), dimensions); } public static ByReferenceTypeSignature MakeByReferenceType(this ITypeDescriptor type) { return new ByReferenceTypeSignature(type.ToTypeSignature()); } public static PinnedTypeSignature MakePinnedType(this ITypeDescriptor type) { return new PinnedTypeSignature(type.ToTypeSignature()); } public static PointerTypeSignature MakePointerType(this ITypeDescriptor type) { return new PointerTypeSignature(type.ToTypeSignature()); } public static CustomModifierTypeSignature MakeModifierType(this ITypeDescriptor type, ITypeDefOrRef modifierType, bool isRequired) { return new CustomModifierTypeSignature(modifierType, isRequired, type.ToTypeSignature()); } public static GenericInstanceTypeSignature MakeGenericInstanceType(this ITypeDescriptor type, params TypeSignature[] typeArguments) { return type.MakeGenericInstanceType(type.IsValueType, typeArguments); } public static GenericInstanceTypeSignature MakeGenericInstanceType(this ITypeDescriptor type, bool isValueType, params TypeSignature[] typeArguments) { return new GenericInstanceTypeSignature(type.ToTypeDefOrRef(), isValueType, typeArguments); } public static TypeReference CreateTypeReference(this IResolutionScope scope, string? ns, string name) { return new TypeReference(scope, Utf8String.op_Implicit(ns), Utf8String.op_Implicit(name)); } public static TypeReference CreateTypeReference(this ITypeDefOrRef declaringType, string nestedTypeName) { TypeReference scope; if (!(declaringType is TypeReference typeReference)) { if (!(declaringType is TypeDefinition typeDefinition)) { throw new ArgumentOutOfRangeException(); } scope = typeDefinition.ToTypeReference(); } else { scope = typeReference; } return new TypeReference(scope, null, Utf8String.op_Implicit(nestedTypeName)); } public static MemberReference CreateMemberReference(this IMemberRefParent parent, string memberName, MemberSignature signature) { return new MemberReference(parent, Utf8String.op_Implicit(memberName), signature); } } public class TypeReference : MetadataMember, ITypeDefOrRef, ITypeDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMemberRefParent, IMetadataMember, IHasCustomAttribute, IResolutionScope { private readonly LazyVariable _name; private readonly LazyVariable _namespace; private readonly LazyVariable _scope; private IList? _customAttributes; public Utf8String? Name { get { return _name.Value; } set { _name.Value = value; } } string? INameProvider.Name => Utf8String.op_Implicit(Name); public Utf8String? Namespace { get { return _namespace.Value; } set { _namespace.Value = value; } } string? ITypeDescriptor.Namespace => Utf8String.op_Implicit(Namespace); public string FullName => MemberNameGenerator.GetTypeFullName(this); public IResolutionScope? Scope { get { return _scope.Value; } set { _scope.Value = value; } } public bool IsValueType => Resolve()?.IsValueType ?? false; public ModuleDefinition? Module { get; protected set; } public ITypeDefOrRef? DeclaringType => Scope as ITypeDefOrRef; ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected TypeReference(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _name = new LazyVariable((Func)GetName); _namespace = new LazyVariable((Func)GetNamespace); _scope = new LazyVariable((Func)GetScope); } public TypeReference(IResolutionScope? scope, Utf8String? ns, Utf8String? name) : this(new MetadataToken((TableIndex)1, 0u)) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) _scope.Value = scope; Namespace = ns; Name = name; } public TypeReference(ModuleDefinition? module, IResolutionScope? scope, Utf8String? ns, Utf8String? name) : this(new MetadataToken((TableIndex)1, 0u)) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) _scope.Value = scope; Module = module; Namespace = ns; Name = name; } AssemblyDescriptor? IResolutionScope.GetAssembly() { return Scope?.GetAssembly(); } ITypeDefOrRef ITypeDescriptor.ToTypeDefOrRef() { return this; } public TypeSignature ToTypeSignature() { return ToTypeSignature(IsValueType); } public TypeSignature ToTypeSignature(bool isValueType) { return (TypeSignature)(((object)Module?.CorLibTypeFactory.FromType(this)) ?? ((object)new TypeDefOrRefSignature(this, isValueType))); } public bool IsImportedInModule(ModuleDefinition module) { return Module == module; } public ITypeDefOrRef ImportWith(ReferenceImporter importer) { return importer.ImportType(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } public TypeDefinition? Resolve() { return Module?.MetadataResolver.ResolveType(this); } IMemberDefinition? IMemberDescriptor.Resolve() { return Resolve(); } protected virtual Utf8String? GetName() { return null; } protected virtual Utf8String? GetNamespace() { return null; } protected virtual IResolutionScope? GetScope() { return null; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } public override string ToString() { return FullName; } } public class TypeSpecification : MetadataMember, ITypeDefOrRef, ITypeDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMemberRefParent, IMetadataMember, IHasCustomAttribute { private readonly LazyVariable _signature; private IList? _customAttributes; public TypeSignature? Signature { get { return _signature.Value; } set { _signature.Value = value; } } public Utf8String Name => Utf8String.op_Implicit(Signature?.Name ?? "<>"); string INameProvider.Name => Utf8String.op_Implicit(Name); public Utf8String? Namespace => Utf8String.op_Implicit(Signature?.Namespace); string? ITypeDescriptor.Namespace => Utf8String.op_Implicit(Namespace); public string FullName => MemberNameGenerator.GetTypeFullName(this); public ModuleDefinition? Module => Signature?.Module; public IResolutionScope? Scope => Signature?.Scope; public ITypeDefOrRef? DeclaringType => Signature?.DeclaringType as ITypeDefOrRef; ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType; public bool IsValueType => Signature?.IsValueType ?? false; public IList CustomAttributes { get { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null); } return _customAttributes; } } protected TypeSpecification(MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) _signature = new LazyVariable((Func)GetSignature); } public TypeSpecification(TypeSignature? signature) : this(new MetadataToken((TableIndex)27, 0u)) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) Signature = signature; } ITypeDefOrRef ITypeDescriptor.ToTypeDefOrRef() { return this; } public TypeSignature ToTypeSignature() { return Signature ?? throw new ArgumentException("Signature embedded into the type specification is null."); } public TypeSignature ToTypeSignature(bool isValueType) { return ToTypeSignature(); } public bool IsImportedInModule(ModuleDefinition module) { return Signature?.IsImportedInModule(module) ?? false; } public ITypeDefOrRef ImportWith(ReferenceImporter importer) { return (TypeSpecification)importer.ImportType(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } public TypeDefinition? Resolve() { return Module?.MetadataResolver.ResolveType(this); } IMemberDefinition? IMemberDescriptor.Resolve() { return Resolve(); } protected virtual TypeSignature? GetSignature() { return null; } public override string ToString() { return FullName; } protected virtual IList GetCustomAttributes() { return (IList)new OwnedCollection((IHasCustomAttribute)this); } } public readonly struct UnmanagedExportInfo { public uint? Ordinal { get; } public string? Name { get; } [MemberNotNullWhen(true, "Ordinal")] public bool HasFixedOrdinal { [MemberNotNullWhen(true, "Ordinal")] get { return Ordinal.HasValue; } } [MemberNotNullWhen(false, "Name")] public bool IsByOrdinal { [MemberNotNullWhen(false, "Name")] get { return Name == null; } } [MemberNotNullWhen(true, "Name")] public bool IsByName { [MemberNotNullWhen(true, "Name")] get { return Name != null; } } public VTableType VTableType { get; } public UnmanagedExportInfo(uint ordinal, VTableType vTableType) { //IL_000d: 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) Ordinal = ordinal; VTableType = vTableType; Name = null; } public UnmanagedExportInfo(string name, VTableType vTableType) { //IL_0014: 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) Ordinal = null; Name = name; VTableType = vTableType; } public UnmanagedExportInfo(uint ordinal, string name, VTableType vTableType) { //IL_0014: 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) Ordinal = ordinal; Name = name; VTableType = vTableType; } } } namespace AsmResolver.DotNet.Signatures { public struct BlobReaderContext { private Stack? _traversedTokens; public ModuleReaderContext ReaderContext { get; } public ITypeSignatureResolver TypeSignatureResolver { get; } public BlobReaderContext(ModuleReaderContext readerContext) : this(readerContext, PhysicalTypeSignatureResolver.Instance) { } public BlobReaderContext(ModuleReaderContext readerContext, ITypeSignatureResolver resolver) { ReaderContext = readerContext; TypeSignatureResolver = resolver; _traversedTokens = null; } public bool StepInToken(MetadataToken token) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (_traversedTokens == null) { _traversedTokens = new Stack(); } else if (_traversedTokens.Contains(token)) { return false; } _traversedTokens.Push(token); return true; } public void StepOutToken() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (_traversedTokens == null) { throw new InvalidOperationException(); } _traversedTokens.Pop(); } } public readonly struct BlobSerializationContext { public IBinaryStreamWriter Writer { get; } public ITypeCodedIndexProvider IndexProvider { get; } public IErrorListener ErrorListener { get; } public BlobSerializationContext(IBinaryStreamWriter writer, ITypeCodedIndexProvider indexProvider, IErrorListener errorListener) { Writer = writer ?? throw new ArgumentNullException("writer"); IndexProvider = indexProvider ?? throw new ArgumentNullException("indexProvider"); ErrorListener = errorListener ?? throw new ArgumentNullException("errorListener"); } } public abstract class BlobSignature { public abstract void Write(in BlobSerializationContext context); public StandAloneSignature MakeStandAloneSignature() { return new StandAloneSignature(this); } } public sealed class BoxedArgument { public TypeSignature Type { get; } public object? Value { get; } public BoxedArgument(TypeSignature type, object? value) { Type = type ?? throw new ArgumentNullException("type"); Value = value; } private bool Equals(BoxedArgument other) { if (object.Equals(Type, other.Type)) { return object.Equals(Value, other.Value); } return false; } public override bool Equals(object? obj) { if (this != obj) { if (obj is BoxedArgument other) { return Equals(other); } return false; } return true; } public override int GetHashCode() { return (Type.GetHashCode() * 397) ^ ((Value != null) ? Value.GetHashCode() : 0); } public override string ToString() { return $"({Type}) {Value ?? "null"}"; } } [Flags] public enum CallingConventionAttributes : byte { Default = 0, C = 1, StdCall = 2, ThisCall = 3, FastCall = 4, VarArg = 5, Field = 6, Local = 7, Property = 8, Unmanaged = 9, GenericInstance = 0xA, Generic = 0x10, HasThis = 0x20, ExplicitThis = 0x40, Sentinel = 0x41 } public abstract class CallingConventionSignature : ExtendableBlobSignature, IImportable { private const CallingConventionAttributes SignatureTypeMask = CallingConventionAttributes.Local | CallingConventionAttributes.Property; public CallingConventionAttributes Attributes { get; set; } public bool IsMethod => (int)(Attributes & (CallingConventionAttributes.Local | CallingConventionAttributes.Property)) <= 5; public bool IsField => (Attributes & (CallingConventionAttributes.Local | CallingConventionAttributes.Property)) == CallingConventionAttributes.Field; public bool IsLocal => (Attributes & (CallingConventionAttributes.Local | CallingConventionAttributes.Property)) == CallingConventionAttributes.Local; public bool IsGenericInstance => (Attributes & (CallingConventionAttributes.Local | CallingConventionAttributes.Property)) == CallingConventionAttributes.GenericInstance; public bool IsGeneric { get { return (Attributes & CallingConventionAttributes.Generic) != 0; } set { Attributes = (Attributes & ~CallingConventionAttributes.Generic) | (value ? CallingConventionAttributes.Generic : CallingConventionAttributes.Default); } } public bool HasThis { get { return (Attributes & CallingConventionAttributes.HasThis) != 0; } set { Attributes = (Attributes & ~CallingConventionAttributes.HasThis) | (value ? CallingConventionAttributes.HasThis : CallingConventionAttributes.Default); } } public bool ExplicitThis { get { return (Attributes & CallingConventionAttributes.ExplicitThis) != 0; } set { Attributes = (Attributes & ~CallingConventionAttributes.ExplicitThis) | (value ? CallingConventionAttributes.ExplicitThis : CallingConventionAttributes.Default); } } public bool IsSentinel { get { return (Attributes & CallingConventionAttributes.Sentinel) != 0; } set { Attributes = (Attributes & ~CallingConventionAttributes.Sentinel) | (value ? CallingConventionAttributes.Sentinel : CallingConventionAttributes.Default); } } public static CallingConventionSignature? FromReader(ref BlobReaderContext context, ref BinaryStreamReader reader, bool readToEnd = true) { CallingConventionSignature callingConventionSignature = ReadSignature(ref context, ref reader); if (readToEnd) { byte[] extraData = ((BinaryStreamReader)(ref reader)).ReadToEnd(); if (callingConventionSignature != null) { callingConventionSignature.ExtraData = extraData; } } return callingConventionSignature; } private static CallingConventionSignature? ReadSignature(ref BlobReaderContext context, ref BinaryStreamReader reader) { byte b = ((BinaryStreamReader)(ref reader)).ReadByte(); ulong offset = ((BinaryStreamReader)(ref reader)).Offset; ((BinaryStreamReader)(ref reader)).Offset = offset - 1; switch ((CallingConventionAttributes)(b & 0xF)) { case CallingConventionAttributes.Default: case CallingConventionAttributes.C: case CallingConventionAttributes.StdCall: case CallingConventionAttributes.ThisCall: case CallingConventionAttributes.FastCall: case CallingConventionAttributes.VarArg: case CallingConventionAttributes.Unmanaged: case CallingConventionAttributes.ExplicitThis: return MethodSignature.FromReader(ref context, ref reader); case CallingConventionAttributes.Property: return PropertySignature.FromReader(ref context, ref reader); case CallingConventionAttributes.Local: return LocalVariablesSignature.FromReader(ref context, ref reader); case CallingConventionAttributes.GenericInstance: return GenericInstanceMethodSignature.FromReader(ref context, ref reader); case CallingConventionAttributes.Field: return FieldSignature.FromReader(ref context, ref reader); default: throw new NotSupportedException($"Invalid or unsupported calling convention signature header {b:X2}."); } } protected CallingConventionSignature(CallingConventionAttributes attributes) { Attributes = attributes; } public abstract bool IsImportedInModule(ModuleDefinition module); protected abstract CallingConventionSignature ImportWithInternal(ReferenceImporter importer); IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWithInternal(importer); } } public class CustomAttributeArgument { public TypeSignature ArgumentType { get; set; } public object? Element { get { if (Elements.Count <= 0) { return null; } return Elements[0]; } } public IList Elements { get; } public bool IsNullArray { get; set; } public static CustomAttributeArgument FromReader(in BlobReaderContext context, TypeSignature argumentType, ref BinaryStreamReader reader) { CustomAttributeArgumentReader customAttributeArgumentReader = CustomAttributeArgumentReader.Create(); customAttributeArgumentReader.ReadValue(in context, ref reader, argumentType); return new CustomAttributeArgument(argumentType, customAttributeArgumentReader.Elements) { IsNullArray = customAttributeArgumentReader.IsNullArray }; } public CustomAttributeArgument(TypeSignature argumentType) { ArgumentType = argumentType ?? throw new ArgumentNullException("argumentType"); Elements = new List(); } public CustomAttributeArgument(TypeSignature argumentType, object? value) { ArgumentType = argumentType ?? throw new ArgumentNullException("argumentType"); Elements = new List(1) { value }; } public CustomAttributeArgument(TypeSignature argumentType, IEnumerable elements) { ArgumentType = argumentType ?? throw new ArgumentNullException("argumentType"); Elements = new List(elements); } public CustomAttributeArgument(TypeSignature argumentType, params object?[] elements) { ArgumentType = argumentType ?? throw new ArgumentNullException("argumentType"); Elements = new List(elements); } public override string ToString() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Invalid comparison between Unknown and I4 if (IsNullArray) { return "null"; } return ElementToString(((int)ArgumentType.ElementType == 29) ? Elements : Element); } private static string ElementToString(object? element) { if (element != null) { if (!(element is IList source)) { if (element is string text) { return Extensions.CreateEscapedString(text); } return element.ToString() ?? string.Empty; } return "{" + string.Join(", ", source.Select(ElementToString)) + "}"; } return "null"; } public void Write(BlobSerializationContext context) { new CustomAttributeArgumentWriter(context).WriteArgument(this); } } public enum CustomAttributeArgumentMemberType : byte { Field = 83, Property } internal struct CustomAttributeArgumentReader { public IList Elements { get; } public bool IsNullArray { get; private set; } public static CustomAttributeArgumentReader Create() { return new CustomAttributeArgumentReader(new List()); } public CustomAttributeArgumentReader(IList elements) { Elements = elements; IsNullArray = false; } public void ReadValue(in BlobReaderContext context, ref BinaryStreamReader reader, TypeSignature valueType) { //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_004d: 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_00c6: Expected I4, but got Unknown //IL_033e: 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_0225: Invalid comparison between Unknown and I4 //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Invalid comparison between Unknown and I4 SerializedModuleDefinition parentModule = context.ReaderContext.ParentModule; if (valueType.IsTypeOf("System", "Type")) { string text = Utf8String.op_Implicit(((BinaryStreamReader)(ref reader)).ReadSerString()); TypeSignature item = ((text != null) ? TypeNameParser.Parse(parentModule, text) : null); Elements.Add(item); return; } ElementType elementType = valueType.ElementType; switch (elementType - 2) { default: if ((int)elementType == 85) { goto case 15; } goto case 13; case 0: Elements.Add(((BinaryStreamReader)(ref reader)).ReadByte() == 1); break; case 1: Elements.Add((char)((BinaryStreamReader)(ref reader)).ReadUInt16()); break; case 10: Elements.Add(((BinaryStreamReader)(ref reader)).ReadSingle()); break; case 11: Elements.Add(((BinaryStreamReader)(ref reader)).ReadDouble()); break; case 2: Elements.Add(((BinaryStreamReader)(ref reader)).ReadSByte()); break; case 4: Elements.Add(((BinaryStreamReader)(ref reader)).ReadInt16()); break; case 6: Elements.Add(((BinaryStreamReader)(ref reader)).ReadInt32()); break; case 8: Elements.Add(((BinaryStreamReader)(ref reader)).ReadInt64()); break; case 3: Elements.Add(((BinaryStreamReader)(ref reader)).ReadByte()); break; case 5: Elements.Add(((BinaryStreamReader)(ref reader)).ReadUInt16()); break; case 7: Elements.Add(((BinaryStreamReader)(ref reader)).ReadUInt32()); break; case 9: Elements.Add(((BinaryStreamReader)(ref reader)).ReadUInt64()); break; case 12: Elements.Add(((BinaryStreamReader)(ref reader)).ReadSerString()); break; case 26: { TypeSignature typeSignature = TypeSignature.ReadFieldOrPropType(in context, ref reader); CustomAttributeArgumentReader customAttributeArgumentReader = Create(); customAttributeArgumentReader.ReadValue(in context, ref reader, typeSignature); Elements.Add(new BoxedArgument(typeSignature, ((int)typeSignature.ElementType == 29) ? customAttributeArgumentReader.Elements.ToArray() : customAttributeArgumentReader.Elements[0])); break; } case 27: { TypeSignature baseType = ((SzArrayTypeSignature)valueType).BaseType; uint num = (((BinaryStreamReader)(ref reader)).CanRead(4u) ? ((BinaryStreamReader)(ref reader)).ReadUInt32() : uint.MaxValue); IsNullArray = num == uint.MaxValue; if (!IsNullArray) { for (uint num2 = 0u; num2 < num; num2++) { ReadValue(in context, ref reader, baseType); } } break; } case 15: case 16: { TypeDefinition typeDefinition = parentModule.MetadataResolver.ResolveType(valueType); TypeSignature typeSignature2 = null; if (typeDefinition != null && typeDefinition.IsEnum) { typeSignature2 = typeDefinition.GetEnumUnderlyingType(); } if (typeSignature2 == null) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, $"Underlying enum type {valueType} could not be resolved. Assuming System.Int32 for custom attribute argument."); typeSignature2 = parentModule.CorLibTypeFactory.Int32; } ReadValue(in context, ref reader, typeSignature2); break; } case 13: case 14: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: ErrorListenerExtensions.NotSupported((IErrorListener)(object)context.ReaderContext, $"Unsupported element type {valueType.ElementType} in custom attribute argument."); Elements.Add(null); break; } } } internal readonly struct CustomAttributeArgumentWriter { private readonly BlobSerializationContext _context; public CustomAttributeArgumentWriter(BlobSerializationContext context) { _context = context; } public void WriteArgument(CustomAttributeArgument argument) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 TypeSignature argumentType = argument.ArgumentType; if ((int)argumentType.ElementType != 29) { WriteElement(argumentType, argument.Element); } else { WriteArrayElement((SzArrayTypeSignature)argumentType, argument.Elements, argument.IsNullArray); } } private void WriteArrayElement(SzArrayTypeSignature szArrayType, IList elements, bool isNullArray) { IBinaryStreamWriter writer = _context.Writer; if (isNullArray) { writer.WriteUInt32(uint.MaxValue); return; } TypeSignature baseType = szArrayType.BaseType; writer.WriteUInt32((uint)elements.Count); for (int i = 0; i < elements.Count; i++) { WriteElement(baseType, elements[i]); } } private void WriteElement(TypeSignature argumentType, object? element) { if (element == null) { WriteNullElement(argumentType); } else { WriteNonNullElement(argumentType, element); } } private void WriteNullElement(TypeSignature argumentType) { //IL_0027: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Invalid comparison between Unknown and I4 //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Invalid comparison between Unknown and I4 //IL_0037: 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_003c: Invalid comparison between Unknown and I4 //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Invalid comparison between Unknown and I4 IBinaryStreamWriter writer = _context.Writer; if (argumentType.IsTypeOf("System", "Type")) { IOExtensions.WriteSerString(writer, (string)null); return; } ElementType elementType = argumentType.ElementType; if ((int)elementType <= 18) { if ((int)elementType == 14) { IOExtensions.WriteSerString(writer, (Utf8String)null); return; } if (elementType - 17 <= 1) { goto IL_0088; } } else { if ((int)elementType == 28) { TypeSignature.WriteFieldOrPropType(_context, argumentType.Module.CorLibTypeFactory.String); return; } if ((int)elementType == 29) { WriteArrayElement((SzArrayTypeSignature)argumentType, Array.Empty(), isNullArray: true); return; } if ((int)elementType == 85) { goto IL_0088; } } ErrorListenerExtensions.NotSupported(_context.ErrorListener, "Cannot write a null value for a non-nullable argument type."); return; IL_0088: WriteEnumValue(argumentType, null); } private void WriteNonNullElement(TypeSignature argumentType, object element) { //IL_0031: 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: 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_00b1: Expected I4, but got Unknown //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Invalid comparison between Unknown and I4 IBinaryStreamWriter writer = _context.Writer; if (argumentType.IsTypeOf("System", "Type")) { IOExtensions.WriteSerString(writer, TypeNameBuilder.GetAssemblyQualifiedName((TypeSignature)element)); return; } ElementType elementType = argumentType.ElementType; switch (elementType - 2) { default: if ((int)elementType != 85) { break; } goto case 15; case 0: writer.WriteByte((byte)(((bool)element) ? 1u : 0u)); return; case 1: writer.WriteUInt16((ushort)(char)element); return; case 2: writer.WriteSByte((sbyte)element); return; case 3: writer.WriteByte((byte)element); return; case 4: writer.WriteInt16((short)element); return; case 5: writer.WriteUInt16((ushort)element); return; case 6: writer.WriteInt32((int)element); return; case 7: writer.WriteUInt32((uint)element); return; case 8: writer.WriteInt64((long)element); return; case 9: writer.WriteUInt64((ulong)element); return; case 10: writer.WriteSingle((float)element); return; case 11: writer.WriteDouble((double)element); return; case 12: { if (element is string text) { IOExtensions.WriteSerString(writer, text); return; } Utf8String val = (Utf8String)((element is Utf8String) ? element : null); if (val != null) { IOExtensions.WriteSerString(writer, val); return; } break; } case 26: { TypeSignature typeSignature; object element2; if (element is BoxedArgument boxedArgument) { typeSignature = boxedArgument.Type; element2 = boxedArgument.Value; } else { ErrorListenerExtensions.NotSupported(_context.ErrorListener, "Object elements in a custom attribute signature should be either 'null' or an instance of BoxedArgument."); typeSignature = argumentType.Module.CorLibTypeFactory.String; element2 = null; } TypeSignature.WriteFieldOrPropType(_context, typeSignature); WriteElement(typeSignature, element2); return; } case 27: WriteArrayElement((SzArrayTypeSignature)argumentType, (element as IList) ?? Array.Empty(), isNullArray: false); return; case 15: case 16: WriteEnumValue(argumentType, element); return; case 13: case 14: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: break; } ErrorListenerExtensions.NotSupported(_context.ErrorListener, "Invalid or unsupported argument type " + argumentType.FullName + "."); } private void WriteEnumValue(TypeSignature argumentType, object? element) { TypeDefinition typeDefinition = argumentType.Resolve(); if (typeDefinition != null && typeDefinition.IsEnum) { TypeSignature enumUnderlyingType = typeDefinition.GetEnumUnderlyingType(); if (enumUnderlyingType != null) { WriteElement(enumUnderlyingType, element); return; } } if (element == null) { _context.ErrorListener.RegisterException((Exception)new NotSupportedException("The element of the enum-typed argument is null.")); element = 0; } CorLibTypeFactory corLibTypeFactory = argumentType.Module.CorLibTypeFactory; TypeSignature typeSignature = Type.GetTypeCode(element.GetType()) switch { TypeCode.Boolean => corLibTypeFactory.Boolean, TypeCode.Byte => corLibTypeFactory.Byte, TypeCode.Char => corLibTypeFactory.Char, TypeCode.Int16 => corLibTypeFactory.Int16, TypeCode.Int32 => corLibTypeFactory.Int32, TypeCode.Int64 => corLibTypeFactory.Int64, TypeCode.SByte => corLibTypeFactory.SByte, TypeCode.UInt16 => corLibTypeFactory.UInt16, TypeCode.UInt32 => corLibTypeFactory.UInt32, TypeCode.UInt64 => corLibTypeFactory.UInt64, _ => ErrorListenerExtensions.NotSupportedAndReturn(_context.ErrorListener, "Type " + argumentType.SafeToString() + " is a non-integer enum type."), }; if (typeSignature != null) { WriteElement(typeSignature, element); } } } public class CustomAttributeNamedArgument { public CustomAttributeArgumentMemberType MemberType { get; set; } public Utf8String? MemberName { get; set; } public TypeSignature ArgumentType { get; set; } public CustomAttributeArgument Argument { get; set; } public CustomAttributeNamedArgument(CustomAttributeArgumentMemberType memberType, Utf8String? memberName, TypeSignature argumentType, CustomAttributeArgument argument) { MemberType = memberType; MemberName = memberName; ArgumentType = argumentType; Argument = argument; } public static CustomAttributeNamedArgument FromReader(in BlobReaderContext context, ref BinaryStreamReader reader) { byte memberType = ((BinaryStreamReader)(ref reader)).ReadByte(); TypeSignature argumentType = TypeSignature.ReadFieldOrPropType(in context, ref reader); Utf8String memberName = ((BinaryStreamReader)(ref reader)).ReadSerString(); CustomAttributeArgument argument = CustomAttributeArgument.FromReader(in context, argumentType, ref reader); return new CustomAttributeNamedArgument((CustomAttributeArgumentMemberType)memberType, memberName, argumentType, argument); } public override string ToString() { return $"{MemberName} = {Argument}"; } public void Write(BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)MemberType); TypeSignature.WriteFieldOrPropType(context, ArgumentType); IOExtensions.WriteSerString(writer, MemberName); Argument.Write(context); } } public class CustomAttributeSignature : ExtendableBlobSignature { protected const ushort CustomAttributeSignaturePrologue = 1; private List? _fixedArguments; private List? _namedArguments; public IList FixedArguments { get { EnsureIsInitialized(); return _fixedArguments; } } public IList NamedArguments { get { EnsureIsInitialized(); return _namedArguments; } } [MemberNotNullWhen(true, "_fixedArguments")] [MemberNotNullWhen(true, "_namedArguments")] protected bool IsInitialized { [MemberNotNullWhen(true, "_fixedArguments")] [MemberNotNullWhen(true, "_namedArguments")] get { if (_fixedArguments != null) { return _namedArguments != null; } return false; } } public CustomAttributeSignature() { } public CustomAttributeSignature(params CustomAttributeArgument[] fixedArguments) : this(fixedArguments, Enumerable.Empty()) { } public CustomAttributeSignature(IEnumerable fixedArguments) : this(fixedArguments, Enumerable.Empty()) { } public CustomAttributeSignature(IEnumerable fixedArguments, IEnumerable namedArguments) { _fixedArguments = new List(fixedArguments); _namedArguments = new List(namedArguments); } public static CustomAttributeSignature FromReader(in BlobReaderContext context, ICustomAttributeType ctor, in BinaryStreamReader reader) { GenericContext genericContext = GenericContext.FromMethod(ctor); IList fixedArgTypes = ctor.Signature?.ParameterTypes ?? Array.Empty(); return new SerializedCustomAttributeSignature(in context, fixedArgTypes, in genericContext, in reader); } [MemberNotNull("_fixedArguments")] [MemberNotNull("_namedArguments")] protected void EnsureIsInitialized() { if (IsInitialized) { return; } List fixedArguments = new List(); List namedArguments = new List(); Initialize(fixedArguments, namedArguments); lock (this) { if (!IsInitialized) { _fixedArguments = fixedArguments; _namedArguments = namedArguments; } } } protected virtual void Initialize(IList fixedArguments, IList namedArguments) { } public override string ToString() { return $"(Fixed: {{{string.Join(", ", FixedArguments)}}}, Named: {{{string.Join(", ", NamedArguments)}}})"; } protected override void WriteContents(in BlobSerializationContext context) { context.Writer.WriteUInt16((ushort)1); for (int i = 0; i < FixedArguments.Count; i++) { FixedArguments[i].Write(context); } context.Writer.WriteUInt16((ushort)NamedArguments.Count); for (int j = 0; j < NamedArguments.Count; j++) { NamedArguments[j].Write(context); } } public bool IsCompatibleWith(ICustomAttributeType constructor) { return IsCompatibleWith(constructor, (IErrorListener)(object)EmptyErrorListener.Instance); } public virtual bool IsCompatibleWith(ICustomAttributeType constructor, IErrorListener listener) { MethodSignature signature = constructor.Signature; int num = signature?.ParameterTypes.Count ?? 0; if (num != FixedArguments.Count) { listener.MetadataBuilder($"Custom attribute constructor {constructor.SafeToString()} expects {num} arguments but the signature provided {FixedArguments.Count} arguments."); return false; } if (signature != null && signature.SentinelParameterTypes.Count > 0) { listener.MetadataBuilder("Custom attribute constructor " + constructor.SafeToString() + " defines sentinel parameters."); return false; } return true; } } public class DataBlobSignature : BlobSignature { public byte[] Data { get; set; } public static DataBlobSignature FromReader(ref BinaryStreamReader reader) { return new DataBlobSignature(((BinaryStreamReader)(ref reader)).ReadToEnd()); } public DataBlobSignature(byte[] data) { Data = data ?? throw new ArgumentNullException("data"); } public object InterpretData(ElementType elementType) { //IL_000d: 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_0049: Expected I4, but got Unknown BinaryStreamReader val = default(BinaryStreamReader); ((BinaryStreamReader)(ref val))..ctor(Data); return (elementType - 2) switch { 0 => ((BinaryStreamReader)(ref val)).ReadByte() != 0, 1 => (char)((BinaryStreamReader)(ref val)).ReadUInt16(), 2 => ((BinaryStreamReader)(ref val)).ReadSByte(), 3 => ((BinaryStreamReader)(ref val)).ReadByte(), 4 => ((BinaryStreamReader)(ref val)).ReadInt16(), 5 => ((BinaryStreamReader)(ref val)).ReadUInt16(), 6 => ((BinaryStreamReader)(ref val)).ReadInt32(), 7 => ((BinaryStreamReader)(ref val)).ReadUInt32(), 8 => ((BinaryStreamReader)(ref val)).ReadInt64(), 9 => ((BinaryStreamReader)(ref val)).ReadUInt64(), 10 => ((BinaryStreamReader)(ref val)).ReadSingle(), 11 => ((BinaryStreamReader)(ref val)).ReadDouble(), 12 => Encoding.Unicode.GetString(((BinaryStreamReader)(ref val)).ReadToEnd()), _ => throw new ArgumentOutOfRangeException("elementType"), }; } public override void Write(in BlobSerializationContext context) { IOExtensions.WriteBytes(context.Writer, Data); } public static DataBlobSignature FromValue(bool value) { return new DataBlobSignature(new byte[1] { (byte)(value ? 1u : 0u) }); } public static DataBlobSignature FromValue(char value) { byte[] array = new byte[2]; BinaryPrimitives.WriteUInt16LittleEndian(array, value); return new DataBlobSignature(array); } public static DataBlobSignature FromValue(byte value) { return new DataBlobSignature(new byte[1] { value }); } public static DataBlobSignature FromValue(sbyte value) { return new DataBlobSignature(new byte[1] { (byte)value }); } public static DataBlobSignature FromValue(ushort value) { byte[] array = new byte[2]; BinaryPrimitives.WriteUInt16LittleEndian(array, value); return new DataBlobSignature(array); } public static DataBlobSignature FromValue(short value) { byte[] array = new byte[2]; BinaryPrimitives.WriteInt16LittleEndian(array, value); return new DataBlobSignature(array); } public static DataBlobSignature FromValue(uint value) { byte[] array = new byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(array, value); return new DataBlobSignature(array); } public static DataBlobSignature FromValue(int value) { byte[] array = new byte[4]; BinaryPrimitives.WriteInt32LittleEndian(array, value); return new DataBlobSignature(array); } public static DataBlobSignature FromValue(ulong value) { byte[] array = new byte[8]; BinaryPrimitives.WriteUInt64LittleEndian(array, value); return new DataBlobSignature(array); } public static DataBlobSignature FromValue(long value) { byte[] array = new byte[8]; BinaryPrimitives.WriteInt64LittleEndian(array, value); return new DataBlobSignature(array); } public static DataBlobSignature FromValue(float value) { byte[] bytes = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) { Array.Reverse(bytes); } return new DataBlobSignature(bytes); } public static DataBlobSignature FromValue(double value) { byte[] bytes = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) { Array.Reverse(bytes); } return new DataBlobSignature(bytes); } public static DataBlobSignature FromValue(string value) { return new DataBlobSignature(Encoding.Unicode.GetBytes(value)); } } public abstract class ExtendableBlobSignature : BlobSignature { public byte[]? ExtraData { get; set; } public sealed override void Write(in BlobSerializationContext context) { WriteContents(in context); if (ExtraData != null) { IOExtensions.WriteBytes(context.Writer, ExtraData); } } protected abstract void WriteContents(in BlobSerializationContext context); } public class FieldSignature : MemberSignature { public TypeSignature FieldType { get { return base.MemberReturnType; } set { base.MemberReturnType = value; } } [Obsolete("The HasThis bit in field signatures is ignored by the CLR. Use the constructor instead, or when this call is used in an argument of a FieldDefinition constructor, use the overload taking TypeSignature instead.")] public static FieldSignature CreateStatic(TypeSignature fieldType) { return new FieldSignature(CallingConventionAttributes.Field, fieldType); } [Obsolete("The HasThis bit in field signatures is ignored by the CLR. Use the constructor instead, or when this call is used in an argument of a FieldDefinition constructor, use the overload taking TypeSignature instead.")] public static FieldSignature CreateInstance(TypeSignature fieldType) { return new FieldSignature(CallingConventionAttributes.Field | CallingConventionAttributes.HasThis, fieldType); } public static FieldSignature FromReader(ref BlobReaderContext context, ref BinaryStreamReader reader) { return new FieldSignature((CallingConventionAttributes)((BinaryStreamReader)(ref reader)).ReadByte(), TypeSignature.FromReader(ref context, ref reader)); } public FieldSignature(TypeSignature fieldType) : this(CallingConventionAttributes.Field, fieldType) { } public FieldSignature(CallingConventionAttributes attributes, TypeSignature fieldType) : base(attributes | CallingConventionAttributes.Field, fieldType) { } public FieldSignature InstantiateGenericTypes(GenericContext context) { return GenericTypeActivator.Instance.InstantiateFieldSignature(this, context); } protected override void WriteContents(in BlobSerializationContext context) { context.Writer.WriteByte((byte)base.Attributes); FieldType.Write(in context); } public FieldSignature ImportWith(ReferenceImporter importer) { return importer.ImportFieldSignature(this); } protected override CallingConventionSignature ImportWithInternal(ReferenceImporter importer) { return ImportWith(importer); } public override string ToString() { return FieldType.FullName; } } public readonly struct GenericContext : IEquatable { public IGenericArgumentsProvider? Type { get; } public IGenericArgumentsProvider? Method { get; } public bool IsEmpty { get { if (Type == null) { return Method == null; } return false; } } public GenericContext(IGenericArgumentsProvider? type, IGenericArgumentsProvider? method) { Type = type; Method = method; } public GenericContext WithType(IGenericArgumentsProvider type) { return new GenericContext(type, Method); } public GenericContext WithMethod(IGenericArgumentsProvider method) { return new GenericContext(Type, method); } public TypeSignature GetTypeArgument(GenericParameterSignature parameter) { IGenericArgumentsProvider genericArgumentsProvider = parameter.ParameterType switch { GenericParameterType.Type => Type, GenericParameterType.Method => Method, _ => throw new ArgumentOutOfRangeException(), }; if (genericArgumentsProvider == null) { return parameter; } if (parameter.Index >= 0 && parameter.Index < genericArgumentsProvider.TypeArguments.Count) { return genericArgumentsProvider.TypeArguments[parameter.Index]; } throw new ArgumentOutOfRangeException(); } public static GenericContext FromType(TypeSpecification type) { if (type.Signature is GenericInstanceTypeSignature type2) { return new GenericContext(type2, null); } return default(GenericContext); } public static GenericContext FromType(GenericInstanceTypeSignature type) { return new GenericContext(type, null); } public static GenericContext FromType(ITypeDescriptor type) { if (!(type is TypeSpecification type2)) { if (type is GenericInstanceTypeSignature type3) { return FromType(type3); } return default(GenericContext); } return FromType(type2); } public static GenericContext FromMethod(MethodSpecification method) { if (!(method.DeclaringType is TypeSpecification typeSpecification) || !(typeSpecification.Signature is GenericInstanceTypeSignature type)) { return new GenericContext(null, method.Signature); } return new GenericContext(type, method.Signature); } public static GenericContext FromMethod(IMethodDescriptor method) { if (!(method is MethodSpecification method2)) { if (method is MemberReference member) { return FromMember(member); } return default(GenericContext); } return FromMethod(method2); } public static GenericContext FromField(IFieldDescriptor field) { if (field is MemberReference member) { return FromMember(member); } return default(GenericContext); } public static GenericContext FromMember(MemberReference member) { if (member.DeclaringType is TypeSpecification type) { return FromType(type); } return default(GenericContext); } public static GenericContext FromMember(IMemberDescriptor member) { if (!(member is IMethodDescriptor method)) { if (!(member is IFieldDescriptor field)) { if (member is ITypeDescriptor type) { return FromType(type); } return default(GenericContext); } return FromField(field); } return FromMethod(method); } public bool Equals(GenericContext other) { if (object.Equals(Type, other.Type)) { return object.Equals(Method, other.Method); } return false; } public override bool Equals(object? obj) { if (obj is GenericContext other) { return Equals(other); } return false; } public override int GetHashCode() { return ((Type?.GetHashCode() ?? 0) * 397) ^ (Method?.GetHashCode() ?? 0); } } public class GenericInstanceMethodSignature : CallingConventionSignature, IGenericArgumentsProvider { public IList TypeArguments { get; } internal static GenericInstanceMethodSignature? FromReader(ref BlobReaderContext context, ref BinaryStreamReader reader) { if (!((BinaryStreamReader)(ref reader)).CanRead(1u)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Insufficient data for a generic method instance signature."); return null; } CallingConventionAttributes attributes = (CallingConventionAttributes)((BinaryStreamReader)(ref reader)).ReadByte(); uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid number of type arguments in generic method signature."); return new GenericInstanceMethodSignature(attributes); } GenericInstanceMethodSignature genericInstanceMethodSignature = new GenericInstanceMethodSignature(attributes, (int)num); for (int i = 0; i < num; i++) { genericInstanceMethodSignature.TypeArguments.Add(TypeSignature.FromReader(ref context, ref reader)); } return genericInstanceMethodSignature; } public GenericInstanceMethodSignature(CallingConventionAttributes attributes) : this(attributes, Enumerable.Empty()) { } public GenericInstanceMethodSignature(CallingConventionAttributes attributes, int capacity) : base(attributes) { TypeArguments = new List(capacity); } public GenericInstanceMethodSignature(params TypeSignature[] typeArguments) : this(CallingConventionAttributes.GenericInstance, typeArguments) { } public GenericInstanceMethodSignature(IEnumerable typeArguments) : this(CallingConventionAttributes.GenericInstance, typeArguments) { } public GenericInstanceMethodSignature(CallingConventionAttributes attributes, IEnumerable typeArguments) : base(attributes | CallingConventionAttributes.GenericInstance) { TypeArguments = new List(typeArguments); } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)base.Attributes); IOExtensions.WriteCompressedUInt32(writer, (uint)TypeArguments.Count); for (int i = 0; i < TypeArguments.Count; i++) { TypeArguments[i].Write(in context); } } public override bool IsImportedInModule(ModuleDefinition module) { for (int i = 0; i < TypeArguments.Count; i++) { if (!TypeArguments[i].IsImportedInModule(module)) { return false; } } return true; } public GenericInstanceMethodSignature ImportWith(ReferenceImporter importer) { return importer.ImportGenericInstanceMethodSignature(this); } protected override CallingConventionSignature ImportWithInternal(ReferenceImporter importer) { return ImportWith(importer); } public override string ToString() { return "<" + string.Join(", ", TypeArguments) + ">"; } } public interface IGenericArgumentsProvider { IList TypeArguments { get; } } [Serializable] public class InvalidBlobSignatureException : Exception { public BlobSignature Signature { get; } public InvalidBlobSignatureException(BlobSignature signature) : this(signature, "Blob signature is invalid or incomplete.", null) { } public InvalidBlobSignatureException(BlobSignature signature, string message) : this(signature, message, null) { } public InvalidBlobSignatureException(BlobSignature signature, Exception? inner) : this(signature, "Blob signature " + signature.SafeToString() + " is invalid or incomplete.", inner) { } public InvalidBlobSignatureException(BlobSignature signature, string message, Exception? inner) : base(message, inner) { Signature = signature; } } public interface ITypeCodedIndexProvider { uint GetTypeDefOrRefIndex(ITypeDefOrRef type); } public class LocalVariablesSignature : CallingConventionSignature { public IList VariableTypes { get; } public static LocalVariablesSignature FromReader(ref BlobReaderContext context, ref BinaryStreamReader reader) { LocalVariablesSignature localVariablesSignature = new LocalVariablesSignature(); localVariablesSignature.Attributes = (CallingConventionAttributes)((BinaryStreamReader)(ref reader)).ReadByte(); uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid number of local variables in local variable signature."); return localVariablesSignature; } for (int i = 0; i < num; i++) { localVariablesSignature.VariableTypes.Add(TypeSignature.FromReader(ref context, ref reader)); } return localVariablesSignature; } public LocalVariablesSignature() : this(Enumerable.Empty()) { } public LocalVariablesSignature(params TypeSignature[] variableTypes) : this(variableTypes.AsEnumerable()) { } public LocalVariablesSignature(IEnumerable variableTypes) : base(CallingConventionAttributes.Local) { VariableTypes = new List(variableTypes); } public override bool IsImportedInModule(ModuleDefinition module) { for (int i = 0; i < VariableTypes.Count; i++) { if (!VariableTypes[i].IsImportedInModule(module)) { return false; } } return true; } public LocalVariablesSignature ImportWith(ReferenceImporter importer) { return importer.ImportLocalVariablesSignature(this); } protected override CallingConventionSignature ImportWithInternal(ReferenceImporter importer) { return ImportWith(importer); } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)base.Attributes); IOExtensions.WriteCompressedUInt32(writer, (uint)VariableTypes.Count); for (int i = 0; i < VariableTypes.Count; i++) { VariableTypes[i].Write(in context); } } public override string ToString() { return "(" + string.Join(", ", VariableTypes) + ")"; } } public abstract class MemberSignature : CallingConventionSignature { protected TypeSignature MemberReturnType { get; set; } protected MemberSignature(CallingConventionAttributes attributes, TypeSignature memberReturnType) : base(attributes) { MemberReturnType = memberReturnType; } public override bool IsImportedInModule(ModuleDefinition module) { return MemberReturnType.IsImportedInModule(module); } } public class MethodSignature : MethodSignatureBase { public int GenericParameterCount { get; set; } public static MethodSignature FromReader(ref BlobReaderContext context, ref BinaryStreamReader reader) { MethodSignature methodSignature = new MethodSignature((CallingConventionAttributes)((BinaryStreamReader)(ref reader)).ReadByte(), context.ReaderContext.ParentModule.CorLibTypeFactory.Void, Enumerable.Empty()); if (methodSignature.IsGeneric) { uint genericParameterCount = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref genericParameterCount)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid generic parameter count in method signature."); return methodSignature; } methodSignature.GenericParameterCount = (int)genericParameterCount; } methodSignature.ReadParametersAndReturnType(ref context, ref reader); return methodSignature; } public static MethodSignature CreateStatic(TypeSignature returnType) { return new MethodSignature(CallingConventionAttributes.Default, returnType, Enumerable.Empty()); } public static MethodSignature CreateStatic(TypeSignature returnType, params TypeSignature[] parameterTypes) { return new MethodSignature(CallingConventionAttributes.Default, returnType, parameterTypes); } public static MethodSignature CreateStatic(TypeSignature returnType, int genericParameterCount, params TypeSignature[] parameterTypes) { return new MethodSignature((genericParameterCount > 0) ? CallingConventionAttributes.Generic : CallingConventionAttributes.Default, returnType, parameterTypes) { GenericParameterCount = genericParameterCount }; } public static MethodSignature CreateStatic(TypeSignature returnType, IEnumerable parameterTypes) { return new MethodSignature(CallingConventionAttributes.Default, returnType, parameterTypes); } public static MethodSignature CreateStatic(TypeSignature returnType, int genericParameterCount, IEnumerable parameterTypes) { return new MethodSignature((genericParameterCount > 0) ? CallingConventionAttributes.Generic : CallingConventionAttributes.Default, returnType, parameterTypes) { GenericParameterCount = genericParameterCount }; } public static MethodSignature CreateInstance(TypeSignature returnType) { return new MethodSignature(CallingConventionAttributes.HasThis, returnType, Enumerable.Empty()); } public static MethodSignature CreateInstance(TypeSignature returnType, params TypeSignature[] parameterTypes) { return new MethodSignature(CallingConventionAttributes.HasThis, returnType, parameterTypes); } public static MethodSignature CreateInstance(TypeSignature returnType, int genericParameterCount, params TypeSignature[] parameterTypes) { return new MethodSignature((genericParameterCount > 0) ? (CallingConventionAttributes.Generic | CallingConventionAttributes.HasThis) : CallingConventionAttributes.HasThis, returnType, parameterTypes) { GenericParameterCount = genericParameterCount }; } public static MethodSignature CreateInstance(TypeSignature returnType, IEnumerable parameterTypes) { return new MethodSignature(CallingConventionAttributes.HasThis, returnType, parameterTypes); } public static MethodSignature CreateInstance(TypeSignature returnType, int genericParameterCount, IEnumerable parameterTypes) { return new MethodSignature((genericParameterCount > 0) ? (CallingConventionAttributes.Generic | CallingConventionAttributes.HasThis) : CallingConventionAttributes.HasThis, returnType, parameterTypes) { GenericParameterCount = genericParameterCount }; } public MethodSignature(CallingConventionAttributes attributes, TypeSignature returnType, IEnumerable parameterTypes) : base(attributes, returnType, parameterTypes) { } public MethodSignature InstantiateGenericTypes(GenericContext context) { return GenericTypeActivator.Instance.InstantiateMethodSignature(this, context); } public FunctionPointerTypeSignature MakeFunctionPointerType() { return new FunctionPointerTypeSignature(this); } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)base.Attributes); if (base.IsGeneric) { IOExtensions.WriteCompressedUInt32(writer, (uint)GenericParameterCount); } WriteParametersAndReturnType(context); } public override string ToString() { string value = (base.HasThis ? "instance " : string.Empty); string fullName = base.ReturnType.FullName; string value2 = ((GenericParameterCount > 0) ? ("<" + string.Join(", ", new string('?', GenericParameterCount)) + ">") : string.Empty); string value3 = string.Join(", ", base.ParameterTypes); string value4 = ((!base.IsSentinel) ? string.Empty : ((base.ParameterTypes.Count > 0) ? ", ..." : " ...")); return $"{value}{fullName} *{value2}({value3}{value4})"; } public MemberSignature ImportWith(ReferenceImporter importer) { return importer.ImportMethodSignature(this); } protected override CallingConventionSignature ImportWithInternal(ReferenceImporter importer) { return ImportWith(importer); } } public abstract class MethodSignatureBase : MemberSignature { private readonly List _parameterTypes; public IList ParameterTypes => _parameterTypes; public TypeSignature ReturnType { get { return base.MemberReturnType; } set { base.MemberReturnType = value; } } public bool IncludeSentinel { get; set; } public bool ReturnsValue { get { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 TypeSignature typeSignature; for (typeSignature = ReturnType; typeSignature is CustomModifierTypeSignature customModifierTypeSignature; typeSignature = customModifierTypeSignature.BaseType) { } return (int)typeSignature.ElementType != 1; } } public IList SentinelParameterTypes { get; } = new List(); protected MethodSignatureBase(CallingConventionAttributes attributes, TypeSignature memberReturnType, IEnumerable parameterTypes) : base(attributes, memberReturnType) { _parameterTypes = new List(parameterTypes); } public override bool IsImportedInModule(ModuleDefinition module) { if (!ReturnType.IsImportedInModule(module)) { return false; } for (int i = 0; i < ParameterTypes.Count; i++) { if (!ParameterTypes[i].IsImportedInModule(module)) { return false; } } for (int j = 0; j < SentinelParameterTypes.Count; j++) { if (!SentinelParameterTypes[j].IsImportedInModule(module)) { return false; } } return true; } protected void ReadParametersAndReturnType(ref BlobReaderContext context, ref BinaryStreamReader reader) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Invalid comparison between Unknown and I4 uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid number of parameters in signature."); return; } ReturnType = TypeSignature.FromReader(ref context, ref reader); _parameterTypes.Capacity = (int)num; bool flag = false; for (int i = 0; i < num; i++) { TypeSignature typeSignature = TypeSignature.FromReader(ref context, ref reader); if ((int)typeSignature.ElementType == 65) { flag = true; i--; } else if (flag) { SentinelParameterTypes.Add(typeSignature); } else { ParameterTypes.Add(typeSignature); } } } protected void WriteParametersAndReturnType(BlobSerializationContext context) { IOExtensions.WriteCompressedUInt32(context.Writer, (uint)ParameterTypes.Count); ReturnType.Write(in context); for (int i = 0; i < ParameterTypes.Count; i++) { ParameterTypes[i].Write(in context); } if (IncludeSentinel) { context.Writer.WriteByte((byte)65); for (int j = 0; j < SentinelParameterTypes.Count; j++) { SentinelParameterTypes[j].Write(in context); } } } public int GetTotalParameterCount() { int num = ParameterTypes.Count + SentinelParameterTypes.Count; if (base.HasThis || base.ExplicitThis) { num++; } return num; } } public class PropertySignature : MethodSignatureBase { public static PropertySignature? FromReader(ref BlobReaderContext context, ref BinaryStreamReader reader) { CallingConventionAttributes callingConventionAttributes = (CallingConventionAttributes)((BinaryStreamReader)(ref reader)).ReadByte(); if ((callingConventionAttributes & CallingConventionAttributes.Property) == 0) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Input stream does not point to a valid property signature."); return null; } PropertySignature propertySignature = new PropertySignature(callingConventionAttributes, context.ReaderContext.ParentModule.CorLibTypeFactory.Object, Enumerable.Empty()); propertySignature.ReadParametersAndReturnType(ref context, ref reader); return propertySignature; } public static PropertySignature CreateStatic(TypeSignature returnType) { return new PropertySignature(CallingConventionAttributes.Default, returnType, Enumerable.Empty()); } public static PropertySignature CreateStatic(TypeSignature returnType, params TypeSignature[] parameterTypes) { return new PropertySignature(CallingConventionAttributes.Default, returnType, parameterTypes); } public static PropertySignature CreateStatic(TypeSignature returnType, IEnumerable parameterTypes) { return new PropertySignature(CallingConventionAttributes.Default, returnType, parameterTypes); } public static PropertySignature CreateInstance(TypeSignature returnType) { return new PropertySignature(CallingConventionAttributes.HasThis, returnType, Enumerable.Empty()); } public static PropertySignature CreateInstance(TypeSignature returnType, params TypeSignature[] parameterTypes) { return new PropertySignature(CallingConventionAttributes.HasThis, returnType, parameterTypes); } public static PropertySignature CreateInstance(TypeSignature returnType, IEnumerable parameterTypes) { return new PropertySignature(CallingConventionAttributes.HasThis, returnType, parameterTypes); } public PropertySignature(CallingConventionAttributes attributes, TypeSignature propertyType, IEnumerable parameterTypes) : base(attributes | CallingConventionAttributes.Property, propertyType, parameterTypes) { } public PropertySignature InstantiateGenericTypes(GenericContext context) { return GenericTypeActivator.Instance.InstantiatePropertySignature(this, context); } protected override void WriteContents(in BlobSerializationContext context) { context.Writer.WriteByte((byte)base.Attributes); WriteParametersAndReturnType(context); } public override string ToString() { return string.Concat(base.HasThis ? "instance " : string.Empty, str3: (base.ParameterTypes.Count > 0) ? ("[" + string.Join(", ", base.ParameterTypes) + "]") : string.Empty, str1: base.ReturnType.FullName, str2: " *"); } public PropertySignature ImportWith(ReferenceImporter importer) { return importer.ImportPropertySignature(this); } protected override CallingConventionSignature ImportWithInternal(ReferenceImporter importer) { return ImportWith(importer); } } public class SerializedCustomAttributeSignature : CustomAttributeSignature { private readonly BlobReaderContext _readerContext; private readonly GenericContext _genericContext; private readonly TypeSignature[] _fixedArgTypes; private readonly BinaryStreamReader _reader; public SerializedCustomAttributeSignature(in BlobReaderContext readerContext, IEnumerable fixedArgTypes, in GenericContext genericContext, in BinaryStreamReader reader) { //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) _readerContext = readerContext; _genericContext = genericContext; _fixedArgTypes = fixedArgTypes.ToArray(); _reader = reader; } protected override void Initialize(IList fixedArguments, IList namedArguments) { //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) BinaryStreamReader reader = ((BinaryStreamReader)(ref _reader)).Fork(); if (((BinaryStreamReader)(ref reader)).ReadUInt16() != 1) { ErrorListenerExtensions.BadImage((IErrorListener)(object)_readerContext.ReaderContext, "Input stream does not point to a valid custom attribute signature."); } for (int i = 0; i < _fixedArgTypes.Length; i++) { TypeSignature argumentType = _fixedArgTypes[i].InstantiateGenericTypes(_genericContext); fixedArguments.Add(CustomAttributeArgument.FromReader(in _readerContext, argumentType, ref reader)); } ushort num = ((BinaryStreamReader)(ref reader)).ReadUInt16(); for (int j = 0; j < num; j++) { namedArguments.Add(CustomAttributeNamedArgument.FromReader(in _readerContext, ref reader)); } } protected override void WriteContents(in BlobSerializationContext context) { //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) if (base.IsInitialized) { base.WriteContents(in context); return; } BinaryStreamReader val = ((BinaryStreamReader)(ref _reader)).Fork(); ((BinaryStreamReader)(ref val)).WriteToOutput(context.Writer); } public override bool IsCompatibleWith(ICustomAttributeType constructor, IErrorListener listener) { if (base.IsInitialized) { return base.IsCompatibleWith(constructor, listener); } return true; } } public class SignatureComparer : IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer, IEqualityComparer>, IEqualityComparer> { private const int ElementTypeOffset = 24; private const SignatureComparisonFlags DefaultFlags = SignatureComparisonFlags.ExactVersion; public static SignatureComparer Default { get; } = new SignatureComparer(); public SignatureComparisonFlags Flags { get; } private bool IgnoreAssemblyVersionNumbers => (Flags & SignatureComparisonFlags.VersionAgnostic) == SignatureComparisonFlags.VersionAgnostic; private bool AcceptNewerAssemblyVersionNumbers => (Flags & SignatureComparisonFlags.AcceptNewerVersions) == SignatureComparisonFlags.AcceptNewerVersions; private bool AcceptOlderAssemblyVersionNumbers => (Flags & SignatureComparisonFlags.AcceptOlderVersions) == SignatureComparisonFlags.AcceptOlderVersions; public bool Equals(CallingConventionSignature? x, CallingConventionSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (!(x is LocalVariablesSignature x2)) { if (!(x is FieldSignature x3)) { if (!(x is MethodSignature x4)) { if (x is PropertySignature x5) { return Equals(x5, y as PropertySignature); } return false; } return Equals(x4, y as MethodSignature); } return Equals(x3, y as FieldSignature); } return Equals(x2, y as LocalVariablesSignature); } public int GetHashCode(CallingConventionSignature obj) { if (!(obj is LocalVariablesSignature obj2)) { if (!(obj is FieldSignature obj3)) { if (!(obj is MethodSignature obj4)) { if (obj is PropertySignature obj5) { return GetHashCode(obj5); } throw new ArgumentOutOfRangeException("obj"); } return GetHashCode(obj4); } return GetHashCode(obj3); } return GetHashCode(obj2); } public bool Equals(FieldSignature? x, FieldSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.Attributes == y.Attributes) { return Equals(x.FieldType, y.FieldType); } return false; } public int GetHashCode(FieldSignature obj) { return ((int)obj.Attributes * 397) ^ GetHashCode(obj.FieldType); } public bool Equals(MethodSignature? x, MethodSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.Attributes == y.Attributes && x.GenericParameterCount == y.GenericParameterCount && Equals(x.ReturnType, y.ReturnType) && Equals(x.ParameterTypes, y.ParameterTypes)) { return Equals(x.SentinelParameterTypes, y.SentinelParameterTypes); } return false; } public int GetHashCode(MethodSignature obj) { return ((((((((int)obj.Attributes * 397) ^ obj.GenericParameterCount) * 397) ^ GetHashCode(obj.ReturnType)) * 397) ^ GetHashCode(obj.ParameterTypes)) * 397) ^ GetHashCode(obj.SentinelParameterTypes); } public bool Equals(LocalVariablesSignature? x, LocalVariablesSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.Attributes == y.Attributes) { return Equals(x.VariableTypes, y.VariableTypes); } return false; } public int GetHashCode(LocalVariablesSignature obj) { return ((int)obj.Attributes * 397) ^ GetHashCode(obj.VariableTypes); } public bool Equals(GenericInstanceMethodSignature? x, GenericInstanceMethodSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.Attributes == y.Attributes) { return Equals(x.TypeArguments, y.TypeArguments); } return false; } public int GetHashCode(GenericInstanceMethodSignature obj) { return ((int)obj.Attributes * 397) ^ GetHashCode(obj.TypeArguments); } public bool Equals(PropertySignature? x, PropertySignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.Attributes == y.Attributes && Equals(x.ReturnType, y.ReturnType)) { return Equals(x.ParameterTypes, y.ParameterTypes); } return false; } public int GetHashCode(PropertySignature obj) { return ((((int)obj.Attributes * 397) ^ GetHashCode(obj.ReturnType)) * 397) ^ GetHashCode(obj.ParameterTypes); } public SignatureComparer() { Flags = SignatureComparisonFlags.ExactVersion; } public SignatureComparer(SignatureComparisonFlags flags) { Flags = flags; } public bool Equals(byte[]? x, byte[]? y) { return ByteArrayEqualityComparer.Instance.Equals(x, y); } public int GetHashCode(byte[] obj) { return ByteArrayEqualityComparer.Instance.GetHashCode(obj); } public bool Equals(MemberReference? x, MemberReference? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.IsMethod) { return Equals((IMethodDescriptor?)x, (IMethodDescriptor?)y); } if (y.IsField) { return Equals((IFieldDescriptor?)x, (IFieldDescriptor?)y); } return false; } public int GetHashCode(MemberReference obj) { if (obj.IsMethod) { return GetHashCode((IMethodDescriptor)obj); } if (obj.IsField) { return GetHashCode((IFieldDescriptor)obj); } throw new ArgumentOutOfRangeException("obj"); } public bool Equals(IMethodDescriptor? x, IMethodDescriptor? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x is MethodSpecification x2) { return Equals(x2, y as MethodSpecification); } if (x.Name == y.Name && Equals(x.DeclaringType, y.DeclaringType)) { return Equals(x.Signature, y.Signature); } return false; } public int GetHashCode(IMethodDescriptor obj) { return (((((obj.Name != null) ? ((object)obj.Name).GetHashCode() : 0) * 397) ^ ((obj.DeclaringType != null) ? GetHashCode(obj.DeclaringType) : 0)) * 397) ^ ((obj.Signature != null) ? GetHashCode(obj.Signature) : 0); } public bool Equals(IFieldDescriptor? x, IFieldDescriptor? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.Name == y.Name && Equals(x.DeclaringType, y.DeclaringType)) { return Equals(x.Signature, y.Signature); } return false; } public int GetHashCode(IFieldDescriptor obj) { return (((((obj.Name != null) ? ((object)obj.Name).GetHashCode() : 0) * 397) ^ ((obj.DeclaringType != null) ? GetHashCode(obj.DeclaringType) : 0)) * 397) ^ ((obj.Signature != null) ? GetHashCode(obj.Signature) : 0); } public bool Equals(MethodSpecification? x, MethodSpecification? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (Equals(x.Method, y.Method)) { return Equals(x.Signature, y.Signature); } return false; } public int GetHashCode(MethodSpecification obj) { return (((obj.Method != null) ? GetHashCode(obj.Method) : 0) * 397) ^ ((obj.Signature != null) ? GetHashCode(obj.Signature) : 0); } public bool Equals(IResolutionScope? x, IResolutionScope? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x is AssemblyDescriptor assemblyDescriptor) { if (y is AssemblyDescriptor y2) { return Equals(assemblyDescriptor, y2); } if (y is ModuleDefinition moduleDefinition) { AssemblyDescriptor x2 = assemblyDescriptor; return Equals(x2, moduleDefinition.Assembly); } } else if (x is ModuleDefinition moduleDefinition2) { if (y is AssemblyDescriptor assemblyDescriptor2) { AssemblyDescriptor y3 = assemblyDescriptor2; return Equals(moduleDefinition2.Assembly, y3); } if (y is ModuleDefinition moduleDefinition3) { ModuleDefinition moduleDefinition4 = moduleDefinition2; ModuleDefinition moduleDefinition5 = moduleDefinition3; return Equals(moduleDefinition4.Assembly, moduleDefinition5.Assembly); } } else if (x is TypeReference x3 && y is TypeReference y4) { return Equals(x3, y4); } return false; } public int GetHashCode(IResolutionScope obj) { if (!(obj is AssemblyDescriptor obj2)) { if (!(obj is ModuleDefinition moduleDefinition)) { if (obj is TypeReference obj3) { return GetHashCode(obj3); } throw new ArgumentOutOfRangeException("obj"); } return (moduleDefinition.Assembly != null) ? GetHashCode(moduleDefinition.Assembly) : 0; } return GetHashCode(obj2); } public bool Equals(AssemblyDescriptor? x, AssemblyDescriptor? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } bool flag = IgnoreAssemblyVersionNumbers || (AcceptNewerAssemblyVersionNumbers ? (x.Version <= y.Version) : ((!AcceptOlderAssemblyVersionNumbers) ? (x.Version == y.Version) : (x.Version >= y.Version))); if (flag && x.Name == y.Name && (x.Culture == y.Culture || (Utf8String.IsNullOrEmpty(x.Culture) && Utf8String.IsNullOrEmpty(y.Culture)))) { return Equals(x.GetPublicKeyToken(), y.GetPublicKeyToken()); } return false; } public int GetHashCode(AssemblyDescriptor obj) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected I4, but got Unknown ? val = (((((((((obj.Name != null) ? ((object)obj.Name).GetHashCode() : 0) * 397) ^ ((obj.Culture != null) ? ((object)obj.Culture).GetHashCode() : 0)) * 397) ^ 0x23) * 397) ^ obj.Version.GetHashCode()) * 397) ^ obj.Attributes; byte[] publicKeyToken = obj.GetPublicKeyToken(); return (val * 397) ^ ((publicKeyToken != null) ? GetHashCode(publicKeyToken) : 0); } public bool Equals(ITypeDescriptor? x, ITypeDescriptor? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (!(x is InvalidTypeDefOrRef x2)) { if (!(x is TypeSpecification x3)) { if (x is TypeSignature x4) { return Equals(x4, y as TypeSignature); } return SimpleTypeEquals(x, y); } return Equals(x3, y as TypeSpecification); } return Equals(x2, y as InvalidTypeDefOrRef); } public int GetHashCode(ITypeDescriptor obj) { return (((((obj.Name != null) ? obj.Name.GetHashCode() : 0) * 397) ^ ((obj.Namespace != null) ? obj.Namespace.GetHashCode() : 0)) * 397) ^ ((obj.DeclaringType != null) ? GetHashCode(obj.DeclaringType) : 0); } private bool SimpleTypeEquals(ITypeDescriptor x, ITypeDescriptor y) { if (!x.IsTypeOf(y.Namespace, y.Name)) { return false; } if (Equals(x.Scope, y.Scope)) { return true; } if (!Equals(x.Module, y.Module)) { TypeDefinition typeDefinition = x.Resolve(); if (typeDefinition != null) { TypeDefinition typeDefinition2 = y.Resolve(); if (typeDefinition2 != null && Equals(typeDefinition.Module.Assembly, typeDefinition2.Module.Assembly)) { return Equals(typeDefinition.DeclaringType, typeDefinition2.DeclaringType); } } return false; } return false; } public bool Equals(ITypeDefOrRef? x, ITypeDefOrRef? y) { return Equals((ITypeDescriptor?)x, (ITypeDescriptor?)y); } public int GetHashCode(ITypeDefOrRef obj) { return GetHashCode((ITypeDescriptor)obj); } public bool Equals(TypeDefinition? x, TypeDefinition? y) { return Equals((ITypeDescriptor?)x, (ITypeDescriptor?)y); } public int GetHashCode(TypeDefinition obj) { return GetHashCode((ITypeDescriptor)obj); } public bool Equals(TypeReference? x, TypeReference? y) { return Equals((ITypeDescriptor?)x, (ITypeDescriptor?)y); } public int GetHashCode(TypeReference obj) { return GetHashCode((ITypeDescriptor)obj); } public bool Equals(TypeSpecification? x, TypeSpecification? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } return Equals(x.Signature, y.Signature); } public int GetHashCode(TypeSpecification obj) { if (obj.Signature == null) { return 0; } return GetHashCode(obj.Signature); } public bool Equals(ExportedType? x, ExportedType? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } return Equals((ITypeDescriptor?)x, (ITypeDescriptor?)y); } public int GetHashCode(ExportedType obj) { return GetHashCode((ITypeDescriptor)obj); } public bool Equals(InvalidTypeDefOrRef? x, InvalidTypeDefOrRef? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } return x.Error == y.Error; } public int GetHashCode(InvalidTypeDefOrRef obj) { return (int)obj.Error; } public bool Equals(TypeSignature? x, TypeSignature? y) { //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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Invalid comparison between Unknown and I4 //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_006f: Expected I4, but got Unknown //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Invalid comparison between Unknown and I4 //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Invalid comparison between Unknown and I4 if (x == y) { return true; } if (x == null || y == null) { return false; } ElementType elementType = x.ElementType; if ((int)elementType <= 64) { switch (elementType - 15) { default: if ((int)elementType != 64) { break; } goto case 18; case 2: case 3: return Equals(x as TypeDefOrRefSignature, y as TypeDefOrRefSignature); case 16: case 17: return Equals(x as CustomModifierTypeSignature, y as CustomModifierTypeSignature); case 6: return Equals(x as GenericInstanceTypeSignature, y as GenericInstanceTypeSignature); case 4: case 15: return Equals(x as GenericParameterSignature, y as GenericParameterSignature); case 0: return Equals(x as PointerTypeSignature, y as PointerTypeSignature); case 1: return Equals(x as ByReferenceTypeSignature, y as ByReferenceTypeSignature); case 5: return Equals(x as ArrayTypeSignature, y as ArrayTypeSignature); case 14: return Equals(x as SzArrayTypeSignature, y as SzArrayTypeSignature); case 12: return Equals(x as FunctionPointerTypeSignature, y as FunctionPointerTypeSignature); case 18: throw new NotSupportedException(); case 7: case 8: case 9: case 10: case 11: case 13: break; } } else { if ((int)elementType == 65) { return Equals(x as SentinelTypeSignature, y as SentinelTypeSignature); } if ((int)elementType == 69) { return Equals(x as PinnedTypeSignature, y as PinnedTypeSignature); } if ((int)elementType == 81) { return Equals(x as BoxedTypeSignature, y as BoxedTypeSignature); } } return Equals(x as CorLibTypeSignature, y as CorLibTypeSignature); } public int GetHashCode(TypeSignature obj) { //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: Invalid comparison between Unknown and I4 //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Invalid comparison between Unknown and I4 //IL_000c: 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_0061: Expected I4, but got Unknown //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Invalid comparison between Unknown and I4 //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Invalid comparison between Unknown and I4 //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 ElementType elementType = obj.ElementType; if ((int)elementType <= 64) { switch (elementType - 15) { default: if ((int)elementType != 64) { break; } goto case 12; case 2: case 3: return GetHashCode((TypeDefOrRefSignature)obj); case 16: case 17: return GetHashCode((CustomModifierTypeSignature)obj); case 6: return GetHashCode((GenericInstanceTypeSignature)obj); case 4: case 15: return GetHashCode((GenericParameterSignature)obj); case 0: return GetHashCode((PointerTypeSignature)obj); case 1: return GetHashCode((ByReferenceTypeSignature)obj); case 5: return GetHashCode((ArrayTypeSignature)obj); case 14: return GetHashCode((SzArrayTypeSignature)obj); case 12: case 18: throw new NotSupportedException(); case 7: case 8: case 9: case 10: case 11: case 13: break; } } else { if ((int)elementType == 65) { return GetHashCode((SentinelTypeSignature)obj); } if ((int)elementType == 69) { return GetHashCode((PinnedTypeSignature)obj); } if ((int)elementType == 81) { return GetHashCode((BoxedTypeSignature)obj); } } return GetHashCode((CorLibTypeSignature)obj); } public bool Equals(CorLibTypeSignature? x, CorLibTypeSignature? y) { //IL_000f: 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) if (x == y) { return true; } if (x == null || y == null) { return false; } return x.ElementType == y.ElementType; } public int GetHashCode(CorLibTypeSignature obj) { //IL_0001: 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_000a: Expected I4, but got Unknown return obj.ElementType << 24; } public bool Equals(SentinelTypeSignature? x, SentinelTypeSignature? y) { //IL_000f: 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) if (x == y) { return true; } if (x == null || y == null) { return false; } return x.ElementType == y.ElementType; } public int GetHashCode(SentinelTypeSignature obj) { //IL_0001: 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_000a: Expected I4, but got Unknown return obj.ElementType << 24; } public bool Equals(ByReferenceTypeSignature? x, ByReferenceTypeSignature? y) { return Equals((TypeSpecificationSignature?)x, (TypeSpecificationSignature?)y); } public int GetHashCode(ByReferenceTypeSignature obj) { return GetHashCode((TypeSpecificationSignature)obj); } public bool Equals(PointerTypeSignature? x, PointerTypeSignature? y) { return Equals((TypeSpecificationSignature?)x, (TypeSpecificationSignature?)y); } public int GetHashCode(PointerTypeSignature obj) { return GetHashCode((TypeSpecificationSignature)obj); } public bool Equals(SzArrayTypeSignature? x, SzArrayTypeSignature? y) { return Equals((TypeSpecificationSignature?)x, (TypeSpecificationSignature?)y); } public int GetHashCode(SzArrayTypeSignature obj) { return GetHashCode((TypeSpecificationSignature)obj); } public bool Equals(PinnedTypeSignature? x, PinnedTypeSignature? y) { return Equals((TypeSpecificationSignature?)x, (TypeSpecificationSignature?)y); } public int GetHashCode(PinnedTypeSignature obj) { return GetHashCode((TypeSpecificationSignature)obj); } public bool Equals(BoxedTypeSignature? x, BoxedTypeSignature? y) { return Equals((TypeSpecificationSignature?)x, (TypeSpecificationSignature?)y); } public int GetHashCode(BoxedTypeSignature obj) { return GetHashCode((TypeSpecificationSignature)obj); } public bool Equals(TypeDefOrRefSignature? x, TypeDefOrRefSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } return SimpleTypeEquals(x.Type, y.Type); } public int GetHashCode(TypeDefOrRefSignature obj) { //IL_0001: 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_000e: 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_0020: 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: 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_0057: Expected I4, but got Unknown return ((((((obj.ElementType << 24) * 397) ^ obj.Name.GetHashCode()) * 397) ^ ((obj.Namespace != null) ? obj.Namespace.GetHashCode() : 0)) * 397) ^ ((obj.Scope != null) ? GetHashCode(obj.Scope) : 0); } public bool Equals(CustomModifierTypeSignature? x, CustomModifierTypeSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.IsRequired == y.IsRequired && Equals(x.ModifierType, y.ModifierType)) { return Equals(x.BaseType, y.BaseType); } return false; } public int GetHashCode(CustomModifierTypeSignature obj) { //IL_0001: 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_000e: 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_0020: 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_002e: Expected I4, but got Unknown return ((((obj.ElementType << 24) * 397) ^ obj.ModifierType.GetHashCode()) * 397) ^ obj.BaseType.GetHashCode(); } public bool Equals(GenericInstanceTypeSignature? x, GenericInstanceTypeSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.IsValueType == y.IsValueType && Equals(x.GenericType, y.GenericType)) { return Equals(x.TypeArguments, y.TypeArguments); } return false; } public int GetHashCode(GenericInstanceTypeSignature obj) { //IL_0001: 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_000e: 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_0020: 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_002f: Expected I4, but got Unknown return ((((obj.ElementType << 24) * 397) ^ obj.GenericType.GetHashCode()) * 397) ^ GetHashCode(obj.TypeArguments); } public bool Equals(GenericParameterSignature? x, GenericParameterSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x.Index == y.Index) { return x.ParameterType == y.ParameterType; } return false; } public int GetHashCode(GenericParameterSignature obj) { //IL_0001: 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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected I4, but got Unknown return (obj.ElementType << 24) | obj.Index; } private bool Equals(TypeSpecificationSignature? x, TypeSpecificationSignature? y) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (x == y) { return true; } if (x == null || y == null || x.ElementType != y.ElementType) { return false; } return Equals(x.BaseType, y.BaseType); } private int GetHashCode(TypeSpecificationSignature obj) { //IL_0001: 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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected I4, but got Unknown return (obj.ElementType << 24) ^ GetHashCode(obj.BaseType); } public bool Equals(ArrayTypeSignature? x, ArrayTypeSignature? y) { if (x == y) { return true; } if (x == null || y == null || x.Dimensions.Count != y.Dimensions.Count) { return false; } for (int i = 0; i < x.Dimensions.Count; i++) { if (x.Dimensions[i].Size != y.Dimensions[i].Size || x.Dimensions[i].LowerBound != y.Dimensions[i].LowerBound) { return false; } } return Equals(x.BaseType, y.BaseType); } public int GetHashCode(ArrayTypeSignature obj) { //IL_0001: 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_000a: Expected I4, but got Unknown int num = obj.ElementType << 24; num = (num * 397) ^ GetHashCode(obj.BaseType); for (int i = 0; i < obj.Dimensions.Count; i++) { num = (num * 397) ^ obj.Dimensions[i].GetHashCode(); } return num; } public bool Equals(FunctionPointerTypeSignature? x, FunctionPointerTypeSignature? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } return Equals(x.Signature, y.Signature); } public int GetHashCode(FunctionPointerTypeSignature obj) { return obj.Signature.GetHashCode(); } public bool Equals(IList? x, IList? y) { if (x == y) { return true; } if (x == null || y == null || x.Count != y.Count) { return false; } for (int i = 0; i < x.Count; i++) { if (!Equals(x[i], y[i])) { return false; } } return true; } public int GetHashCode(IList obj) { int num = 0; for (int i = 0; i < obj.Count; i++) { num ^= GetHashCode(obj[i]); } return num; } public bool Equals(IEnumerable? x, IEnumerable? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } return x.SequenceEqual(y, this); } public int GetHashCode(IEnumerable obj) { int num = 0; foreach (TypeSignature item in obj) { num ^= GetHashCode(item); } return num; } } [Flags] public enum SignatureComparisonFlags { ExactVersion = 0, AcceptOlderVersions = 1, AcceptNewerVersions = 2, VersionAgnostic = 3 } } namespace AsmResolver.DotNet.Signatures.Types { public readonly struct ArrayDimension : IEquatable { public int? Size { get; } public int? LowerBound { get; } public ArrayDimension(int size) : this(size, null) { } public ArrayDimension(int? size, int? lowerBound) { Size = size; LowerBound = lowerBound; } public bool Equals(ArrayDimension other) { if (Size == other.Size) { return LowerBound == other.LowerBound; } return false; } public override bool Equals(object? obj) { if (obj is ArrayDimension other) { return Equals(other); } return false; } public override int GetHashCode() { return (Size.GetHashCode() * 397) ^ LowerBound.GetHashCode(); } } public class ArrayTypeSignature : TypeSpecificationSignature { public override ElementType ElementType => (ElementType)20; public override string Name => (base.BaseType.Name ?? "<>") + GetDimensionsString(); public override bool IsValueType => false; public IList Dimensions { get; } public ArrayTypeSignature(TypeSignature baseType) : base(baseType) { Dimensions = new List(0); } public ArrayTypeSignature(TypeSignature baseType, int dimensionCount) : base(baseType) { if (dimensionCount < 0) { throw new ArgumentException("Number of dimensions cannot be negative."); } Dimensions = new List(dimensionCount); for (int i = 0; i < dimensionCount; i++) { Dimensions.Add(default(ArrayDimension)); } } public ArrayTypeSignature(TypeSignature baseType, params ArrayDimension[] dimensions) : base(baseType) { Dimensions = new List(dimensions); } internal new static ArrayTypeSignature FromReader(ref BlobReaderContext context, ref BinaryStreamReader reader) { ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature(TypeSignature.FromReader(ref context, ref reader)); uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid rank in array type signature."); return arrayTypeSignature; } uint num2 = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num2)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid number of dimension sizes in array type signature."); return arrayTypeSignature; } List list = new List((int)num2); uint item = default(uint); for (int i = 0; i < num2; i++) { if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref item)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Dimension " + i + " of array signature is invalid."); return arrayTypeSignature; } list.Add(item); } uint num3 = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num3)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid number of dimension lower bounds in array type signature."); return arrayTypeSignature; } List list2 = new List((int)num3); uint item2 = default(uint); for (int j = 0; j < num3; j++) { if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref item2)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Lower bound " + j + " of array type signature is invalid."); return arrayTypeSignature; } list2.Add(item2); } for (int k = 0; k < num; k++) { int? size = null; int? lowerBound = null; if (k < num2) { size = (int)list[k]; } if (k < num3) { lowerBound = (int)list2[k]; } arrayTypeSignature.Dimensions.Add(new ArrayDimension(size, lowerBound)); } return arrayTypeSignature; } private string GetDimensionsString() { return "[" + string.Join(",", Dimensions.Select(delegate(ArrayDimension x) { if (x.LowerBound.HasValue) { if (x.Size.HasValue) { return FormatDimensionBounds(x.LowerBound.Value, x.Size.Value); } return x.LowerBound.Value + "..."; } return x.Size.HasValue ? FormatDimensionBounds(0, x.Size.Value) : string.Empty; })) + "]"; } private static string FormatDimensionBounds(int low, int size) { return $"{low}...{low + size - 1}"; } public bool Validate() { bool flag = true; bool flag2 = true; for (int i = 0; i < Dimensions.Count; i++) { ArrayDimension arrayDimension = Dimensions[i]; if (arrayDimension.Size.HasValue) { if (!flag) { return false; } } else { flag = false; } if (arrayDimension.LowerBound.HasValue) { if (!flag2) { return false; } } else { flag2 = false; } } return true; } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitArrayType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitArrayType(this, state); } protected override void WriteContents(in BlobSerializationContext context) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected I4, but got Unknown if (!Validate()) { throw new InvalidOperationException(); } IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)(int)ElementType); WriteBaseType(context); IOExtensions.WriteCompressedUInt32(writer, (uint)Dimensions.Count); ArrayDimension[] array = Dimensions.Where((ArrayDimension x) => x.Size.HasValue).ToArray(); IOExtensions.WriteCompressedUInt32(writer, (uint)array.Length); ArrayDimension[] array2 = array; foreach (ArrayDimension arrayDimension in array2) { IOExtensions.WriteCompressedUInt32(writer, (uint)arrayDimension.Size.Value); } ArrayDimension[] array3 = Dimensions.Where((ArrayDimension x) => x.LowerBound.HasValue).ToArray(); IOExtensions.WriteCompressedUInt32(writer, (uint)array3.Length); array2 = array3; foreach (ArrayDimension arrayDimension2 in array2) { IOExtensions.WriteCompressedUInt32(writer, (uint)arrayDimension2.LowerBound.Value); } } } public class BoxedTypeSignature : TypeSpecificationSignature { public override ElementType ElementType => (ElementType)81; public override string Name => base.BaseType.Name ?? "<>"; public override bool IsValueType => false; public BoxedTypeSignature(TypeSignature baseType) : base(baseType) { } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitBoxedType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitBoxedType(this, state); } } public class ByReferenceTypeSignature : TypeSpecificationSignature { public override ElementType ElementType => (ElementType)16; public override string Name => (base.BaseType.Name ?? "<>") + "&"; public override bool IsValueType => false; public ByReferenceTypeSignature(TypeSignature baseType) : base(baseType) { } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitByReferenceType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitByReferenceType(this, state); } } public class CorLibTypeFactory { private CorLibTypeSignature? _void; private CorLibTypeSignature? _boolean; private CorLibTypeSignature? _char; private CorLibTypeSignature? _sbyte; private CorLibTypeSignature? _byte; private CorLibTypeSignature? _int16; private CorLibTypeSignature? _uint16; private CorLibTypeSignature? _int32; private CorLibTypeSignature? _uint32; private CorLibTypeSignature? _int64; private CorLibTypeSignature? _uint64; private CorLibTypeSignature? _single; private CorLibTypeSignature? _double; private CorLibTypeSignature? _string; private CorLibTypeSignature? _intPtr; private CorLibTypeSignature? _uintPtr; private CorLibTypeSignature? _object; private CorLibTypeSignature? _typedReference; public IResolutionScope CorLibScope { get; } public CorLibTypeSignature Void => GetOrCreateCorLibTypeSignature(ref _void, (ElementType)1, "Void"); public CorLibTypeSignature Boolean => GetOrCreateCorLibTypeSignature(ref _boolean, (ElementType)2, "Boolean"); public CorLibTypeSignature Char => GetOrCreateCorLibTypeSignature(ref _char, (ElementType)3, "Char"); public CorLibTypeSignature SByte => GetOrCreateCorLibTypeSignature(ref _sbyte, (ElementType)4, "SByte"); public CorLibTypeSignature Byte => GetOrCreateCorLibTypeSignature(ref _byte, (ElementType)5, "Byte"); public CorLibTypeSignature Int16 => GetOrCreateCorLibTypeSignature(ref _int16, (ElementType)6, "Int16"); public CorLibTypeSignature UInt16 => GetOrCreateCorLibTypeSignature(ref _uint16, (ElementType)7, "UInt16"); public CorLibTypeSignature Int32 => GetOrCreateCorLibTypeSignature(ref _int32, (ElementType)8, "Int32"); public CorLibTypeSignature UInt32 => GetOrCreateCorLibTypeSignature(ref _uint32, (ElementType)9, "UInt32"); public CorLibTypeSignature Int64 => GetOrCreateCorLibTypeSignature(ref _int64, (ElementType)10, "Int64"); public CorLibTypeSignature UInt64 => GetOrCreateCorLibTypeSignature(ref _uint64, (ElementType)11, "UInt64"); public CorLibTypeSignature Single => GetOrCreateCorLibTypeSignature(ref _single, (ElementType)12, "Single"); public CorLibTypeSignature Double => GetOrCreateCorLibTypeSignature(ref _double, (ElementType)13, "Double"); public CorLibTypeSignature String => GetOrCreateCorLibTypeSignature(ref _string, (ElementType)14, "String"); public CorLibTypeSignature IntPtr => GetOrCreateCorLibTypeSignature(ref _intPtr, (ElementType)24, "IntPtr"); public CorLibTypeSignature UIntPtr => GetOrCreateCorLibTypeSignature(ref _uintPtr, (ElementType)25, "UIntPtr"); public CorLibTypeSignature TypedReference => GetOrCreateCorLibTypeSignature(ref _typedReference, (ElementType)22, "TypedReference"); public CorLibTypeSignature Object => GetOrCreateCorLibTypeSignature(ref _object, (ElementType)28, "Object"); public static CorLibTypeFactory CreateMscorlib40TypeFactory(ModuleDefinition module) { return new CorLibTypeFactory(new ReferenceImporter(module).ImportScope(KnownCorLibs.MsCorLib_v4_0_0_0)); } public CorLibTypeFactory(IResolutionScope corLibScope) { CorLibScope = corLibScope ?? throw new ArgumentNullException("corLibScope"); } public CorLibTypeSignature? FromType(ITypeDescriptor type) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (!(type is CorLibTypeSignature corLibTypeSignature)) { return FromName(type.Namespace, type.Name); } return FromElementType(corLibTypeSignature.ElementType); } public CorLibTypeSignature? FromElementType(ElementType elementType) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected I4, but got Unknown return (elementType - 1) switch { 0 => Void, 1 => Boolean, 2 => Char, 3 => SByte, 4 => Byte, 5 => Int16, 6 => UInt16, 7 => Int32, 8 => UInt32, 9 => Int64, 10 => UInt64, 11 => Single, 12 => Double, 13 => String, 23 => IntPtr, 24 => UIntPtr, 21 => TypedReference, 27 => Object, _ => null, }; } public CorLibTypeSignature? FromName(string? ns, string? name) { if (ns == "System") { return name switch { "Void" => Void, "Boolean" => Boolean, "Char" => Char, "SByte" => SByte, "Byte" => Byte, "Int16" => Int16, "UInt16" => UInt16, "Int32" => Int32, "UInt32" => UInt32, "Int64" => Int64, "UInt64" => UInt64, "Single" => Single, "Double" => Double, "String" => String, "IntPtr" => IntPtr, "UIntPtr" => UIntPtr, "TypedReference" => TypedReference, "Object" => Object, _ => null, }; } return null; } public DotNetRuntimeInfo ExtractDotNetRuntimeInfo() { AssemblyDescriptor assembly = CorLibScope.GetAssembly(); if (assembly == null) { return new DotNetRuntimeInfo(".NETFramework", new Version(4, 0)); } Version version = assembly.Version; if (version.Major >= 5) { return new DotNetRuntimeInfo(".NETCoreApp", new Version(version.Major, version.Minor)); } int build; int revision; (string, Version) tuple; string name; Version version2; switch (Utf8String.op_Implicit(assembly.Name)) { case "mscorlib": return new DotNetRuntimeInfo(".NETFramework", version); case "netstandard": return new DotNetRuntimeInfo(".NETStandard", version); case "System.Private.CoreLib": return new DotNetRuntimeInfo(".NETCoreApp", new Version(1, 0)); case "System.Runtime": { int major = version.Major; int minor = version.Minor; build = version.Build; revision = version.Revision; if (major == 4) { switch (minor) { case 0: break; case 1: goto IL_00fe; case 2: goto IL_0108; default: goto IL_0152; } if (build == 20 && revision == 0) { tuple = (".NETStandard", new Version(1, 3)); goto IL_0165; } } goto IL_0152; } default: { return new DotNetRuntimeInfo(".NETCoreApp", version); } IL_0152: tuple = (".NETCoreApp", new Version(3, 1)); goto IL_0165; IL_0108: if (build != 1 || revision != 0) { goto IL_0152; } tuple = (".NETCoreApp", new Version(2, 1)); goto IL_0165; IL_0165: (name, version2) = tuple; return new DotNetRuntimeInfo(name, version2); IL_00fe: if (build != 0 || revision != 0) { goto IL_0152; } tuple = (".NETStandard", new Version(1, 5)); goto IL_0165; } } private CorLibTypeSignature GetOrCreateCorLibTypeSignature(ref CorLibTypeSignature? cache, ElementType elementType, string name) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (cache == null) { CorLibTypeSignature value = new CorLibTypeSignature(CorLibScope, elementType, name); Interlocked.CompareExchange(ref cache, value, null); } return cache; } } public class CorLibTypeSignature : TypeSignature { public ITypeDefOrRef Type { get; } public override string? Name { get; } public override string Namespace => "System"; public override bool IsValueType { get { //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_0009: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected I4, but got Unknown ElementType elementType = ElementType; return (elementType - 1) switch { 13 => false, 27 => false, 0 => true, 1 => true, 2 => true, 3 => true, 4 => true, 5 => true, 6 => true, 7 => true, 8 => true, 9 => true, 10 => true, 11 => true, 12 => true, 21 => true, 23 => true, 24 => true, _ => throw new ArgumentOutOfRangeException(), }; } } public override ElementType ElementType { get; } public override IResolutionScope? Scope { get; } internal CorLibTypeSignature(IResolutionScope corlibScope, ElementType elementType, string name) { //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) string name2 = name; base..ctor(); Scope = corlibScope; ElementType = elementType; Name = name2; if (corlibScope is ModuleDefinition moduleDefinition) { Type = moduleDefinition.TopLevelTypes.First((TypeDefinition t) => t.IsTypeOf("System", name2)); return; } if (corlibScope.Module != null) { Type = new TypeReference(corlibScope.Module, corlibScope, Utf8String.op_Implicit("System"), Utf8String.op_Implicit(name2)); return; } throw new ArgumentException("Provided CorLib was not valid."); } public override TypeDefinition? Resolve() { return Type.Resolve(); } public override bool IsImportedInModule(ModuleDefinition module) { return Module == module; } public override ITypeDefOrRef? GetUnderlyingTypeDefOrRef() { return Type; } public override ITypeDefOrRef ToTypeDefOrRef() { return Type; } protected override void WriteContents(in BlobSerializationContext context) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected I4, but got Unknown context.Writer.WriteByte((byte)(int)ElementType); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitCorLibType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitCorLibType(this, state); } } public class CustomModifierTypeSignature : TypeSpecificationSignature { public override ElementType ElementType { get { if (IsRequired) { return (ElementType)31; } return (ElementType)32; } } public bool IsRequired { get; set; } public bool IsOptional { get { return !IsRequired; } set { IsRequired = !value; } } public ITypeDefOrRef ModifierType { get; set; } public override string Name { get { string value = (IsRequired ? "modreq(" : "modopt("); string value2 = base.BaseType.Name ?? "<>"; string fullName = ModifierType.FullName; return $"{value2} {value}{fullName})"; } } public override bool IsValueType => base.BaseType.IsValueType; public CustomModifierTypeSignature(ITypeDefOrRef modifierType, bool isRequired, TypeSignature baseType) : base(baseType) { ModifierType = modifierType; IsRequired = isRequired; } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitCustomModifierType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitCustomModifierType(this, state); } public override bool IsImportedInModule(ModuleDefinition module) { if (ModifierType.IsImportedInModule(module)) { return base.IsImportedInModule(module); } return false; } protected override void WriteContents(in BlobSerializationContext context) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected I4, but got Unknown context.Writer.WriteByte((byte)(int)ElementType); WriteTypeDefOrRef(context, ModifierType, "Modifier type"); WriteBaseType(context); } } public class FunctionPointerTypeSignature : TypeSignature { public override ElementType ElementType => (ElementType)27; public MethodSignature Signature { get; set; } public override string Name => $"method {Signature}"; public override string? Namespace => null; public override IResolutionScope? Scope => Signature.ReturnType.Scope; public override bool IsValueType => true; public FunctionPointerTypeSignature(MethodSignature signature) { Signature = signature ?? throw new ArgumentNullException("signature"); } public override TypeDefinition? Resolve() { return GetUnderlyingTypeDefOrRef()?.Resolve(); } public override ITypeDefOrRef? GetUnderlyingTypeDefOrRef() { return Signature.ReturnType.Module?.CorLibTypeFactory.IntPtr.Type; } public override bool IsImportedInModule(ModuleDefinition module) { return Signature.IsImportedInModule(module); } protected override void WriteContents(in BlobSerializationContext context) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected I4, but got Unknown context.Writer.WriteByte((byte)(int)ElementType); Signature.Write(in context); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitFunctionPointerType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitFunctionPointerType(this, state); } } public class GenericInstanceTypeSignature : TypeSignature, IGenericArgumentsProvider { private readonly List _typeArguments; private ITypeDefOrRef _genericType; private bool _isValueType; public override ElementType ElementType => (ElementType)21; public ITypeDefOrRef GenericType { get { return _genericType; } set { _genericType = value; _isValueType = _genericType.IsValueType; } } public IList TypeArguments => _typeArguments; public override string? Name { get { string value = string.Join(", ", TypeArguments); return $"{GenericType.Name ?? Utf8String.op_Implicit("<>")}<{value}>"; } } public override string? Namespace => Utf8String.op_Implicit(GenericType.Namespace); public override IResolutionScope? Scope => GenericType.Scope; public override ModuleDefinition? Module => GenericType.Module; public override bool IsValueType => _isValueType; internal new static GenericInstanceTypeSignature FromReader(ref BlobReaderContext context, ref BinaryStreamReader reader) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 TypeSignature typeSignature = TypeSignature.FromReader(ref context, ref reader); GenericInstanceTypeSignature genericInstanceTypeSignature = new GenericInstanceTypeSignature(typeSignature.ToTypeDefOrRef(), (int)typeSignature.ElementType == 17); uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid number of type arguments in generic type signature."); return genericInstanceTypeSignature; } genericInstanceTypeSignature._typeArguments.Capacity = (int)num; for (int i = 0; i < num; i++) { genericInstanceTypeSignature._typeArguments.Add(TypeSignature.FromReader(ref context, ref reader)); } return genericInstanceTypeSignature; } public GenericInstanceTypeSignature(ITypeDefOrRef genericType, bool isValueType) : this(genericType, isValueType, Enumerable.Empty()) { } public GenericInstanceTypeSignature(ITypeDefOrRef genericType, bool isValueType, params TypeSignature[] typeArguments) : this(genericType, isValueType, typeArguments.AsEnumerable()) { } private GenericInstanceTypeSignature(ITypeDefOrRef genericType, bool isValueType, IEnumerable typeArguments) { _genericType = genericType; _typeArguments = new List(typeArguments); _isValueType = isValueType; } public override TypeDefinition? Resolve() { return GenericType.Resolve(); } public override ITypeDefOrRef? GetUnderlyingTypeDefOrRef() { return GenericType; } public override bool IsImportedInModule(ModuleDefinition module) { if (!GenericType.IsImportedInModule(module)) { return false; } for (int i = 0; i < TypeArguments.Count; i++) { if (!TypeArguments[i].IsImportedInModule(module)) { return false; } } return true; } protected override void WriteContents(in BlobSerializationContext context) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected I4, but got Unknown IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)(int)ElementType); writer.WriteByte((byte)(IsValueType ? 17 : 18)); WriteTypeDefOrRef(context, GenericType, "Underlying generic type"); IOExtensions.WriteCompressedUInt32(writer, (uint)TypeArguments.Count); for (int i = 0; i < TypeArguments.Count; i++) { TypeArguments[i].Write(in context); } } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitGenericInstanceType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitGenericInstanceType(this, state); } } public class GenericParameterSignature : TypeSignature { public override ElementType ElementType => (ElementType)(ParameterType switch { GenericParameterType.Type => 19, GenericParameterType.Method => 30, _ => throw new ArgumentOutOfRangeException(), }); public GenericParameterType ParameterType { get; set; } public int Index { get; set; } public override string Name => ParameterType switch { GenericParameterType.Type => $"!{Index}", GenericParameterType.Method => $"!!{Index}", _ => throw new ArgumentOutOfRangeException(), }; public override string? Namespace => null; public override IResolutionScope? Scope { get; } public override bool IsValueType => false; public GenericParameterSignature(GenericParameterType parameterType, int index) { ParameterType = parameterType; Index = index; } public GenericParameterSignature(ModuleDefinition module, GenericParameterType parameterType, int index) { Scope = module; ParameterType = parameterType; Index = index; } public override TypeDefinition? Resolve() { return null; } public override bool IsImportedInModule(ModuleDefinition module) { return Module == module; } public override ITypeDefOrRef? GetUnderlyingTypeDefOrRef() { return null; } protected override void WriteContents(in BlobSerializationContext context) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected I4, but got Unknown IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)(int)ElementType); IOExtensions.WriteCompressedUInt32(writer, (uint)Index); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitGenericParameter(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitGenericParameter(this, state); } } public enum GenericParameterType { Type = 1, Method } public class GenericTypeActivator : ITypeSignatureVisitor { public static GenericTypeActivator Instance { get; } = new GenericTypeActivator(); public FieldSignature InstantiateFieldSignature(FieldSignature signature, GenericContext context) { return new FieldSignature(signature.Attributes, signature.FieldType.AcceptVisitor(this, context)); } public PropertySignature InstantiatePropertySignature(PropertySignature signature, GenericContext context) { PropertySignature result = new PropertySignature(signature.Attributes, signature.ReturnType, Enumerable.Empty()); InstantiateMethodSignatureBase(signature, result, context); return result; } public MethodSignature InstantiateMethodSignature(MethodSignature signature, GenericContext context) { MethodSignature methodSignature = new MethodSignature(signature.Attributes, signature.ReturnType, Enumerable.Empty()); InstantiateMethodSignatureBase(signature, methodSignature, context); methodSignature.GenericParameterCount = signature.GenericParameterCount; if (signature.IncludeSentinel) { methodSignature.IncludeSentinel = signature.IncludeSentinel; foreach (TypeSignature sentinelParameterType in signature.SentinelParameterTypes) { methodSignature.SentinelParameterTypes.Add(sentinelParameterType.AcceptVisitor(this, context)); } } return methodSignature; } private void InstantiateMethodSignatureBase(MethodSignatureBase signature, MethodSignatureBase result, GenericContext context) { result.ReturnType = signature.ReturnType.AcceptVisitor(this, context); foreach (TypeSignature parameterType in signature.ParameterTypes) { result.ParameterTypes.Add(parameterType.AcceptVisitor(this, context)); } } public TypeSignature VisitArrayType(ArrayTypeSignature signature, GenericContext context) { ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature(signature.BaseType.AcceptVisitor(this, context)); for (int i = 0; i < signature.Dimensions.Count; i++) { arrayTypeSignature.Dimensions.Add(signature.Dimensions[i]); } return arrayTypeSignature; } public TypeSignature VisitBoxedType(BoxedTypeSignature signature, GenericContext context) { TypeSignature typeSignature = signature.BaseType.AcceptVisitor(this, context); if (typeSignature == signature.BaseType) { return signature; } return new BoxedTypeSignature(typeSignature); } public TypeSignature VisitByReferenceType(ByReferenceTypeSignature signature, GenericContext context) { TypeSignature typeSignature = signature.BaseType.AcceptVisitor(this, context); if (typeSignature == signature.BaseType) { return signature; } return new ByReferenceTypeSignature(typeSignature); } public TypeSignature VisitCorLibType(CorLibTypeSignature signature, GenericContext context) { return signature; } public TypeSignature VisitCustomModifierType(CustomModifierTypeSignature signature, GenericContext context) { return new CustomModifierTypeSignature(signature.ModifierType, signature.IsRequired, signature.BaseType.AcceptVisitor(this, context)); } public TypeSignature VisitGenericInstanceType(GenericInstanceTypeSignature signature, GenericContext context) { GenericInstanceTypeSignature genericInstanceTypeSignature = new GenericInstanceTypeSignature(signature.GenericType, signature.IsValueType); for (int i = 0; i < signature.TypeArguments.Count; i++) { genericInstanceTypeSignature.TypeArguments.Add(signature.TypeArguments[i].AcceptVisitor(this, context)); } return genericInstanceTypeSignature; } public TypeSignature VisitGenericParameter(GenericParameterSignature signature, GenericContext context) { return context.GetTypeArgument(signature); } public TypeSignature VisitPinnedType(PinnedTypeSignature signature, GenericContext context) { TypeSignature typeSignature = signature.BaseType.AcceptVisitor(this, context); if (typeSignature == signature.BaseType) { return signature; } return new PinnedTypeSignature(typeSignature); } public TypeSignature VisitPointerType(PointerTypeSignature signature, GenericContext context) { TypeSignature typeSignature = signature.BaseType.AcceptVisitor(this, context); if (typeSignature == signature.BaseType) { return signature; } return new PointerTypeSignature(typeSignature); } public TypeSignature VisitSentinelType(SentinelTypeSignature signature, GenericContext context) { return signature; } public TypeSignature VisitSzArrayType(SzArrayTypeSignature signature, GenericContext context) { TypeSignature typeSignature = signature.BaseType.AcceptVisitor(this, context); if (typeSignature == signature.BaseType) { return signature; } return new SzArrayTypeSignature(typeSignature); } public TypeSignature VisitTypeDefOrRef(TypeDefOrRefSignature signature, GenericContext context) { return signature; } public TypeSignature VisitFunctionPointerType(FunctionPointerTypeSignature signature, GenericContext context) { MethodSignature methodSignature = InstantiateMethodSignature(signature.Signature, context); if (methodSignature == signature.Signature) { return signature; } return new FunctionPointerTypeSignature(methodSignature); } } public interface ITypeSignatureResolver { ITypeDefOrRef ResolveToken(ref BlobReaderContext context, MetadataToken token); TypeSignature ResolveRuntimeType(ref BlobReaderContext context, nint address); } public interface ITypeSignatureVisitor { TResult VisitArrayType(ArrayTypeSignature signature); TResult VisitBoxedType(BoxedTypeSignature signature); TResult VisitByReferenceType(ByReferenceTypeSignature signature); TResult VisitCorLibType(CorLibTypeSignature signature); TResult VisitCustomModifierType(CustomModifierTypeSignature signature); TResult VisitGenericInstanceType(GenericInstanceTypeSignature signature); TResult VisitGenericParameter(GenericParameterSignature signature); TResult VisitPinnedType(PinnedTypeSignature signature); TResult VisitPointerType(PointerTypeSignature signature); TResult VisitSentinelType(SentinelTypeSignature signature); TResult VisitSzArrayType(SzArrayTypeSignature signature); TResult VisitTypeDefOrRef(TypeDefOrRefSignature signature); TResult VisitFunctionPointerType(FunctionPointerTypeSignature signature); } public interface ITypeSignatureVisitor { TResult VisitArrayType(ArrayTypeSignature signature, TState state); TResult VisitBoxedType(BoxedTypeSignature signature, TState state); TResult VisitByReferenceType(ByReferenceTypeSignature signature, TState state); TResult VisitCorLibType(CorLibTypeSignature signature, TState state); TResult VisitCustomModifierType(CustomModifierTypeSignature signature, TState state); TResult VisitGenericInstanceType(GenericInstanceTypeSignature signature, TState state); TResult VisitGenericParameter(GenericParameterSignature signature, TState state); TResult VisitPinnedType(PinnedTypeSignature signature, TState state); TResult VisitPointerType(PointerTypeSignature signature, TState state); TResult VisitSentinelType(SentinelTypeSignature signature, TState state); TResult VisitSzArrayType(SzArrayTypeSignature signature, TState state); TResult VisitTypeDefOrRef(TypeDefOrRefSignature signature, TState state); TResult VisitFunctionPointerType(FunctionPointerTypeSignature signature, TState state); } public class PhysicalTypeSignatureResolver : ITypeSignatureResolver { public static PhysicalTypeSignatureResolver Instance { get; } = new PhysicalTypeSignatureResolver(); public virtual ITypeDefOrRef ResolveToken(ref BlobReaderContext context, MetadataToken token) { //IL_0002: 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_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_0041: 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_0011: Invalid comparison between Unknown and I4 //IL_0086: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Invalid comparison between Unknown and I4 TableIndex table = ((MetadataToken)(ref token)).Table; if (table - 1 > 1) { if ((int)table != 27) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid coded index."); return InvalidTypeDefOrRef.Get(InvalidTypeSignatureError.InvalidCodedIndex); } if (!context.StepInToken(token)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Infinite metadata loop was detected."); return InvalidTypeDefOrRef.Get(InvalidTypeSignatureError.MetadataLoop); } } if (context.ReaderContext.ParentModule.TryLookupMember(token, out IMetadataMember member) && member is ITypeDefOrRef result) { if ((int)((MetadataToken)(ref token)).Table == 27) { context.StepOutToken(); } return result; } ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, $"Metadata token in type signature refers to a non-existing TypeDefOrRef member {token}."); return InvalidTypeDefOrRef.Get(InvalidTypeSignatureError.InvalidCodedIndex); } public virtual TypeSignature ResolveRuntimeType(ref BlobReaderContext context, nint address) { throw new NotSupportedException("Encountered an COR_ELEMENT_TYPE_INTERNAL type signature which is not supported by this type signature reader. Use the AsmResolver.DotNet.Dynamic extension package instead."); } } public class PinnedTypeSignature : TypeSpecificationSignature { public override ElementType ElementType => (ElementType)69; public override string? Name => base.BaseType.Name ?? "<>"; public override bool IsValueType => base.BaseType.IsValueType; public PinnedTypeSignature(TypeSignature baseType) : base(baseType) { } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitPinnedType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitPinnedType(this, state); } } public class PointerTypeSignature : TypeSpecificationSignature { public override ElementType ElementType => (ElementType)15; public override string? Name => (base.BaseType?.Name ?? "<>") + "*"; public override bool IsValueType => false; public PointerTypeSignature(TypeSignature baseType) : base(baseType) { } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitPointerType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitPointerType(this, state); } } public class SentinelTypeSignature : TypeSignature { public override ElementType ElementType => (ElementType)65; public override string Name => "<>"; public override string? Namespace => null; public override IResolutionScope? Scope => null; public override bool IsValueType => false; public override TypeDefinition? Resolve() { throw new InvalidOperationException(); } public override ITypeDefOrRef? GetUnderlyingTypeDefOrRef() { return null; } public override bool IsImportedInModule(ModuleDefinition module) { return true; } protected override void WriteContents(in BlobSerializationContext context) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected I4, but got Unknown context.Writer.WriteByte((byte)(int)ElementType); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitSentinelType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitSentinelType(this, state); } } public class SzArrayTypeSignature : TypeSpecificationSignature { public override ElementType ElementType => (ElementType)29; public override string Name => (base.BaseType.Name ?? "<>") + "[]"; public override bool IsValueType => false; public SzArrayTypeSignature(TypeSignature baseType) : base(baseType) { } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitSzArrayType(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitSzArrayType(this, state); } } public class TypeDefOrRefSignature : TypeSignature { private ITypeDefOrRef _type; private bool _isValueType; public ITypeDefOrRef Type { get { return _type; } set { _type = value; _isValueType = value.IsValueType; } } public override ElementType ElementType { get { if (IsValueType) { return (ElementType)17; } return (ElementType)18; } } public override string Name => Utf8String.op_Implicit(Type?.Name ?? Utf8String.op_Implicit("<>")); public override string? Namespace => Utf8String.op_Implicit(Type.Namespace); public override IResolutionScope? Scope => Type.Scope; public override ModuleDefinition? Module => Type.Module; public override bool IsValueType => _isValueType; public TypeDefOrRefSignature(ITypeDefOrRef type) : this(type, type.IsValueType) { } public TypeDefOrRefSignature(ITypeDefOrRef type, bool isValueType) { _type = type; _isValueType = isValueType; } public override TypeDefinition? Resolve() { return Type.Resolve(); } public override bool IsImportedInModule(ModuleDefinition module) { return Type.IsImportedInModule(module); } public override ITypeDefOrRef ToTypeDefOrRef() { return Type; } public override ITypeDefOrRef? GetUnderlyingTypeDefOrRef() { return Type; } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor) { return visitor.VisitTypeDefOrRef(this); } public override TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state) { return visitor.VisitTypeDefOrRef(this, state); } protected override void WriteContents(in BlobSerializationContext context) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected I4, but got Unknown context.Writer.WriteByte((byte)(int)ElementType); WriteTypeDefOrRef(context, Type, "Underlying type"); } } public abstract class TypeSignature : ExtendableBlobSignature, ITypeDescriptor, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable { internal const string NullTypeToString = "<>"; public abstract string? Name { get; } public abstract string? Namespace { get; } public string FullName => MemberNameGenerator.GetTypeFullName(this); public abstract IResolutionScope? Scope { get; } public abstract bool IsValueType { get; } public abstract ElementType ElementType { get; } public virtual ModuleDefinition? Module => Scope?.Module; public ITypeDescriptor? DeclaringType => Scope as ITypeDescriptor; public static TypeSignature FromReader(ref BlobReaderContext context, ref BinaryStreamReader reader) { //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: Invalid comparison between Unknown and I4 //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Invalid comparison between Unknown and I4 //IL_000f: 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_009b: Expected I4, but got Unknown //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Invalid comparison between Unknown and I4 //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Invalid comparison between Unknown and I4 ElementType val = (ElementType)((BinaryStreamReader)(ref reader)).ReadByte(); if ((int)val <= 65) { switch (val - 1) { default: if ((int)val != 65) { break; } return new SentinelTypeSignature(); case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 21: case 23: case 24: case 27: return context.ReaderContext.ParentModule.CorLibTypeFactory.FromElementType(val); case 16: return new TypeDefOrRefSignature(ReadTypeDefOrRef(ref context, ref reader, allowTypeSpec: false), isValueType: true); case 17: return new TypeDefOrRefSignature(ReadTypeDefOrRef(ref context, ref reader, allowTypeSpec: false), isValueType: false); case 14: return new PointerTypeSignature(FromReader(ref context, ref reader)); case 15: return new ByReferenceTypeSignature(FromReader(ref context, ref reader)); case 18: return new GenericParameterSignature(context.ReaderContext.ParentModule, GenericParameterType.Type, (int)((BinaryStreamReader)(ref reader)).ReadCompressedUInt32()); case 29: return new GenericParameterSignature(context.ReaderContext.ParentModule, GenericParameterType.Method, (int)((BinaryStreamReader)(ref reader)).ReadCompressedUInt32()); case 19: return ArrayTypeSignature.FromReader(ref context, ref reader); case 20: return GenericInstanceTypeSignature.FromReader(ref context, ref reader); case 26: return new FunctionPointerTypeSignature(MethodSignature.FromReader(ref context, ref reader)); case 28: return new SzArrayTypeSignature(FromReader(ref context, ref reader)); case 30: return new CustomModifierTypeSignature(ReadTypeDefOrRef(ref context, ref reader, allowTypeSpec: true), isRequired: true, FromReader(ref context, ref reader)); case 31: return new CustomModifierTypeSignature(ReadTypeDefOrRef(ref context, ref reader, allowTypeSpec: true), isRequired: false, FromReader(ref context, ref reader)); case 32: { ITypeSignatureResolver typeSignatureResolver = context.TypeSignatureResolver; nint address = ((IntPtr.Size != 4) ? new IntPtr(((BinaryStreamReader)(ref reader)).ReadInt64()) : new IntPtr(((BinaryStreamReader)(ref reader)).ReadInt32())); return typeSignatureResolver.ResolveRuntimeType(ref context, address); } case 22: case 25: break; } } else { if ((int)val == 69) { return new PinnedTypeSignature(FromReader(ref context, ref reader)); } if ((int)val == 81) { return new BoxedTypeSignature(FromReader(ref context, ref reader)); } } throw new ArgumentOutOfRangeException($"Invalid or unsupported element type {val}."); } protected static ITypeDefOrRef ReadTypeDefOrRef(ref BlobReaderContext context, ref BinaryStreamReader reader, bool allowTypeSpec) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 //IL_0056: Unknown result type (might be due to invalid IL or missing references) uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { return InvalidTypeDefOrRef.Get(InvalidTypeSignatureError.BlobTooShort); } MetadataToken token = context.ReaderContext.ParentModule.GetIndexEncoder((CodedIndex)56).DecodeIndex(num); if ((int)((MetadataToken)(ref token)).Table == 27 && !allowTypeSpec) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid reference to a TypeSpec metadata row."); return InvalidTypeDefOrRef.Get(InvalidTypeSignatureError.IllegalTypeSpec); } return context.TypeSignatureResolver.ResolveToken(ref context, token); } protected void WriteTypeDefOrRef(BlobSerializationContext context, ITypeDefOrRef? type, string propertyName) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) uint num = 0u; if (type == null) { context.ErrorListener.RegisterException((Exception)new InvalidBlobSignatureException(this, $"{ElementType} blob signature {this.SafeToString()} is invalid or incomplete.", new NullReferenceException(propertyName + " is null."))); } else { num = context.IndexProvider.GetTypeDefOrRefIndex(type); } IOExtensions.WriteCompressedUInt32(context.Writer, num); } internal static TypeSignature ReadFieldOrPropType(in BlobReaderContext context, ref BinaryStreamReader reader) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Invalid comparison between Unknown and I4 //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Invalid comparison between Unknown and I4 //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Invalid comparison between Unknown and I4 //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_00a2: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = context.ReaderContext.ParentModule; ElementType val = (ElementType)((BinaryStreamReader)(ref reader)).ReadByte(); if ((int)val <= 80) { if ((int)val == 29) { return new SzArrayTypeSignature(ReadFieldOrPropType(in context, ref reader)); } if ((int)val == 80) { return new TypeDefOrRefSignature(new TypeReference(parentModule, parentModule.CorLibTypeFactory.CorLibScope, Utf8String.op_Implicit("System"), Utf8String.op_Implicit("Type"))); } } else { if ((int)val == 81) { return parentModule.CorLibTypeFactory.Object; } if ((int)val == 85) { string text = Utf8String.op_Implicit(((BinaryStreamReader)(ref reader)).ReadSerString()); if (!string.IsNullOrEmpty(text)) { return TypeNameParser.Parse(parentModule, text); } return new TypeDefOrRefSignature(InvalidTypeDefOrRef.Get(InvalidTypeSignatureError.InvalidFieldOrProptype)); } } return (TypeSignature)(((object)parentModule.CorLibTypeFactory.FromElementType(val)) ?? ((object)new TypeDefOrRefSignature(InvalidTypeDefOrRef.Get(InvalidTypeSignatureError.InvalidFieldOrProptype)))); } internal static void WriteFieldOrPropType(BlobSerializationContext context, TypeSignature type) { //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_000f: 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_0087: Expected I4, but got Unknown //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected I4, but got Unknown IBinaryStreamWriter writer = context.Writer; ElementType elementType = type.ElementType; switch (elementType - 2) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 22: case 23: writer.WriteByte((byte)(int)type.ElementType); return; case 26: writer.WriteByte((byte)81); return; case 27: { writer.WriteByte((byte)29); SzArrayTypeSignature szArrayTypeSignature = (SzArrayTypeSignature)type; WriteFieldOrPropType(context, szArrayTypeSignature.BaseType); return; } } if (type.IsTypeOf("System", "Type")) { writer.WriteByte((byte)80); return; } TypeDefinition typeDefinition = type.Resolve(); if (typeDefinition == null) { context.ErrorListener.MetadataBuilder("Custom attribute argument type " + type.SafeToString() + " could not be resolved."); } else if (!typeDefinition.IsEnum) { context.ErrorListener.MetadataBuilder("Custom attribute argument type " + type.SafeToString() + "is not an enum type."); } writer.WriteByte((byte)85); IOExtensions.WriteSerString(writer, TypeNameBuilder.GetAssemblyQualifiedName(type)); } public abstract TypeDefinition? Resolve(); IMemberDefinition? IMemberDescriptor.Resolve() { return Resolve(); } public virtual ITypeDefOrRef ToTypeDefOrRef() { return new TypeSpecification(this); } TypeSignature ITypeDescriptor.ToTypeSignature() { return this; } public abstract ITypeDefOrRef? GetUnderlyingTypeDefOrRef(); public TypeSignature InstantiateGenericTypes(GenericContext context) { return AcceptVisitor(GenericTypeActivator.Instance, context); } public abstract bool IsImportedInModule(ModuleDefinition module); public TypeSignature ImportWith(ReferenceImporter importer) { return importer.ImportTypeSignature(this); } IImportable IImportable.ImportWith(ReferenceImporter importer) { return ImportWith(importer); } public abstract TResult AcceptVisitor(ITypeSignatureVisitor visitor); public abstract TResult AcceptVisitor(ITypeSignatureVisitor visitor, TState state); public override string ToString() { //IL_002c: Unknown result type (might be due to invalid IL or missing references) if (!string.IsNullOrEmpty(FullName)) { return FullName; } return $"<<<{ElementType}>>>"; } } public abstract class TypeSpecificationSignature : TypeSignature { public TypeSignature BaseType { get; set; } public override ModuleDefinition? Module => BaseType.Module; public override string? Namespace => BaseType.Namespace; public override IResolutionScope? Scope => BaseType.Scope; protected TypeSpecificationSignature(TypeSignature baseType) { BaseType = baseType; } public override TypeDefinition? Resolve() { return BaseType.Resolve(); } public override ITypeDefOrRef? GetUnderlyingTypeDefOrRef() { return BaseType.GetUnderlyingTypeDefOrRef(); } public override bool IsImportedInModule(ModuleDefinition module) { return BaseType.IsImportedInModule(module); } protected override void WriteContents(in BlobSerializationContext context) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected I4, but got Unknown context.Writer.WriteByte((byte)(int)ElementType); WriteBaseType(context); } protected void WriteBaseType(BlobSerializationContext context) { BaseType.Write(in context); } } } namespace AsmResolver.DotNet.Signatures.Types.Parsing { public sealed class TypeNameBuilder : ITypeSignatureVisitor { private readonly TextWriter _writer; private readonly bool _omitCorLib; private TypeNameBuilder(TextWriter writer, bool omitCorLib) { _writer = writer ?? throw new ArgumentNullException("writer"); _omitCorLib = omitCorLib; } public static string GetAssemblyQualifiedName(TypeSignature signature) { return GetAssemblyQualifiedName(signature, omitCorLib: true); } public static string GetAssemblyQualifiedName(TypeSignature signature, bool omitCorLib) { StringWriter stringWriter = new StringWriter(); new TypeNameBuilder(stringWriter, omitCorLib).WriteTypeAssemblyQualifiedName(signature); return stringWriter.ToString(); } private void WriteTypeAssemblyQualifiedName(TypeSignature type) { type.AcceptVisitor(this); AssemblyDescriptor assemblyDescriptor = type.Scope?.GetAssembly(); if (assemblyDescriptor != null && assemblyDescriptor != type.Module?.Assembly && (!assemblyDescriptor.IsCorLib || !_omitCorLib)) { _writer.Write(", "); WriteAssemblySpec(assemblyDescriptor); } } public object? VisitArrayType(ArrayTypeSignature signature) { signature.BaseType.AcceptVisitor(this); _writer.Write('['); for (int i = 0; i < signature.Dimensions.Count; i++) { _writer.Write(','); } _writer.Write(']'); return null; } public object VisitBoxedType(BoxedTypeSignature signature) { throw new NotSupportedException(); } public object? VisitByReferenceType(ByReferenceTypeSignature signature) { signature.BaseType.AcceptVisitor(this); _writer.Write('&'); return null; } public object? VisitCorLibType(CorLibTypeSignature signature) { WriteIdentifier(signature.Namespace); _writer.Write('.'); WriteIdentifier(signature.Name); return null; } public object VisitCustomModifierType(CustomModifierTypeSignature signature) { throw new NotSupportedException(); } public object? VisitGenericInstanceType(GenericInstanceTypeSignature signature) { WriteSimpleTypeName(signature.GenericType); _writer.Write('['); for (int i = 0; i < signature.TypeArguments.Count; i++) { _writer.Write('['); WriteTypeAssemblyQualifiedName(signature.TypeArguments[i]); _writer.Write(']'); if (i < signature.TypeArguments.Count - 1) { _writer.Write(','); } } _writer.Write(']'); return null; } public object VisitGenericParameter(GenericParameterSignature signature) { throw new NotSupportedException(); } public object VisitPinnedType(PinnedTypeSignature signature) { throw new NotSupportedException(); } public object? VisitPointerType(PointerTypeSignature signature) { signature.BaseType.AcceptVisitor(this); _writer.Write('*'); return null; } public object VisitSentinelType(SentinelTypeSignature signature) { throw new NotSupportedException(); } public object? VisitSzArrayType(SzArrayTypeSignature signature) { signature.BaseType.AcceptVisitor(this); _writer.Write("[]"); return null; } public object? VisitTypeDefOrRef(TypeDefOrRefSignature signature) { WriteSimpleTypeName(signature.Type); return null; } public object VisitFunctionPointerType(FunctionPointerTypeSignature signature) { throw new NotSupportedException("Function pointer type signatures are not supported in type name building."); } private void WriteSimpleTypeName(ITypeDefOrRef? type) { List list = new List(); while (type != null) { list.Add(type); type = type.DeclaringType; } string text = Utf8String.op_Implicit(list[list.Count - 1].Namespace); if (!string.IsNullOrEmpty(text)) { WriteIdentifier(text, escapeDots: true); _writer.Write('.'); } WriteIdentifier(Utf8String.op_Implicit(list[list.Count - 1].Name)); for (int num = list.Count - 2; num >= 0; num--) { _writer.Write('+'); WriteIdentifier(Utf8String.op_Implicit(list[num].Name)); } } private void WriteAssemblySpec(AssemblyDescriptor assembly) { WriteIdentifier(Utf8String.op_Implicit(assembly.Name), escapeDots: true); _writer.Write(", Version="); _writer.Write(assembly.Version.ToString()); _writer.Write(", PublicKeyToken="); byte[] publicKeyToken = assembly.GetPublicKeyToken(); if (publicKeyToken == null) { _writer.Write("null"); } else { WriteHexBlob(publicKeyToken); } _writer.Write(", Culture="); WriteIdentifier(Utf8String.op_Implicit(assembly.Culture ?? Utf8String.op_Implicit("neutral"))); } private void WriteIdentifier(string? identifier, bool escapeDots = false) { if (string.IsNullOrEmpty(identifier)) { return; } foreach (char c in identifier) { if (TypeNameLexer.ReservedChars.Contains(c) && (c != '.' || !escapeDots)) { _writer.Write('\\'); } _writer.Write(c); } } private void WriteHexBlob(byte[] token) { foreach (byte b in token) { _writer.Write(b.ToString("x2")); } } } internal struct TypeNameLexer { internal static readonly ISet ReservedChars = new HashSet("*+.,&[]…"); private static readonly char[] TrimCharacters = " ".ToCharArray(); private readonly TextReader _reader; private readonly StringBuilder _buffer; private TypeNameToken? _bufferedToken; public bool HasConsumedTypeName { get; set; } public TypeNameLexer(TextReader reader) { _buffer = new StringBuilder(); _reader = reader ?? throw new ArgumentNullException("reader"); HasConsumedTypeName = false; _bufferedToken = null; } public TypeNameToken Peek() { TypeNameToken? bufferedToken = _bufferedToken; if (!bufferedToken.HasValue) { _bufferedToken = ReadNextToken(); } return _bufferedToken.GetValueOrDefault(); } public TypeNameToken Next() { if (_bufferedToken.HasValue) { TypeNameToken value = _bufferedToken.Value; _bufferedToken = null; return value; } return ReadNextToken() ?? throw new EndOfStreamException(); } private TypeNameToken? ReadNextToken() { SkipWhitespaces(); _buffer.Clear(); int num = _reader.Peek(); if (num == -1) { return null; } char c = (char)num; return c switch { '*' => ReadSymbolToken(TypeNameTerminal.Star), '+' => ReadSymbolToken(TypeNameTerminal.Plus), '=' => ReadSymbolToken(TypeNameTerminal.Equals), '.' => ReadDotToken(), ',' => ReadSymbolToken(TypeNameTerminal.Comma), '&' => ReadSymbolToken(TypeNameTerminal.Ampersand), '[' => ReadSymbolToken(TypeNameTerminal.OpenBracket), ']' => ReadSymbolToken(TypeNameTerminal.CloseBracket), '…' => ReadSymbolToken(TypeNameTerminal.Ellipsis), _ => char.IsDigit(c) ? ReadNumberOrIdentifierToken() : ReadIdentifierToken(), }; } private TypeNameToken ReadDotToken() { _reader.Read(); if (_reader.Peek() == 46) { _reader.Read(); return new TypeNameToken(TypeNameTerminal.DoubleDot, ".."); } return new TypeNameToken(TypeNameTerminal.Dot, "."); } private TypeNameToken ReadNumberOrIdentifierToken() { bool flag = false; TypeNameTerminal typeNameTerminal = TypeNameTerminal.Number; while (true) { int num = _reader.Peek(); if (num == -1) { break; } char c = (char)num; if (flag) { flag = false; } else if (c == '\\') { flag = true; } else if ((c == '=' && HasConsumedTypeName) || (typeNameTerminal == TypeNameTerminal.Number && (char.IsWhiteSpace(c) || ReservedChars.Contains(c)))) { break; } if (!char.IsDigit(c)) { typeNameTerminal = TypeNameTerminal.Identifier; } _reader.Read(); if (!flag) { _buffer.Append(c); } } return new TypeNameToken(typeNameTerminal, _buffer.ToString().Trim(TrimCharacters)); } private TypeNameToken ReadIdentifierToken() { bool flag = false; while (true) { int num = _reader.Peek(); if (num == -1) { break; } char c = (char)num; if (flag) { flag = false; } else if (c == '\\') { flag = true; } else if ((c == '=' && HasConsumedTypeName) || ReservedChars.Contains(c)) { break; } _reader.Read(); if (!flag) { _buffer.Append(c); } } return new TypeNameToken(TypeNameTerminal.Identifier, _buffer.ToString().Trim(TrimCharacters)); } private TypeNameToken ReadSymbolToken(TypeNameTerminal terminal) { string text = ((char)_reader.Read()).ToString(); return new TypeNameToken(terminal, text); } private void SkipWhitespaces() { while (true) { int num = _reader.Peek(); if (num != -1 && char.IsWhiteSpace((char)num)) { _reader.Read(); continue; } break; } } } public struct TypeNameParser { private static readonly SignatureComparer Comparer = new SignatureComparer(); private readonly ModuleDefinition _module; private TypeNameLexer _lexer; private TypeNameParser(ModuleDefinition module, TypeNameLexer lexer) { _module = module ?? throw new ArgumentNullException("module"); _lexer = lexer; } public static TypeSignature Parse(ModuleDefinition module, string canonicalName) { TypeNameLexer lexer = new TypeNameLexer(new StringReader(canonicalName)); return new TypeNameParser(module, lexer).ParseTypeSpec(); } private TypeSignature ParseTypeSpec() { bool hasConsumedTypeName = _lexer.HasConsumedTypeName; _lexer.HasConsumedTypeName = false; TypeSignature typeSignature = ParseSimpleTypeSpec(); _lexer.HasConsumedTypeName = true; object obj; if (!TryExpect(TypeNameTerminal.Comma).HasValue) { obj = null; } else { IResolutionScope resolutionScope = ParseAssemblyNameSpec(); obj = resolutionScope; } IResolutionScope newScope = (IResolutionScope)obj; _lexer.HasConsumedTypeName = hasConsumedTypeName; if (typeSignature.GetUnderlyingTypeDefOrRef() is TypeReference reference) { SetScope(reference, newScope); } if (Comparer.Equals(typeSignature.Scope, _module.CorLibTypeFactory.CorLibScope)) { CorLibTypeSignature corLibTypeSignature = _module.CorLibTypeFactory.FromType(typeSignature); if (corLibTypeSignature != null) { return corLibTypeSignature; } } return typeSignature; } private void SetScope(TypeReference reference, IResolutionScope? newScope) { while (reference.Scope is TypeReference typeReference) { reference = typeReference; } if (newScope != null) { reference.Scope = newScope; return; } reference.Scope = _module; if (reference.Resolve() == null) { reference.Scope = _module.CorLibTypeFactory.CorLibScope; if (reference.Resolve() == null) { reference.Scope = _module; } } } private TypeSignature ParseSimpleTypeSpec() { TypeSignature typeSignature = ParseTypeName(); while (true) { switch (_lexer.Peek().Terminal) { case TypeNameTerminal.Ampersand: typeSignature = ParseByReferenceTypeSpec(typeSignature); break; case TypeNameTerminal.Star: typeSignature = ParsePointerTypeSpec(typeSignature); break; case TypeNameTerminal.OpenBracket: typeSignature = ParseArrayOrGenericTypeSpec(typeSignature); break; default: return typeSignature; } } } private TypeSignature ParseByReferenceTypeSpec(TypeSignature typeName) { Expect(TypeNameTerminal.Ampersand); return new ByReferenceTypeSignature(typeName); } private TypeSignature ParsePointerTypeSpec(TypeSignature typeName) { Expect(TypeNameTerminal.Star); return new PointerTypeSignature(typeName); } private TypeSignature ParseArrayOrGenericTypeSpec(TypeSignature typeName) { Expect(TypeNameTerminal.OpenBracket); TypeNameTerminal terminal = _lexer.Peek().Terminal; if (terminal == TypeNameTerminal.Identifier || terminal == TypeNameTerminal.OpenBracket) { return ParseGenericTypeSpec(typeName); } return ParseArrayTypeSpec(typeName); } private TypeSignature ParseArrayTypeSpec(TypeSignature typeName) { List list = new List { ParseArrayDimension() }; bool flag = false; while (!flag) { switch (Expect(TypeNameTerminal.CloseBracket, TypeNameTerminal.Comma).Terminal) { case TypeNameTerminal.CloseBracket: flag = true; break; case TypeNameTerminal.Comma: list.Add(ParseArrayDimension()); break; } } if (list.Count == 1 && !list[0].Size.HasValue && !list[0].LowerBound.HasValue) { return new SzArrayTypeSignature(typeName); } ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature(typeName); foreach (ArrayDimension item in list) { arrayTypeSignature.Dimensions.Add(item); } return arrayTypeSignature; } private ArrayDimension ParseArrayDimension() { switch (_lexer.Peek().Terminal) { case TypeNameTerminal.Comma: case TypeNameTerminal.CloseBracket: return default(ArrayDimension); case TypeNameTerminal.Number: { int? size = null; int? lowerBound = null; int num = int.Parse(_lexer.Next().Text); if (TryExpect(TypeNameTerminal.Ellipsis, TypeNameTerminal.DoubleDot).HasValue) { TypeNameToken? typeNameToken = TryExpect(TypeNameTerminal.Number); if (typeNameToken.HasValue) { int num2 = int.Parse(typeNameToken.Value.Text); size = num2 - num; lowerBound = num; } else { lowerBound = num; } } return new ArrayDimension(size, lowerBound); } default: Expect(TypeNameTerminal.CloseBracket, TypeNameTerminal.Comma, TypeNameTerminal.Number); return default(ArrayDimension); } } private TypeSignature ParseGenericTypeSpec(TypeSignature typeName) { GenericInstanceTypeSignature genericInstanceTypeSignature = new GenericInstanceTypeSignature(typeName.ToTypeDefOrRef(), typeName.IsValueType); genericInstanceTypeSignature.TypeArguments.Add(ParseGenericTypeArgument(genericInstanceTypeSignature)); bool flag = false; while (!flag) { switch (Expect(TypeNameTerminal.CloseBracket, TypeNameTerminal.Comma).Terminal) { case TypeNameTerminal.CloseBracket: flag = true; break; case TypeNameTerminal.Comma: genericInstanceTypeSignature.TypeArguments.Add(ParseGenericTypeArgument(genericInstanceTypeSignature)); break; } } return genericInstanceTypeSignature; } private TypeSignature ParseGenericTypeArgument(GenericInstanceTypeSignature genericInstance) { TypeNameToken? typeNameToken = TryExpect(TypeNameTerminal.OpenBracket); TypeSignature result = ((!typeNameToken.HasValue) ? ParseSimpleTypeSpec() : ParseTypeSpec()); if (typeNameToken.HasValue) { Expect(TypeNameTerminal.CloseBracket); } return result; } private TypeSignature ParseTypeName() { (string? Namespace, IList TypeNames) tuple = ParseNamespaceTypeName(); string item = tuple.Namespace; IList item2 = tuple.TypeNames; TypeReference typeReference = null; for (int i = 0; i < item2.Count; i++) { typeReference = ((typeReference == null) ? new TypeReference(_module, _module, Utf8String.op_Implicit(item), Utf8String.op_Implicit(item2[i])) : new TypeReference(_module, typeReference, null, Utf8String.op_Implicit(item2[i]))); } if (typeReference == null) { throw new FormatException(); } return typeReference.ToTypeSignature(); } private (string? Namespace, IList TypeNames) ParseNamespaceTypeName() { List list = ParseDottedExpression(TypeNameTerminal.Identifier); string item; if (list.Count > 1) { item = string.Join(".", list.Take(list.Count - 1)); list.RemoveRange(0, list.Count - 1); } else { item = null; } while (TryExpect(TypeNameTerminal.Plus).HasValue) { list.Add(Expect(TypeNameTerminal.Identifier).Text); } return (item, list); } private List ParseDottedExpression(TypeNameTerminal terminal) { List list = new List(); do { TypeNameToken? typeNameToken = TryExpect(terminal); if (!typeNameToken.HasValue) { break; } list.Add(typeNameToken.Value.Text); } while (TryExpect(TypeNameTerminal.Dot).HasValue); if (list.Count == 0) { throw new FormatException($"Expected {terminal}."); } return list; } private AssemblyReference ParseAssemblyNameSpec() { AssemblyReference assemblyReference = new AssemblyReference(Utf8String.op_Implicit(string.Join(".", ParseDottedExpression(TypeNameTerminal.Identifier))), new Version()); while (TryExpect(TypeNameTerminal.Comma).HasValue) { string text = Expect(TypeNameTerminal.Identifier).Text; Expect(TypeNameTerminal.Equals); if (text.Equals("version", StringComparison.OrdinalIgnoreCase)) { assemblyReference.Version = ParseVersion(); continue; } if (text.Equals("publickey", StringComparison.OrdinalIgnoreCase)) { assemblyReference.PublicKeyOrToken = ParseHexBlob(); assemblyReference.HasPublicKey = true; continue; } if (text.Equals("publickeytoken", StringComparison.OrdinalIgnoreCase)) { assemblyReference.PublicKeyOrToken = ParseHexBlob(); assemblyReference.HasPublicKey = false; continue; } if (text.Equals("culture", StringComparison.OrdinalIgnoreCase)) { string text2 = ParseCulture(); assemblyReference.Culture = Utf8String.op_Implicit((!text2.Equals("neutral", StringComparison.OrdinalIgnoreCase)) ? text2 : null); continue; } throw new FormatException("Unsupported " + text + " assembly property."); } for (int i = 0; i < _module.AssemblyReferences.Count; i++) { AssemblyReference assemblyReference2 = _module.AssemblyReferences[i]; if (Comparer.Equals((AssemblyDescriptor?)assemblyReference2, (AssemblyDescriptor?)assemblyReference)) { return assemblyReference2; } } return assemblyReference; } private Version ParseVersion() { return Version.Parse(string.Join(".", ParseDottedExpression(TypeNameTerminal.Number))); } private byte[]? ParseHexBlob() { string text = Expect(TypeNameTerminal.Identifier, TypeNameTerminal.Number).Text; if (text == "null") { return null; } if (text.Length % 2 != 0) { throw new FormatException("Provided hex string does not have an even length."); } byte[] array = new byte[text.Length / 2]; for (int i = 0; i < text.Length; i += 2) { array[i / 2] = ParseHexByte(text, i); } return array; } private static byte ParseHexByte(string hexString, int index) { return (byte)((ParseHexNibble(hexString[index]) << 4) | ParseHexNibble(hexString[index + 1])); } private static byte ParseHexNibble(char nibble) { switch (nibble) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return (byte)(nibble - 48); case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return (byte)(nibble - 65 + 10); case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': return (byte)(nibble - 97 + 10); default: throw new FormatException(); } } private string ParseCulture() { return Expect(TypeNameTerminal.Identifier).Text; } private TypeNameToken Expect(TypeNameTerminal terminal) { return TryExpect(terminal) ?? throw new FormatException($"Expected {terminal}."); } private TypeNameToken? TryExpect(TypeNameTerminal terminal) { TypeNameToken value = _lexer.Peek(); if (terminal != value.Terminal) { return null; } _lexer.Next(); return value; } private TypeNameToken Expect(params TypeNameTerminal[] terminals) { return TryExpect(terminals) ?? throw new FormatException("Expected one of " + string.Join(", ", terminals) + "."); } private TypeNameToken? TryExpect(params TypeNameTerminal[] terminals) { TypeNameToken value = _lexer.Peek(); if (!terminals.Contains(value.Terminal)) { return null; } _lexer.Next(); return value; } } internal enum TypeNameTerminal { Eof, Identifier, Number, Star, Plus, Equals, Dot, DoubleDot, Comma, Ampersand, OpenBracket, CloseBracket, Ellipsis } internal readonly struct TypeNameToken { public TypeNameTerminal Terminal { get; } public string Text { get; } public TypeNameToken(TypeNameTerminal terminal, string text) { Terminal = terminal; Text = text; } public override string ToString() { return $"{Text} ({Terminal})"; } } } namespace AsmResolver.DotNet.Signatures.Security { public class PermissionSetSignature : ExtendableBlobSignature { public IList Attributes { get; } = new List(); public static PermissionSetSignature FromReader(in BlobReaderContext context, ref BinaryStreamReader reader) { PermissionSetSignature permissionSetSignature = new PermissionSetSignature(); if (((BinaryStreamReader)(ref reader)).ReadByte() != 46) { return permissionSetSignature; } uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { return permissionSetSignature; } for (int i = 0; i < num; i++) { if (!((BinaryStreamReader)(ref reader)).CanRead(1u)) { break; } permissionSetSignature.Attributes.Add(SecurityAttribute.FromReader(in context, ref reader)); } return permissionSetSignature; } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)46); IOExtensions.WriteCompressedUInt32(writer, (uint)Attributes.Count); for (int i = 0; i < Attributes.Count; i++) { Attributes[i].Write(context); } } } public class SecurityAttribute { public TypeSignature AttributeType { get; set; } public IList NamedArguments { get; } = new List(); public static SecurityAttribute FromReader(in BlobReaderContext context, ref BinaryStreamReader reader) { string text = Utf8String.op_Implicit(((BinaryStreamReader)(ref reader)).ReadSerString()); SecurityAttribute securityAttribute = new SecurityAttribute(string.IsNullOrEmpty(text) ? new TypeDefOrRefSignature(InvalidTypeDefOrRef.Get(InvalidTypeSignatureError.InvalidFieldOrProptype)) : TypeNameParser.Parse(context.ReaderContext.ParentModule, text)); uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid size in security attribute."); return securityAttribute; } uint num2 = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num2)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context.ReaderContext, "Invalid number of arguments in security attribute."); return securityAttribute; } for (int i = 0; i < num2; i++) { securityAttribute.NamedArguments.Add(CustomAttributeNamedArgument.FromReader(in context, ref reader)); } return securityAttribute; } public SecurityAttribute(TypeSignature type) { AttributeType = type; } public void Write(BlobSerializationContext context) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown IBinaryStreamWriter writer = context.Writer; string assemblyQualifiedName = TypeNameBuilder.GetAssemblyQualifiedName(AttributeType); IOExtensions.WriteSerString(writer, assemblyQualifiedName); if (NamedArguments.Count == 0) { IOExtensions.WriteCompressedUInt32(writer, 1u); IOExtensions.WriteCompressedUInt32(writer, 0u); return; } using MemoryStream memoryStream = new MemoryStream(); BlobSerializationContext context2 = new BlobSerializationContext((IBinaryStreamWriter)new BinaryStreamWriter((Stream)memoryStream), context.IndexProvider, context.ErrorListener); IOExtensions.WriteCompressedUInt32(context2.Writer, (uint)NamedArguments.Count); foreach (CustomAttributeNamedArgument namedArgument in NamedArguments) { namedArgument.Write(context2); } IOExtensions.WriteCompressedUInt32(writer, (uint)memoryStream.Length); IOExtensions.WriteBytes(writer, memoryStream.ToArray()); } public override string ToString() { return $"{AttributeType}({string.Join(", ", NamedArguments)})"; } } } namespace AsmResolver.DotNet.Signatures.Marshal { public class ComInterfaceMarshalDescriptor : MarshalDescriptor { public override NativeType NativeType { get; } public int? IidParameterIndex { get; set; } public static ComInterfaceMarshalDescriptor FromReader(NativeType type, ref BinaryStreamReader reader) { ComInterfaceMarshalDescriptor comInterfaceMarshalDescriptor = new ComInterfaceMarshalDescriptor(type); uint value = default(uint); if (((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref value)) { comInterfaceMarshalDescriptor.IidParameterIndex = (int)value; } return comInterfaceMarshalDescriptor; } public ComInterfaceMarshalDescriptor(NativeType nativeType) { if (nativeType - 25 <= NativeType.Void || nativeType == NativeType.Interface) { NativeType = nativeType; return; } throw new ArgumentOutOfRangeException("nativeType"); } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)NativeType); if (IidParameterIndex.HasValue) { IOExtensions.WriteCompressedUInt32(writer, (uint)IidParameterIndex.Value); } } } public class CustomMarshalDescriptor : MarshalDescriptor { public override NativeType NativeType => NativeType.CustomMarshaller; public string? Guid { get; set; } public Utf8String? NativeTypeName { get; set; } public TypeSignature? MarshalType { get; set; } public Utf8String? Cookie { get; set; } public new static CustomMarshalDescriptor FromReader(ModuleDefinition parentModule, ref BinaryStreamReader reader) { string guid = Utf8String.op_Implicit(((BinaryStreamReader)(ref reader)).ReadSerString()); Utf8String nativeTypeName = ((BinaryStreamReader)(ref reader)).ReadSerString(); string text = Utf8String.op_Implicit(((BinaryStreamReader)(ref reader)).ReadSerString()); return new CustomMarshalDescriptor(cookie: ((BinaryStreamReader)(ref reader)).ReadSerString(), guid: guid, nativeTypeName: nativeTypeName, marshalType: (text == null) ? null : TypeNameParser.Parse(parentModule, text)); } public CustomMarshalDescriptor(string? guid, Utf8String? nativeTypeName, TypeSignature? marshalType, Utf8String? cookie) { Guid = guid; NativeTypeName = nativeTypeName; MarshalType = marshalType; Cookie = cookie; } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)NativeType); IOExtensions.WriteSerString(writer, Guid ?? string.Empty); IOExtensions.WriteSerString(writer, NativeTypeName ?? Utf8String.Empty); IOExtensions.WriteSerString(writer, (MarshalType == null) ? string.Empty : TypeNameBuilder.GetAssemblyQualifiedName(MarshalType)); IOExtensions.WriteSerString(writer, Cookie ?? Utf8String.Empty); } } public class FixedArrayMarshalDescriptor : MarshalDescriptor { public override NativeType NativeType => NativeType.FixedArray; public int? Size { get; set; } public NativeType? ArrayElementType { get; set; } public static FixedArrayMarshalDescriptor FromReader(ref BinaryStreamReader reader) { FixedArrayMarshalDescriptor fixedArrayMarshalDescriptor = new FixedArrayMarshalDescriptor(); uint num = default(uint); if (((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { fixedArrayMarshalDescriptor.Size = (int)num; if (((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { fixedArrayMarshalDescriptor.ArrayElementType = (NativeType)num; } } return fixedArrayMarshalDescriptor; } public FixedArrayMarshalDescriptor() { } public FixedArrayMarshalDescriptor(int size) { Size = size; } public FixedArrayMarshalDescriptor(int size, NativeType arrayElementType) { Size = size; ArrayElementType = arrayElementType; } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)NativeType); if (Size.HasValue) { IOExtensions.WriteCompressedUInt32(writer, (uint)Size.Value); if (ArrayElementType.HasValue) { IOExtensions.WriteCompressedUInt32(writer, (uint)ArrayElementType.Value); } } } } public class FixedSysStringMarshalDescriptor : MarshalDescriptor { public override NativeType NativeType => NativeType.FixedSysString; public int Size { get; set; } public static FixedSysStringMarshalDescriptor FromReader(ref BinaryStreamReader reader) { uint size = default(uint); ((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref size); return new FixedSysStringMarshalDescriptor((int)size); } public FixedSysStringMarshalDescriptor(int size) { Size = size; } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)NativeType); IOExtensions.WriteCompressedUInt32(writer, (uint)Size); } } [Flags] public enum LPArrayFlags : ushort { SizeParamIndexSpecified = 1, Reserved = 0xFFFE } public class LPArrayMarshalDescriptor : MarshalDescriptor { public override NativeType NativeType => NativeType.LPArray; public NativeType? ArrayElementType { get; set; } public int? ParameterIndex { get; set; } public int? NumberOfElements { get; set; } public LPArrayFlags? Flags { get; set; } public static LPArrayMarshalDescriptor FromReader(ref BinaryStreamReader reader) { LPArrayMarshalDescriptor lPArrayMarshalDescriptor = new LPArrayMarshalDescriptor(); if (!((BinaryStreamReader)(ref reader)).CanRead(1u)) { return lPArrayMarshalDescriptor; } lPArrayMarshalDescriptor.ArrayElementType = (NativeType)((BinaryStreamReader)(ref reader)).ReadByte(); uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { return lPArrayMarshalDescriptor; } lPArrayMarshalDescriptor.ParameterIndex = (int)num; if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { return lPArrayMarshalDescriptor; } lPArrayMarshalDescriptor.NumberOfElements = (int)num; if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { return lPArrayMarshalDescriptor; } lPArrayMarshalDescriptor.Flags = (LPArrayFlags)num; return lPArrayMarshalDescriptor; } public LPArrayMarshalDescriptor() { } public LPArrayMarshalDescriptor(NativeType? arrayElementType) { ArrayElementType = arrayElementType; } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)NativeType); if (!ArrayElementType.HasValue) { return; } writer.WriteByte((byte)ArrayElementType.Value); if (!ParameterIndex.HasValue) { return; } IOExtensions.WriteCompressedUInt32(writer, (uint)ParameterIndex.Value); if (NumberOfElements.HasValue) { IOExtensions.WriteCompressedUInt32(writer, (uint)NumberOfElements.Value); if (Flags.HasValue) { IOExtensions.WriteCompressedUInt32(writer, (uint)Flags.Value); } } } } public abstract class MarshalDescriptor : ExtendableBlobSignature { public abstract NativeType NativeType { get; } public static MarshalDescriptor FromReader(ModuleDefinition parentModule, ref BinaryStreamReader reader) { NativeType nativeType = (NativeType)((BinaryStreamReader)(ref reader)).ReadByte(); object obj = nativeType switch { NativeType.SafeArray => SafeArrayMarshalDescriptor.FromReader(parentModule, ref reader), NativeType.FixedArray => FixedArrayMarshalDescriptor.FromReader(ref reader), NativeType.LPArray => LPArrayMarshalDescriptor.FromReader(ref reader), NativeType.CustomMarshaller => CustomMarshalDescriptor.FromReader(parentModule, ref reader), NativeType.FixedSysString => FixedSysStringMarshalDescriptor.FromReader(ref reader), NativeType.Interface => ComInterfaceMarshalDescriptor.FromReader(nativeType, ref reader), NativeType.IDispatch => ComInterfaceMarshalDescriptor.FromReader(nativeType, ref reader), NativeType.IUnknown => ComInterfaceMarshalDescriptor.FromReader(nativeType, ref reader), _ => new SimpleMarshalDescriptor(nativeType), }; ((ExtendableBlobSignature)obj).ExtraData = ((BinaryStreamReader)(ref reader)).ReadToEnd(); return (MarshalDescriptor)obj; } } public enum NativeType : byte { Void = 1, Boolean = 2, I1 = 3, U1 = 4, I2 = 5, U2 = 6, I4 = 7, U4 = 8, I8 = 9, U8 = 10, R4 = 11, R8 = 12, SysChar = 13, Variant = 14, Currency = 15, Ptr = 16, Decimal = 17, Date = 18, BStr = 19, LPStr = 20, LPWStr = 21, LPTStr = 22, FixedSysString = 23, ObjectRef = 24, IUnknown = 25, IDispatch = 26, Struct = 27, Interface = 28, SafeArray = 29, FixedArray = 30, SysInt = 31, SysUInt = 32, NestedStruct = 33, ByValStr = 34, AnsiBStr = 35, TBStr = 36, VariantBool = 37, FunctionPointer = 38, AsAny = 40, LPArray = 42, LPStruct = 43, CustomMarshaller = 44, Error = 45, IInspectable = 46, HString = 47, LPUTF8Str = 48, Max = 80 } public class SafeArrayMarshalDescriptor : MarshalDescriptor { public override NativeType NativeType => NativeType.SafeArray; public SafeArrayVariantType VariantType { get; set; } public SafeArrayTypeFlags VariantTypeFlags { get; set; } public bool IsVector { get { return (VariantTypeFlags & SafeArrayTypeFlags.Vector) != 0; } set { VariantTypeFlags = (VariantTypeFlags & ~SafeArrayTypeFlags.Vector) | (value ? SafeArrayTypeFlags.Vector : ((SafeArrayTypeFlags)0)); } } public bool IsArray { get { return (VariantTypeFlags & SafeArrayTypeFlags.Array) != 0; } set { VariantTypeFlags = (VariantTypeFlags & ~SafeArrayTypeFlags.Array) | (value ? SafeArrayTypeFlags.Array : ((SafeArrayTypeFlags)0)); } } public bool IsByRef { get { return (VariantTypeFlags & SafeArrayTypeFlags.ByRef) != 0; } set { VariantTypeFlags = (VariantTypeFlags & ~SafeArrayTypeFlags.ByRef) | (value ? SafeArrayTypeFlags.ByRef : ((SafeArrayTypeFlags)0)); } } public TypeSignature? UserDefinedSubType { get; set; } public new static SafeArrayMarshalDescriptor FromReader(ModuleDefinition parentModule, ref BinaryStreamReader reader) { uint num = default(uint); if (!((BinaryStreamReader)(ref reader)).TryReadCompressedUInt32(ref num)) { return new SafeArrayMarshalDescriptor(SafeArrayVariantType.NotSet); } uint variantType = num & 0xFFF; SafeArrayTypeFlags flags = (SafeArrayTypeFlags)((int)num & -61441); SafeArrayMarshalDescriptor safeArrayMarshalDescriptor = new SafeArrayMarshalDescriptor((SafeArrayVariantType)variantType, flags); if (((BinaryStreamReader)(ref reader)).CanRead(1u)) { string text = Utf8String.op_Implicit(((BinaryStreamReader)(ref reader)).ReadSerString()); if (text != null) { safeArrayMarshalDescriptor.UserDefinedSubType = TypeNameParser.Parse(parentModule, text); } } return safeArrayMarshalDescriptor; } public SafeArrayMarshalDescriptor(SafeArrayVariantType variantType) { VariantType = variantType; } public SafeArrayMarshalDescriptor(SafeArrayVariantType variantType, SafeArrayTypeFlags flags) { VariantType = variantType; VariantTypeFlags = flags; } public SafeArrayMarshalDescriptor(SafeArrayVariantType variantType, SafeArrayTypeFlags flags, TypeSignature? subType) { VariantType = variantType; VariantTypeFlags = flags; UserDefinedSubType = subType; } protected override void WriteContents(in BlobSerializationContext context) { IBinaryStreamWriter writer = context.Writer; writer.WriteByte((byte)NativeType); if (VariantType != SafeArrayVariantType.NotSet) { IOExtensions.WriteCompressedUInt32(writer, (uint)(VariantType & SafeArrayVariantType.TypeMask) | (uint)VariantTypeFlags); if (UserDefinedSubType != null) { IOExtensions.WriteSerString(writer, TypeNameBuilder.GetAssemblyQualifiedName(UserDefinedSubType)); } } } } [Flags] public enum SafeArrayTypeFlags { Vector = 0x1000, Array = 0x2000, ByRef = 0x4000, Mask = 0xF000 } public enum SafeArrayVariantType { Empty = 0, Null = 1, I2 = 2, I4 = 3, R4 = 4, R8 = 5, CY = 6, Date = 7, BStr = 8, Dispatch = 9, Error = 10, Bool = 11, Variant = 12, Unknown = 13, Decimal = 14, I1 = 16, UI1 = 17, UI2 = 18, UI4 = 19, I8 = 20, UI8 = 21, Int = 22, UInt = 23, Void = 24, HResult = 25, Ptr = 26, SafeArray = 27, CArray = 28, UserDefined = 29, LPStr = 30, LPWStr = 31, Record = 36, IntPtr = 37, UIntPtr = 38, FileTime = 64, Blob = 65, Stream = 66, Storage = 67, StreamedObject = 68, StoredObject = 69, BlobObject = 70, CF = 71, CLSID = 72, TypeMask = 4095, NotSet = 65535 } public class SimpleMarshalDescriptor : MarshalDescriptor { public override NativeType NativeType { get; } public SimpleMarshalDescriptor(NativeType nativeType) { NativeType = nativeType; } protected override void WriteContents(in BlobSerializationContext context) { context.Writer.WriteByte((byte)NativeType); } } } namespace AsmResolver.DotNet.Serialized { internal class CachedSerializedMemberFactory { private readonly ModuleReaderContext _context; private readonly TablesStream _tablesStream; private TypeReference?[]? _typeReferences; private TypeDefinition?[]? _typeDefinitions; private FieldDefinition?[]? _fieldDefinitions; private MethodDefinition?[]? _methodDefinitions; private ParameterDefinition?[]? _parameterDefinitions; private MemberReference?[]? _memberReferences; private StandAloneSignature?[]? _standAloneSignatures; private PropertyDefinition?[]? _propertyDefinitions; private EventDefinition?[]? _eventDefinition; private MethodSemantics?[]? _methodSemantics; private TypeSpecification?[]? _typeSpecifications; private CustomAttribute?[]? _customAttributes; private MethodSpecification?[]? _methodSpecifications; private GenericParameter?[]? _genericParameters; private GenericParameterConstraint?[]? _genericParameterConstraints; private ModuleReference?[]? _moduleReferences; private FileReference?[]? _fileReferences; private ManifestResource?[]? _resources; private ExportedType?[]? _exportedTypes; private Constant?[]? _constants; private ClassLayout?[]? _classLayouts; private ImplementationMap?[]? _implementationMaps; private InterfaceImplementation?[]? _interfaceImplementations; private SecurityDeclaration?[]? _securityDeclarations; internal CachedSerializedMemberFactory(ModuleReaderContext context) { _context = context ?? throw new ArgumentNullException("context"); _tablesStream = _context.TablesStream; } internal bool TryLookupMember(MetadataToken token, [NotNullWhen(true)] out IMetadataMember? member) { //IL_0002: 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_00c2: Expected I4, but got Unknown //IL_00d6: 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_0117: 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_0131: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_014b: 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_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: 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_010a: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: 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_01bc: 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_0189: Unknown result type (might be due to invalid IL or missing references) TableIndex table = ((MetadataToken)(ref token)).Table; member = (int)table switch { 0 => LookupModuleDefinition(in token), 1 => LookupTypeReference(token), 2 => LookupTypeDefinition(token), 27 => LookupTypeSpecification(token), 32 => LookupAssemblyDefinition(token), 35 => LookupAssemblyReference(token), 4 => LookupFieldDefinition(token), 6 => LookupMethodDefinition(token), 8 => LookupParameterDefinition(token), 10 => LookupMemberReference(token), 17 => LookupStandAloneSignature(token), 23 => LookupPropertyDefinition(token), 20 => LookupEventDefinition(token), 24 => LookupMethodSemantics(token), 12 => LookupCustomAttribute(token), 43 => LookupMethodSpecification(token), 42 => LookupGenericParameter(token), 44 => LookupGenericParameterConstraint(in token), 26 => LookupModuleReference(token), 38 => LookupFileReference(token), 40 => LookupManifestResource(token), 39 => LookupExportedType(token), 11 => LookupConstant(token), 15 => LookupClassLayout(token), 28 => LookupImplementationMap(token), 9 => LookupInterfaceImplementation(token), 14 => LookupSecurityDeclaration(token), _ => null, }; return member != null; } private ModuleDefinition? LookupModuleDefinition(in MetadataToken token) { if (((MetadataToken)(ref token)).Rid != 1) { return null; } return _context.ParentModule; } internal TypeReference? LookupTypeReference(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _typeReferences, token, (Func)((ModuleReaderContext c, MetadataToken t, TypeReferenceRow r) => new SerializedTypeReference(c, t, in r))); } internal TypeDefinition? LookupTypeDefinition(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _typeDefinitions, token, (Func)((ModuleReaderContext c, MetadataToken t, TypeDefinitionRow r) => new SerializedTypeDefinition(c, t, in r))); } internal TypeSpecification? LookupTypeSpecification(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _typeSpecifications, token, (Func)((ModuleReaderContext c, MetadataToken t, TypeSpecificationRow r) => new SerializedTypeSpecification(c, t, in r))); } private AssemblyDefinition? LookupAssemblyDefinition(MetadataToken token) { if (((MetadataToken)(ref token)).Rid != 1) { return null; } return _context.ParentModule.Assembly; } internal IMetadataMember? LookupAssemblyReference(MetadataToken token) { if (((MetadataToken)(ref token)).Rid == 0 || ((MetadataToken)(ref token)).Rid > _context.ParentModule.AssemblyReferences.Count) { return null; } return _context.ParentModule.AssemblyReferences[(int)(((MetadataToken)(ref token)).Rid - 1)]; } private FieldDefinition? LookupFieldDefinition(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _fieldDefinitions, token, (Func)((ModuleReaderContext c, MetadataToken t, FieldDefinitionRow r) => new SerializedFieldDefinition(c, t, in r))); } private MethodDefinition? LookupMethodDefinition(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _methodDefinitions, token, (Func)((ModuleReaderContext c, MetadataToken t, MethodDefinitionRow r) => new SerializedMethodDefinition(c, t, in r))); } private ParameterDefinition? LookupParameterDefinition(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _parameterDefinitions, token, (Func)((ModuleReaderContext c, MetadataToken t, ParameterDefinitionRow r) => new SerializedParameterDefinition(c, t, in r))); } private MemberReference? LookupMemberReference(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _memberReferences, token, (Func)((ModuleReaderContext c, MetadataToken t, MemberReferenceRow r) => new SerializedMemberReference(c, t, in r))); } private StandAloneSignature? LookupStandAloneSignature(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _standAloneSignatures, token, (Func)((ModuleReaderContext c, MetadataToken t, StandAloneSignatureRow r) => new SerializedStandAloneSignature(c, t, in r))); } private PropertyDefinition? LookupPropertyDefinition(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _propertyDefinitions, token, (Func)((ModuleReaderContext c, MetadataToken t, PropertyDefinitionRow r) => new SerializedPropertyDefinition(c, t, in r))); } private EventDefinition? LookupEventDefinition(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _eventDefinition, token, (Func)((ModuleReaderContext c, MetadataToken t, EventDefinitionRow r) => new SerializedEventDefinition(c, t, in r))); } private MethodSemantics? LookupMethodSemantics(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _methodSemantics, token, (Func)((ModuleReaderContext c, MetadataToken t, MethodSemanticsRow r) => new SerializedMethodSemantics(c, t, in r))); } private CustomAttribute? LookupCustomAttribute(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _customAttributes, token, (Func)((ModuleReaderContext c, MetadataToken t, CustomAttributeRow r) => new SerializedCustomAttribute(c, t, in r))); } private IMetadataMember? LookupMethodSpecification(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _methodSpecifications, token, (Func)((ModuleReaderContext c, MetadataToken t, MethodSpecificationRow r) => new SerializedMethodSpecification(c, t, in r))); } private GenericParameter? LookupGenericParameter(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _genericParameters, token, (Func)((ModuleReaderContext c, MetadataToken t, GenericParameterRow r) => new SerializedGenericParameter(c, t, in r))); } private GenericParameterConstraint? LookupGenericParameterConstraint(in MetadataToken token) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _genericParameterConstraints, token, (Func)((ModuleReaderContext c, MetadataToken t, GenericParameterConstraintRow r) => new SerializedGenericParameterConstraint(c, t, in r))); } private ModuleReference? LookupModuleReference(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _moduleReferences, token, (Func)((ModuleReaderContext c, MetadataToken t, ModuleReferenceRow r) => new SerializedModuleReference(c, t, in r))); } private FileReference? LookupFileReference(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _fileReferences, token, (Func)((ModuleReaderContext c, MetadataToken t, FileReferenceRow r) => new SerializedFileReference(c, t, in r))); } private ManifestResource? LookupManifestResource(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _resources, token, (Func)((ModuleReaderContext c, MetadataToken t, ManifestResourceRow r) => new SerializedManifestResource(c, t, in r))); } private ExportedType? LookupExportedType(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _exportedTypes, token, (Func)((ModuleReaderContext c, MetadataToken t, ExportedTypeRow r) => new SerializedExportedType(c, t, in r))); } private Constant? LookupConstant(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _constants, token, (Func)((ModuleReaderContext c, MetadataToken t, ConstantRow r) => new SerializedConstant(c, t, in r))); } private ClassLayout? LookupClassLayout(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _classLayouts, token, (Func)((ModuleReaderContext c, MetadataToken t, ClassLayoutRow r) => new SerializedClassLayout(c, t, in r))); } internal ImplementationMap? LookupImplementationMap(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _implementationMaps, token, (Func)((ModuleReaderContext c, MetadataToken t, ImplementationMapRow r) => new SerializedImplementationMap(c, t, in r))); } private InterfaceImplementation? LookupInterfaceImplementation(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _interfaceImplementations, token, (Func)((ModuleReaderContext c, MetadataToken t, InterfaceImplementationRow r) => new SerializedInterfaceImplementation(c, t, in r))); } private SecurityDeclaration? LookupSecurityDeclaration(MetadataToken token) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return this.LookupOrCreateMember(ref _securityDeclarations, token, (Func)((ModuleReaderContext c, MetadataToken t, SecurityDeclarationRow r) => new SerializedSecurityDeclaration(c, t, in r))); } internal TMember? LookupOrCreateMember(ref TMember?[]? cache, MetadataToken token, Func createMember) where TMember : class, IMetadataMember where TRow : struct, IMetadataRow { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) MetadataTable val = (MetadataTable)(object)_tablesStream.GetTable(((MetadataToken)(ref token)).Table); if (((MetadataToken)(ref token)).Rid == 0 || ((MetadataToken)(ref token)).Rid > val.Count) { return null; } if (cache == null) { Interlocked.CompareExchange(ref cache, new TMember[val.Count], null); } int num = (int)(((MetadataToken)(ref token)).Rid - 1); TMember val2 = cache[num]; if (val2 == null) { val2 = createMember(_context, token, val[num]); val2 = Interlocked.CompareExchange(ref cache[num], val2, null) ?? val2; } return val2; } } public class DefaultMethodBodyReader : IMethodBodyReader { public virtual AsmResolver.DotNet.Code.MethodBody? ReadMethodBody(ModuleReaderContext context, MethodDefinition owner, in MethodDefinitionRow row) { //IL_0085: 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_0029: Unknown result type (might be due to invalid IL or missing references) ISegmentReference body = ((MethodDefinitionRow)(ref row)).Body; if (body == SegmentReference.Null) { return null; } AsmResolver.DotNet.Code.MethodBody methodBody = null; try { if (body.CanRead && owner.IsIL) { BinaryStreamReader val = body.CreateReader(); CilRawMethodBody val2 = CilRawMethodBody.FromReader((IErrorListener)(object)context, ref val); if (val2 != null) { methodBody = CilMethodBody.FromRawMethodBody(context, owner, val2); } } if (methodBody == null && body.IsBounded) { ISegment segment = body.GetSegment(); CilRawMethodBody val3 = (CilRawMethodBody)(object)((segment is CilRawMethodBody) ? segment : null); if (val3 != null) { methodBody = CilMethodBody.FromRawMethodBody(context, owner, val3); } } } catch (Exception inner) { context.RegisterException(new BadImageFormatException($"Failed to parse the method body of {owner.MetadataToken}.", inner)); } if (methodBody != null) { methodBody.Address = body; return methodBody; } return new UnresolvedMethodBody(owner, body); } } public class DirectoryNetModuleResolver : INetModuleResolver { public string Directory { get; } public ModuleReaderParameters ReaderParameters { get; } public DirectoryNetModuleResolver(string directory, ModuleReaderParameters readerParameters) { Directory = directory ?? throw new ArgumentNullException("directory"); ReaderParameters = readerParameters ?? throw new ArgumentNullException("readerParameters"); } public ModuleDefinition? Resolve(string name) { string text = Path.Combine(Directory, name); if (!File.Exists(text)) { return null; } try { return ModuleDefinition.FromFile(text, ReaderParameters); } catch { return null; } } } public interface IMethodBodyReader { AsmResolver.DotNet.Code.MethodBody? ReadMethodBody(ModuleReaderContext context, MethodDefinition owner, in MethodDefinitionRow row); } public interface INetModuleResolver { ModuleDefinition? Resolve(string name); } public class ModuleReaderContext : IErrorListener { public IPEImage Image { get; } public SerializedModuleDefinition ParentModule { get; } public IMetadata Metadata => Image.DotNetDirectory.Metadata; public TablesStream TablesStream { get; } public int TablesStreamIndex { get; } = -1; public BlobStream? BlobStream { get; } public int BlobStreamIndex { get; } = -1; public GuidStream? GuidStream { get; } public int GuidStreamIndex { get; } = -1; public StringsStream? StringsStream { get; } public int StringsStreamIndex { get; } = -1; public UserStringsStream? UserStringsStream { get; } public int UserStringsStreamIndex { get; } = -1; public ModuleReaderParameters Parameters { get; } public ModuleReaderContext(IPEImage image, SerializedModuleDefinition parentModule, ModuleReaderParameters parameters) { Image = image ?? throw new ArgumentNullException("image"); ParentModule = parentModule ?? throw new ArgumentNullException("parentModule"); Parameters = parameters ?? throw new ArgumentNullException("parameters"); bool isEncMetadata = Metadata.IsEncMetadata; for (int i = 0; i < Metadata.Streams.Count; i++) { IMetadataStream val = Metadata.Streams[i]; TablesStream val2 = (TablesStream)(object)((val is TablesStream) ? val : null); if (val2 == null) { BlobStream val3 = (BlobStream)(object)((val is BlobStream) ? val : null); if (val3 == null) { GuidStream val4 = (GuidStream)(object)((val is GuidStream) ? val : null); if (val4 == null) { StringsStream val5 = (StringsStream)(object)((val is StringsStream) ? val : null); if (val5 == null) { UserStringsStream val6 = (UserStringsStream)(object)((val is UserStringsStream) ? val : null); if (val6 != null && (UserStringsStream == null || !isEncMetadata)) { UserStringsStream = val6; UserStringsStreamIndex = i; } } else if (StringsStream == null || !isEncMetadata) { StringsStream = val5; StringsStreamIndex = i; } } else if (GuidStream == null || !isEncMetadata) { GuidStream = val4; GuidStreamIndex = i; } } else if (BlobStream == null || !isEncMetadata) { BlobStream = val3; BlobStreamIndex = i; } } else if (TablesStream == null) { TablesStream = val2; TablesStreamIndex = i; } } if (TablesStream == null) { throw new ArgumentException("Metadata directory does not contain a tables stream."); } } public void MarkAsFatal() { Parameters.PEReaderParameters.ErrorListener.MarkAsFatal(); } public void RegisterException(Exception exception) { Parameters.PEReaderParameters.ErrorListener.RegisterException(exception); } } public class ModuleReaderParameters { public string? WorkingDirectory { get; } public INetModuleResolver? ModuleResolver { get; set; } public IMethodBodyReader MethodBodyReader { get; set; } = new DefaultMethodBodyReader(); public IFieldRvaDataReader FieldRvaDataReader { get; set; } = (IFieldRvaDataReader)new FieldRvaDataReader(); public PEReaderParameters PEReaderParameters { get; set; } = new PEReaderParameters(); public ModuleReaderParameters() { }//IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown public ModuleReaderParameters(IErrorListener errorListener) : this(null, errorListener) { } public ModuleReaderParameters(string? workingDirectory) : this(workingDirectory, (IErrorListener)(object)ThrowErrorListener.Instance) { } public ModuleReaderParameters(string? workingDirectory, IErrorListener errorListener) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown if (workingDirectory != null) { WorkingDirectory = workingDirectory; ModuleResolver = new DirectoryNetModuleResolver(workingDirectory, this); } PEReaderParameters.ErrorListener = errorListener; } } public class SerializedAssemblyDefinition : AssemblyDefinition { private static readonly Utf8String SystemRuntimeVersioningNamespace = Utf8String.op_Implicit("System.Runtime.Versioning"); private static readonly Utf8String TargetFrameworkAttributeName = Utf8String.op_Implicit("TargetFrameworkAttribute"); private readonly ModuleReaderContext _context; private readonly AssemblyDefinitionRow _row; private readonly SerializedModuleDefinition _manifestModule; public SerializedAssemblyDefinition(ModuleReaderContext context, MetadataToken token, in AssemblyDefinitionRow row, SerializedModuleDefinition manifestModule) : base(token) { //IL_0001: 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_0042: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; _manifestModule = manifestModule ?? throw new ArgumentNullException("manifestModule"); base.Attributes = ((AssemblyDefinitionRow)(ref row)).Attributes; base.Version = new Version(((AssemblyDefinitionRow)(ref row)).MajorVersion, ((AssemblyDefinitionRow)(ref row)).MinorVersion, ((AssemblyDefinitionRow)(ref row)).BuildNumber, ((AssemblyDefinitionRow)(ref row)).RevisionNumber); base.HashAlgorithm = ((AssemblyDefinitionRow)(ref row)).HashAlgorithm; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((AssemblyDefinitionRow)(ref _row)).Name); } protected override Utf8String? GetCulture() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((AssemblyDefinitionRow)(ref _row)).Culture); } protected override byte[]? GetPublicKey() { BlobStream? blobStream = _context.BlobStream; if (blobStream == null) { return null; } return blobStream.GetBlobByIndex(((AssemblyDefinitionRow)(ref _row)).PublicKey); } protected override IList GetModules() { //IL_0066: 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_006f: Unknown result type (might be due to invalid IL or missing references) _manifestModule.Assembly = null; OwnedCollection obj = new OwnedCollection((AssemblyDefinition)this); ((LazyList)(object)obj).Add((ModuleDefinition)_manifestModule); OwnedCollection val = obj; INetModuleResolver moduleResolver = _context.Parameters.ModuleResolver; if (moduleResolver != null) { TablesStream tablesStream = _context.TablesStream; StringsStream stringsStream = _context.StringsStream; if (stringsStream == null) { return (IList)val; } MetadataTable table = tablesStream.GetTable((TableIndex)38); for (int i = 0; i < table.Count; i++) { FileReferenceRow val2 = table[i]; if ((int)((FileReferenceRow)(ref val2)).Attributes != 0) { continue; } string text = Utf8String.op_Implicit(stringsStream.GetStringByIndex(((FileReferenceRow)(ref val2)).Name)); if (!string.IsNullOrEmpty(text)) { ModuleDefinition moduleDefinition = moduleResolver.Resolve(text); if (moduleDefinition != null) { ((LazyList)(object)val).Add(moduleDefinition); } } } } return (IList)val; } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } protected override IList GetSecurityDeclarations() { return _context.ParentModule.GetSecurityDeclarationCollection(this); } public override bool TryGetTargetFramework(out DotNetRuntimeInfo info) { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: 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_00a1: Invalid comparison between Unknown and I4 //IL_00c3: 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: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Invalid comparison between Unknown and I4 //IL_0133: Unknown result type (might be due to invalid IL or missing references) TablesStream tablesStream = _context.TablesStream; StringsStream stringsStream = _context.StringsStream; if (stringsStream == null) { info = default(DotNetRuntimeInfo); return false; } MetadataTable table = tablesStream.GetTable((TableIndex)12); MetadataTable table2 = tablesStream.GetTable((TableIndex)10); MetadataTable table3 = tablesStream.GetTable((TableIndex)1); IndexEncoder indexEncoder = tablesStream.GetIndexEncoder((CodedIndex)66); IndexEncoder indexEncoder2 = tablesStream.GetIndexEncoder((CodedIndex)61); Enumerator enumerator = _manifestModule.GetCustomAttributes(base.MetadataToken).GetEnumerator(); try { CustomAttributeRow val = default(CustomAttributeRow); MemberReferenceRow val3 = default(MemberReferenceRow); TypeReferenceRow val5 = default(TypeReferenceRow); while (enumerator.MoveNext()) { uint current = enumerator.Current; if (!table.TryGetByRid(current, ref val)) { continue; } MetadataToken val2 = indexEncoder.DecodeIndex(((CustomAttributeRow)(ref val)).Type); if ((int)((MetadataToken)(ref val2)).Table != 10 || !table2.TryGetByRid(((MetadataToken)(ref val2)).Rid, ref val3)) { continue; } MetadataToken val4 = indexEncoder2.DecodeIndex(((MemberReferenceRow)(ref val3)).Parent); if ((int)((MetadataToken)(ref val4)).Table != 1 || !table3.TryGetByRid(((MetadataToken)(ref val4)).Rid, ref val5)) { continue; } Utf8String stringByIndex = stringsStream.GetStringByIndex(((TypeReferenceRow)(ref val5)).Namespace); Utf8String stringByIndex2 = stringsStream.GetStringByIndex(((TypeReferenceRow)(ref val5)).Name); if (stringByIndex != SystemRuntimeVersioningNamespace || stringByIndex2 != TargetFrameworkAttributeName) { continue; } CustomAttribute customAttribute = (CustomAttribute)_manifestModule.LookupMember(new MetadataToken((TableIndex)12, current)); if (customAttribute.Signature != null && customAttribute.Signature.FixedArguments.Count != 0) { object element = customAttribute.Signature.FixedArguments[0].Element; if ((element is string || element is Utf8String) && DotNetRuntimeInfo.TryParse(element.ToString(), out info)) { return true; } } } } finally { ((IDisposable)enumerator).Dispose(); } info = default(DotNetRuntimeInfo); return false; } } public class SerializedAssemblyReference : AssemblyReference { private readonly ModuleReaderContext _context; private readonly AssemblyReferenceRow _row; public SerializedAssemblyReference(ModuleReaderContext context, MetadataToken token, in AssemblyReferenceRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((AssemblyReferenceRow)(ref row)).Attributes; base.Version = new Version(((AssemblyReferenceRow)(ref row)).MajorVersion, ((AssemblyReferenceRow)(ref row)).MinorVersion, ((AssemblyReferenceRow)(ref row)).BuildNumber, ((AssemblyReferenceRow)(ref row)).RevisionNumber); } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((AssemblyReferenceRow)(ref _row)).Name); } protected override Utf8String? GetCulture() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((AssemblyReferenceRow)(ref _row)).Culture); } protected override byte[]? GetPublicKeyOrToken() { BlobStream? blobStream = _context.BlobStream; if (blobStream == null) { return null; } return blobStream.GetBlobByIndex(((AssemblyReferenceRow)(ref _row)).PublicKeyOrToken); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedClassLayout : ClassLayout { private readonly ModuleReaderContext _context; private readonly ClassLayoutRow _row; public SerializedClassLayout(ModuleReaderContext context, MetadataToken token, in ClassLayoutRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.PackingSize = ((ClassLayoutRow)(ref row)).PackingSize; base.ClassSize = ((ClassLayoutRow)(ref row)).ClassSize; } protected override TypeDefinition? GetParent() { //IL_0017: 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_0036: Unknown result type (might be due to invalid IL or missing references) if (!_context.ParentModule.TryLookupMember(new MetadataToken((TableIndex)2, ((ClassLayoutRow)(ref _row)).Parent), out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid parent type in class layout " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as TypeDefinition; } } public class SerializedConstant : Constant { private readonly ModuleReaderContext _context; private readonly ConstantRow _row; public SerializedConstant(ModuleReaderContext context, MetadataToken token, in ConstantRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Type = ((ConstantRow)(ref row)).Type; } protected override IHasConstant? GetParent() { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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_0045: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken constantOwner = parentModule.GetConstantOwner(((MetadataToken)(ref metadataToken)).Rid); if (!_context.ParentModule.TryLookupMember(constantOwner, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid parent member in constant " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as IHasConstant; } protected override DataBlobSignature? GetValue() { BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((ConstantRow)(ref _row)).Value, ref reader)) { return null; } return DataBlobSignature.FromReader(ref reader); } } public class SerializedCustomAttribute : CustomAttribute { private readonly ModuleReaderContext _context; private readonly CustomAttributeRow _row; public SerializedCustomAttribute(ModuleReaderContext context, MetadataToken token, in CustomAttributeRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; } protected override IHasCustomAttribute? GetParent() { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken customAttributeOwner = parentModule.GetCustomAttributeOwner(((MetadataToken)(ref metadataToken)).Rid); if (!_context.ParentModule.TryLookupMember(customAttributeOwner, out IMetadataMember member)) { return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)_context, $"Invalid parent in custom attribute {base.MetadataToken}."); } return member as IHasCustomAttribute; } protected override ICustomAttributeType? GetConstructor() { //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_002e: 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) MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)66).DecodeIndex(((CustomAttributeRow)(ref _row)).Type); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)_context, $"Invalid constructor in custom attribute {base.MetadataToken}."); } return member as ICustomAttributeType; } protected override CustomAttributeSignature? GetSignature() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (base.Constructor == null) { return null; } BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((CustomAttributeRow)(ref _row)).Value, ref reader)) { return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)_context, $"Invalid signature blob index in custom attribute {base.MetadataToken}."); } BlobReaderContext context = new BlobReaderContext(_context); return CustomAttributeSignature.FromReader(in context, base.Constructor, in reader); } } public class SerializedEventDefinition : EventDefinition { private readonly ModuleReaderContext _context; private readonly EventDefinitionRow _row; public SerializedEventDefinition(ModuleReaderContext context, MetadataToken token, in EventDefinitionRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((EventDefinitionRow)(ref row)).Attributes; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((EventDefinitionRow)(ref _row)).Name); } protected override ITypeDefOrRef? GetEventType() { //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_002e: 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) MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)56).DecodeIndex(((EventDefinitionRow)(ref _row)).EventType); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid event type referenced by event " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as ITypeDefOrRef; } protected override TypeDefinition? GetDeclaringType() { //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_0029: 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_0044: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken token = default(MetadataToken); ((MetadataToken)(ref token))..ctor((TableIndex)2, parentModule.GetEventDeclaringType(((MetadataToken)(ref metadataToken)).Rid)); if (!parentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Event " + ((object)(MetadataToken)(ref metadataToken)).ToString() + " is not added to an event map of a declaring type."); } return member as TypeDefinition; } protected override IList GetSemantics() { //IL_001c: 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_002b: 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) MethodSemanticsCollection methodSemanticsCollection = new MethodSemanticsCollection(this); methodSemanticsCollection.ValidateMembership = false; SerializedModuleDefinition parentModule = _context.ParentModule; Enumerator enumerator = parentModule.GetMethodSemantics(base.MetadataToken).GetEnumerator(); try { MetadataToken token = default(MetadataToken); while (enumerator.MoveNext()) { uint current = enumerator.Current; ((MetadataToken)(ref token))..ctor((TableIndex)24, current); ((LazyList)(object)methodSemanticsCollection).Add((MethodSemantics)parentModule.LookupMember(token)); } } finally { ((IDisposable)enumerator).Dispose(); } methodSemanticsCollection.ValidateMembership = true; return (IList)methodSemanticsCollection; } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedExportedType : ExportedType { private readonly ModuleReaderContext _context; private readonly ExportedTypeRow _row; public SerializedExportedType(ModuleReaderContext context, MetadataToken token, in ExportedTypeRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((ExportedTypeRow)(ref row)).Attributes; ((IOwnedCollectionElement)(object)this).Owner = context.ParentModule; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((ExportedTypeRow)(ref _row)).Name); } protected override Utf8String? GetNamespace() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((ExportedTypeRow)(ref _row)).Namespace); } protected override IImplementation? GetImplementation() { //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_002e: 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) MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)65).DecodeIndex(((ExportedTypeRow)(ref _row)).Implementation); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid implementation reference in exported type " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as IImplementation; } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedFieldDefinition : FieldDefinition { private readonly ModuleReaderContext _context; private readonly FieldDefinitionRow _row; public SerializedFieldDefinition(ModuleReaderContext context, MetadataToken token, in FieldDefinitionRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((FieldDefinitionRow)(ref row)).Attributes; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((FieldDefinitionRow)(ref _row)).Name); } protected override FieldSignature? GetSignature() { //IL_0030: 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) BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((FieldDefinitionRow)(ref _row)).Signature, ref reader)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid signature blob index in field " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } BlobReaderContext context2 = new BlobReaderContext(_context); return FieldSignature.FromReader(ref context2, ref reader); } protected override TypeDefinition? GetDeclaringType() { //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_0029: 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_0044: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken token = default(MetadataToken); ((MetadataToken)(ref token))..ctor((TableIndex)2, parentModule.GetFieldDeclaringType(((MetadataToken)(ref metadataToken)).Rid)); if (!parentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Field " + ((object)(MetadataToken)(ref metadataToken)).ToString() + " is not in the range of a declaring type."); } return member as TypeDefinition; } protected override Constant? GetConstant() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return _context.ParentModule.GetConstant(base.MetadataToken); } protected override MarshalDescriptor? GetMarshalDescriptor() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return _context.ParentModule.GetFieldMarshal(base.MetadataToken); } protected override ImplementationMap? GetImplementationMap() { //IL_000d: 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) SerializedModuleDefinition parentModule = _context.ParentModule; uint implementationMapRid = parentModule.GetImplementationMapRid(base.MetadataToken); if (!parentModule.TryLookupMember(new MetadataToken((TableIndex)28, implementationMapRid), out IMetadataMember member)) { return null; } return member as ImplementationMap; } protected override ISegment? GetFieldRva() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) uint fieldRvaRid = _context.ParentModule.GetFieldRvaRid(base.MetadataToken); FieldRvaRow val = default(FieldRvaRow); if (!_context.TablesStream.GetTable((TableIndex)29).TryGetByRid(fieldRvaRid, ref val)) { return null; } return _context.Parameters.FieldRvaDataReader.ResolveFieldData((IErrorListener)(object)_context, _context.Metadata, ref val); } protected override int? GetFieldOffset() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) uint fieldLayoutRid = _context.ParentModule.GetFieldLayoutRid(base.MetadataToken); FieldLayoutRow val = default(FieldLayoutRow); if (!_context.TablesStream.GetTable().TryGetByRid(fieldLayoutRid, ref val)) { return null; } return (int)((FieldLayoutRow)(ref val)).Offset; } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedFileReference : FileReference { private readonly ModuleReaderContext _context; private readonly FileReferenceRow _row; public SerializedFileReference(ModuleReaderContext context, MetadataToken token, in FileReferenceRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((FileReferenceRow)(ref row)).Attributes; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((FileReferenceRow)(ref _row)).Name); } protected override byte[]? GetHashValue() { BlobStream? blobStream = _context.BlobStream; if (blobStream == null) { return null; } return blobStream.GetBlobByIndex(((FileReferenceRow)(ref _row)).HashValue); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedGenericParameter : GenericParameter { private readonly ModuleReaderContext _context; private readonly GenericParameterRow _row; public SerializedGenericParameter(ModuleReaderContext context, MetadataToken token, in GenericParameterRow row) : base(token) { //IL_0001: 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_0030: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((GenericParameterRow)(ref _row)).Attributes; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((GenericParameterRow)(ref _row)).Name); } protected override IHasGenericParameters? GetOwner() { //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_002e: 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) MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)68).DecodeIndex(((GenericParameterRow)(ref _row)).Owner); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid owner in generic parameter " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as IHasGenericParameters; } protected override IList GetConstraints() { //IL_000e: 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_002c: 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) SerializedModuleDefinition parentModule = _context.ParentModule; ValueSet genericParameterConstraints = parentModule.GetGenericParameterConstraints(base.MetadataToken); OwnedCollection val = new OwnedCollection((GenericParameter)this, genericParameterConstraints.Count); Enumerator enumerator = genericParameterConstraints.GetEnumerator(); try { MetadataToken token = default(MetadataToken); while (enumerator.MoveNext()) { uint current = enumerator.Current; ((MetadataToken)(ref token))..ctor((TableIndex)44, current); ((LazyList)(object)val).Add((GenericParameterConstraint)parentModule.LookupMember(token)); } return (IList)val; } finally { ((IDisposable)enumerator).Dispose(); } } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedGenericParameterConstraint : GenericParameterConstraint { private readonly ModuleReaderContext _context; private readonly GenericParameterConstraintRow _row; public SerializedGenericParameterConstraint(ModuleReaderContext context, MetadataToken token, in GenericParameterConstraintRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; } protected override GenericParameter? GetOwner() { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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_0045: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken genericParameterConstraintOwner = parentModule.GetGenericParameterConstraintOwner(((MetadataToken)(ref metadataToken)).Rid); if (!_context.ParentModule.TryLookupMember(genericParameterConstraintOwner, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid owner in generic parameter constraint " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as GenericParameter; } protected override ITypeDefOrRef? GetConstraint() { //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_002e: 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) MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)56).DecodeIndex(((GenericParameterConstraintRow)(ref _row)).Constraint); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid constraint type in generic parameter constraint " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as ITypeDefOrRef; } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedImplementationMap : ImplementationMap { private readonly ModuleReaderContext _context; private readonly ImplementationMapRow _row; public SerializedImplementationMap(ModuleReaderContext context, MetadataToken token, in ImplementationMapRow row) : base(token) { //IL_0001: 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_0030: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((ImplementationMapRow)(ref _row)).Attributes; } protected override IMemberForwarded? GetMemberForwarded() { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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_0045: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken implementationMapOwner = parentModule.GetImplementationMapOwner(((MetadataToken)(ref metadataToken)).Rid); if (!_context.ParentModule.TryLookupMember(implementationMapOwner, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid forwarded member in implementation map " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as IMemberForwarded; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((ImplementationMapRow)(ref _row)).ImportName); } protected override ModuleReference? GetScope() { //IL_0018: 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_0037: Unknown result type (might be due to invalid IL or missing references) if (!_context.ParentModule.TryLookupMember(new MetadataToken((TableIndex)26, ((ImplementationMapRow)(ref _row)).ImportScope), out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid import scope in implementation map " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as ModuleReference; } } public class SerializedInterfaceImplementation : InterfaceImplementation { private readonly ModuleReaderContext _context; private readonly InterfaceImplementationRow _row; public SerializedInterfaceImplementation(ModuleReaderContext context, MetadataToken token, in InterfaceImplementationRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; } protected override TypeDefinition? GetClass() { //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_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_0020: 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) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken interfaceImplementationOwner = parentModule.GetInterfaceImplementationOwner(((MetadataToken)(ref metadataToken)).Rid); if (!parentModule.TryLookupMember(interfaceImplementationOwner, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid parent class in interface implementation " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as TypeDefinition; } protected override ITypeDefOrRef? GetInterface() { //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_002e: 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) MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)56).DecodeIndex(((InterfaceImplementationRow)(ref _row)).Interface); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid interface in interface implementation " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as ITypeDefOrRef; } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedManifestResource : ManifestResource { private readonly ModuleReaderContext _context; private readonly ManifestResourceRow _row; public SerializedManifestResource(ModuleReaderContext context, MetadataToken token, in ManifestResourceRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((ManifestResourceRow)(ref row)).Attributes; ((IOwnedCollectionElement)(object)this).Owner = context.ParentModule; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((ManifestResourceRow)(ref _row)).Name); } protected override IImplementation? GetImplementation() { //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_003d: 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_0058: Unknown result type (might be due to invalid IL or missing references) if (((ManifestResourceRow)(ref _row)).Implementation == 0) { return null; } MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)65).DecodeIndex(((ManifestResourceRow)(ref _row)).Implementation); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid implementation in manifest resource " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as IImplementation; } protected override ISegment? GetEmbeddedDataSegment() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) if (((ManifestResourceRow)(ref _row)).Implementation != 0) { return null; } DotNetResourcesDirectory dotNetResources = _context.Image.DotNetDirectory.DotNetResources; BinaryStreamReader val = default(BinaryStreamReader); if (dotNetResources == null || !dotNetResources.TryCreateManifestResourceReader(((ManifestResourceRow)(ref _row)).Offset, ref val)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid data offset in manifest resource " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return (ISegment?)(object)DataSegment.FromReader(ref val); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedMemberReference : MemberReference { private readonly ModuleReaderContext _context; private readonly MemberReferenceRow _row; public SerializedMemberReference(ModuleReaderContext context, MetadataToken token, in MemberReferenceRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; } protected override IMemberRefParent? GetParent() { //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_002e: 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) MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)61).DecodeIndex(((MemberReferenceRow)(ref _row)).Parent); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid parent in member reference " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as IMemberRefParent; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((MemberReferenceRow)(ref _row)).Name); } protected override CallingConventionSignature? GetSignature() { //IL_0030: 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) BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((MemberReferenceRow)(ref _row)).Signature, ref reader)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid signature blob index in member reference " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } BlobReaderContext context2 = new BlobReaderContext(_context); return CallingConventionSignature.FromReader(ref context2, ref reader); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedMethodDefinition : MethodDefinition { private readonly ModuleReaderContext _context; private readonly MethodDefinitionRow _row; public SerializedMethodDefinition(ModuleReaderContext context, MetadataToken token, in MethodDefinitionRow row) : base(token) { //IL_0001: 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_002b: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((MethodDefinitionRow)(ref row)).Attributes; base.ImplAttributes = ((MethodDefinitionRow)(ref row)).ImplAttributes; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((MethodDefinitionRow)(ref _row)).Name); } protected override MethodSignature? GetSignature() { //IL_0030: 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) BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((MethodDefinitionRow)(ref _row)).Signature, ref reader)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid signature blob index in method " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } BlobReaderContext context2 = new BlobReaderContext(_context); return MethodSignature.FromReader(ref context2, ref reader); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } protected override IList GetSecurityDeclarations() { return _context.ParentModule.GetSecurityDeclarationCollection(this); } protected override TypeDefinition? GetDeclaringType() { //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_0031: 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_004c: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken token = default(MetadataToken); ((MetadataToken)(ref token))..ctor((TableIndex)2, parentModule.GetMethodDeclaringType(((MetadataToken)(ref metadataToken)).Rid)); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Method " + ((object)(MetadataToken)(ref metadataToken)).ToString() + " is not in the range of a declaring type."); } return member as TypeDefinition; } protected override IList GetParameterDefinitions() { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_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_0039: 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_004b: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataRange parameterRange = parentModule.GetParameterRange(((MetadataToken)(ref metadataToken)).Rid); OwnedCollection val = new OwnedCollection((MethodDefinition)this, ((MetadataRange)(ref parameterRange)).Count); Enumerator enumerator = ((MetadataRange)(ref parameterRange)).GetEnumerator(); try { while (((Enumerator)(ref enumerator)).MoveNext()) { MetadataToken current = ((Enumerator)(ref enumerator)).Current; if (_context.ParentModule.TryLookupMember(current, out IMetadataMember member) && member is ParameterDefinition parameterDefinition) { ((LazyList)(object)val).Add(parameterDefinition); } } return (IList)val; } finally { ((IDisposable)(Enumerator)(ref enumerator)).Dispose(); } } protected override AsmResolver.DotNet.Code.MethodBody? GetBody() { return _context.Parameters.MethodBodyReader.ReadMethodBody(_context, this, in _row); } protected override ImplementationMap? GetImplementationMap() { //IL_000c: 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) uint implementationMapRid = _context.ParentModule.GetImplementationMapRid(base.MetadataToken); if (!_context.ParentModule.TryLookupMember(new MetadataToken((TableIndex)28, implementationMapRid), out IMetadataMember member)) { return null; } return member as ImplementationMap; } protected override IList GetGenericParameters() { //IL_000c: 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_002a: 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) ValueSet genericParameters = _context.ParentModule.GetGenericParameters(base.MetadataToken); OwnedCollection val = new OwnedCollection((IHasGenericParameters)this, genericParameters.Count); Enumerator enumerator = genericParameters.GetEnumerator(); try { while (enumerator.MoveNext()) { uint current = enumerator.Current; if (_context.ParentModule.TryLookupMember(new MetadataToken((TableIndex)42, current), out IMetadataMember member) && member is GenericParameter genericParameter) { ((LazyList)(object)val).Add(genericParameter); } } return (IList)val; } finally { ((IDisposable)enumerator).Dispose(); } } protected override MethodSemantics? GetSemantics() { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken methodParentSemantics = parentModule.GetMethodParentSemantics(((MetadataToken)(ref metadataToken)).Rid); if (!_context.ParentModule.TryLookupMember(methodParentSemantics, out IMetadataMember member)) { return null; } return member as MethodSemantics; } protected override UnmanagedExportInfo? GetExportInfo() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return _context.ParentModule.GetExportInfo(base.MetadataToken); } } public class SerializedMethodSemantics : MethodSemantics { private readonly ModuleReaderContext _context; private readonly MethodSemanticsRow _row; public SerializedMethodSemantics(ModuleReaderContext context, MetadataToken token, in MethodSemanticsRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((MethodSemanticsRow)(ref row)).Attributes; } protected override MethodDefinition? GetMethod() { //IL_001e: 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) MetadataToken token = default(MetadataToken); ((MetadataToken)(ref token))..ctor((TableIndex)6, ((MethodSemanticsRow)(ref _row)).Method); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid method in method semantics " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as MethodDefinition; } protected override IHasSemantics? GetAssociation() { //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_002e: 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) MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)62).DecodeIndex(((MethodSemanticsRow)(ref _row)).Association); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid association in method semantics " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as IHasSemantics; } } public class SerializedMethodSpecification : MethodSpecification { private readonly ModuleReaderContext _context; private readonly MethodSpecificationRow _row; public SerializedMethodSpecification(ModuleReaderContext context, MetadataToken token, in MethodSpecificationRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; } protected override IMethodDefOrRef? GetMethod() { //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_002e: 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) MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)63).DecodeIndex(((MethodSpecificationRow)(ref _row)).Method); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid method in method specification " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as IMethodDefOrRef; } protected override GenericInstanceMethodSignature? GetSignature() { //IL_0030: 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) BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((MethodSpecificationRow)(ref _row)).Instantiation, ref reader)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid instantiation blob index in method specification " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } BlobReaderContext context2 = new BlobReaderContext(_context); return GenericInstanceMethodSignature.FromReader(ref context2, ref reader); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedModuleDefinition : ModuleDefinition { private readonly ModuleDefinitionRow _row; private readonly CachedSerializedMemberFactory _memberFactory; private readonly LazyRidListRelation _fieldLists; private readonly LazyRidListRelation _methodLists; private readonly LazyRidListRelation _paramLists; private readonly LazyRidListRelation _propertyLists; private readonly LazyRidListRelation _eventLists; private OneToManyRelation? _typeDefTree; private OneToManyRelation? _semantics; private Dictionary? _semanticMethods; private OneToOneRelation? _constants; private OneToManyRelation? _customAttributes; private OneToManyRelation? _securityDeclarations; private OneToManyRelation? _genericParameters; private OneToManyRelation? _genericParameterConstraints; private OneToManyRelation? _interfaces; private OneToManyRelation? _methodImplementations; private OneToOneRelation? _classLayouts; private OneToOneRelation? _implementationMaps; private OneToOneRelation? _fieldRvas; private OneToOneRelation? _fieldMarshals; private OneToOneRelation? _fieldLayouts; private Dictionary? _exportInfos; public override IDotNetDirectory DotNetDirectory => ReaderContext.Image.DotNetDirectory; public ModuleReaderContext ReaderContext { get; } public SerializedModuleDefinition(IPEImage peImage, ModuleReaderParameters readerParameters) : base(new MetadataToken((TableIndex)0, 1u)) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_009b: 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_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: 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) if (peImage == null) { throw new ArgumentNullException("peImage"); } if (readerParameters == null) { throw new ArgumentNullException("readerParameters"); } IDotNetDirectory dotNetDirectory = peImage.DotNetDirectory; IMetadata val = ((dotNetDirectory != null) ? dotNetDirectory.Metadata : null); if (val == null) { throw new BadImageFormatException("Input PE image does not contain a .NET metadata directory."); } TablesStream stream = val.GetStream(); if (stream == null) { throw new BadImageFormatException(".NET metadata directory does not define a tables stream."); } if (!stream.GetTable((TableIndex)0).TryGetByRid(1u, ref _row)) { throw new BadImageFormatException("Module definition table does not contain any rows."); } ReaderContext = new ModuleReaderContext(peImage, this, readerParameters); base.FilePath = peImage.FilePath; base.MachineType = peImage.MachineType; base.FileCharacteristics = peImage.Characteristics; base.PEKind = peImage.PEKind; base.SubSystem = peImage.SubSystem; base.DllCharacteristics = peImage.DllCharacteristics; base.TimeDateStamp = peImage.TimeDateStamp; base.Generation = ((ModuleDefinitionRow)(ref _row)).Generation; base.Attributes = peImage.DotNetDirectory.Flags; _memberFactory = new CachedSerializedMemberFactory(ReaderContext); base.Assembly = FindParentAssembly(); base.CorLibTypeFactory = CreateCorLibTypeFactory(); base.OriginalTargetRuntime = DetectTargetRuntime(); base.MetadataResolver = new DefaultMetadataResolver(CreateAssemblyResolver(readerParameters.PEReaderParameters.FileService)); _fieldLists = new LazyRidListRelation(val, (TableIndex)4, (TableIndex)2, (LazyRidListRelation.GetOwnerRidDelegate)((uint rid, TypeDefinitionRow _) => rid), (LazyRidListRelation.GetMemberListDelegate)stream.GetFieldRange); _methodLists = new LazyRidListRelation(val, (TableIndex)6, (TableIndex)2, (LazyRidListRelation.GetOwnerRidDelegate)((uint rid, TypeDefinitionRow _) => rid), (LazyRidListRelation.GetMemberListDelegate)stream.GetMethodRange); _paramLists = new LazyRidListRelation(val, (TableIndex)8, (TableIndex)6, (LazyRidListRelation.GetOwnerRidDelegate)((uint rid, MethodDefinitionRow _) => rid), (LazyRidListRelation.GetMemberListDelegate)stream.GetParameterRange); _propertyLists = new LazyRidListRelation(val, (TableIndex)23, (TableIndex)21, (LazyRidListRelation.GetOwnerRidDelegate)((uint _, PropertyMapRow map) => ((PropertyMapRow)(ref map)).Parent), (LazyRidListRelation.GetMemberListDelegate)stream.GetPropertyRange); _eventLists = new LazyRidListRelation(val, (TableIndex)20, (TableIndex)18, (LazyRidListRelation.GetOwnerRidDelegate)((uint _, EventMapRow map) => ((EventMapRow)(ref map)).Parent), (LazyRidListRelation.GetMemberListDelegate)stream.GetEventRange); } public override IMetadataMember LookupMember(MetadataToken token) { //IL_0001: 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) if (TryLookupMember(token, out IMetadataMember member)) { return member; } throw new ArgumentException($"Cannot resolve metadata token {token}."); } public override bool TryLookupMember(MetadataToken token, [NotNullWhen(true)] out IMetadataMember? member) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _memberFactory.TryLookupMember(token, out member); } public override string LookupString(MetadataToken token) { //IL_0001: 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) if (TryLookupString(token, out string value)) { return value; } throw new ArgumentException($"Cannot resolve string token {token}."); } public override bool TryLookupString(MetadataToken token, [NotNullWhen(true)] out string? value) { UserStringsStream userStringsStream = ReaderContext.UserStringsStream; if (userStringsStream == null) { value = null; return false; } value = userStringsStream.GetStringByIndex(((MetadataToken)(ref token)).Rid); return value != null; } public override IndexEncoder GetIndexEncoder(CodedIndex codedIndex) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return ReaderContext.TablesStream.GetIndexEncoder(codedIndex); } public override IEnumerable GetImportedTypeReferences() { IMetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)1); for (uint rid = 1u; rid <= ((ICollection)table).Count; rid++) { if (TryLookupMember(new MetadataToken((TableIndex)1, rid), out IMetadataMember member) && member is TypeReference typeReference) { yield return typeReference; } } } public override IEnumerable GetImportedMemberReferences() { IMetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)10); for (uint rid = 1u; rid <= ((ICollection)table).Count; rid++) { if (TryLookupMember(new MetadataToken((TableIndex)10, rid), out IMetadataMember member) && member is MemberReference memberReference) { yield return memberReference; } } } protected override Utf8String? GetName() { StringsStream? stringsStream = ReaderContext.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((ModuleDefinitionRow)(ref _row)).Name); } protected override Guid GetMvid() { GuidStream? guidStream = ReaderContext.GuidStream; if (guidStream == null) { return Guid.Empty; } return guidStream.GetGuidByIndex(((ModuleDefinitionRow)(ref _row)).Mvid); } protected override Guid GetEncId() { GuidStream? guidStream = ReaderContext.GuidStream; if (guidStream == null) { return Guid.Empty; } return guidStream.GetGuidByIndex(((ModuleDefinitionRow)(ref _row)).EncId); } protected override Guid GetEncBaseId() { GuidStream? guidStream = ReaderContext.GuidStream; if (guidStream == null) { return Guid.Empty; } return guidStream.GetGuidByIndex(((ModuleDefinitionRow)(ref _row)).EncBaseId); } protected override IList GetTopLevelTypes() { //IL_0068: Unknown result type (might be due to invalid IL or missing references) EnsureTypeDefinitionTreeInitialized(); MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)2); int count = ((ICollection)ReaderContext.TablesStream.GetTable((TableIndex)41)).Count; OwnedCollection val = new OwnedCollection((ModuleDefinition)this, table.Count - count); MetadataToken token = default(MetadataToken); for (int i = 0; i < table.Count; i++) { uint num = (uint)(i + 1); if (_typeDefTree.GetKey(num) == 0) { ((MetadataToken)(ref token))..ctor((TableIndex)2, num); ((LazyList)(object)val).Add(_memberFactory.LookupTypeDefinition(token)); } } return (IList)val; } protected override IList GetAssemblyReferences() { //IL_0037: 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) MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)35); OwnedCollection val = new OwnedCollection((ModuleDefinition)this, table.Count); MetadataToken val2 = default(MetadataToken); for (int i = 0; i < table.Count; i++) { ((MetadataToken)(ref val2))..ctor((TableIndex)35, (uint)(i + 1)); ModuleReaderContext readerContext = ReaderContext; MetadataToken token = val2; AssemblyReferenceRow row = table[i]; ((LazyList)(object)val).Add((AssemblyReference)new SerializedAssemblyReference(readerContext, token, in row)); } return (IList)val; } protected override IList GetModuleReferences() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) IMetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)26); OwnedCollection val = new OwnedCollection((ModuleDefinition)this, ((ICollection)table).Count); MetadataToken token = default(MetadataToken); for (int i = 0; i < ((ICollection)table).Count; i++) { ((MetadataToken)(ref token))..ctor((TableIndex)26, (uint)(i + 1)); if (_memberFactory.TryLookupMember(token, out IMetadataMember member) && member is ModuleReference moduleReference) { ((LazyList)(object)val).Add(moduleReference); } } return (IList)val; } protected override IList GetFileReferences() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) IMetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)38); OwnedCollection val = new OwnedCollection((ModuleDefinition)this, ((ICollection)table).Count); MetadataToken token = default(MetadataToken); for (int i = 0; i < ((ICollection)table).Count; i++) { ((MetadataToken)(ref token))..ctor((TableIndex)38, (uint)(i + 1)); if (_memberFactory.TryLookupMember(token, out IMetadataMember member) && member is FileReference fileReference) { ((LazyList)(object)val).Add(fileReference); } } return (IList)val; } protected override IList GetResources() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) IMetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)40); OwnedCollection val = new OwnedCollection((ModuleDefinition)this, ((ICollection)table).Count); MetadataToken token = default(MetadataToken); for (int i = 0; i < ((ICollection)table).Count; i++) { ((MetadataToken)(ref token))..ctor((TableIndex)40, (uint)(i + 1)); if (_memberFactory.TryLookupMember(token, out IMetadataMember member) && member is ManifestResource manifestResource) { ((LazyList)(object)val).Add(manifestResource); } } return (IList)val; } protected override IList GetExportedTypes() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) IMetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)39); OwnedCollection val = new OwnedCollection((ModuleDefinition)this, ((ICollection)table).Count); MetadataToken token = default(MetadataToken); for (int i = 0; i < ((ICollection)table).Count; i++) { ((MetadataToken)(ref token))..ctor((TableIndex)39, (uint)(i + 1)); if (_memberFactory.TryLookupMember(token, out IMetadataMember member) && member is ExportedType exportedType) { ((LazyList)(object)val).Add(exportedType); } } return (IList)val; } protected override string GetRuntimeVersion() { return ReaderContext.Metadata.VersionString; } protected override IManagedEntryPoint? GetManagedEntryPoint() { //IL_0006: 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_002b: Unknown result type (might be due to invalid IL or missing references) if ((DotNetDirectory.Flags & 0x10) != 0) { return null; } if (DotNetDirectory.EntryPoint != 0) { return LookupMember(MetadataToken.op_Implicit(DotNetDirectory.EntryPoint)) as IManagedEntryPoint; } return null; } protected override IResourceDirectory? GetNativeResources() { return ReaderContext.Image.Resources; } protected override IList GetDebugData() { return new List(ReaderContext.Image.DebugData); } private AssemblyDefinition? FindParentAssembly() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) MetadataTable table = ReaderContext.TablesStream.GetTable(); if (table.Count > 0) { ModuleReaderContext readerContext = ReaderContext; MetadataToken token = new MetadataToken((TableIndex)32, 1u); AssemblyDefinitionRow row = table[0]; return new SerializedAssemblyDefinition(readerContext, token, in row, this); } return null; } private CorLibTypeFactory CreateCorLibTypeFactory() { IResolutionScope resolutionScope = FindMostRecentCorLib(); if (resolutionScope == null) { return AsmResolver.DotNet.Signatures.Types.CorLibTypeFactory.CreateMscorlib40TypeFactory(this); } return new CorLibTypeFactory(resolutionScope); } private IResolutionScope? FindMostRecentCorLib() { IResolutionScope resolutionScope = null; foreach (AssemblyReference assemblyReference in base.AssemblyReferences) { if (assemblyReference.Name != null && KnownCorLibs.KnownCorLibNames.Contains(Utf8String.op_Implicit(assemblyReference.Name)) && (resolutionScope == null || assemblyReference.Version > resolutionScope.GetAssembly().Version)) { resolutionScope = assemblyReference; } } if (resolutionScope == null) { AssemblyDefinition assembly = base.Assembly; if (assembly != null) { Utf8String name = assembly.Name; if (name != null && KnownCorLibs.KnownCorLibNames.Contains(Utf8String.op_Implicit(name))) { resolutionScope = this; } } } return resolutionScope; } [MemberNotNull("_typeDefTree")] private void EnsureTypeDefinitionTreeInitialized() { if (_typeDefTree == null) { Interlocked.CompareExchange(ref _typeDefTree, InitializeTypeDefinitionTree(), null); } } private OneToManyRelation InitializeTypeDefinitionTree() { //IL_0021: 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) MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)41); OneToManyRelation val = new OneToManyRelation(); foreach (NestedClassRow item in table) { NestedClassRow current = item; val.Add(((NestedClassRow)(ref current)).EnclosingClass, ((NestedClassRow)(ref current)).NestedClass); } return val; } internal ValueSet GetNestedTypeRids(uint enclosingTypeRid) { EnsureTypeDefinitionTreeInitialized(); return _typeDefTree.GetValues(enclosingTypeRid); } internal uint GetParentTypeRid(uint nestedTypeRid) { EnsureTypeDefinitionTreeInitialized(); return _typeDefTree.GetKey(nestedTypeRid); } internal MetadataRange GetFieldRange(uint typeRid) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _fieldLists.GetMemberRange(typeRid); } internal uint GetFieldDeclaringType(uint fieldRid) { return _fieldLists.GetMemberOwner(fieldRid); } internal MetadataRange GetMethodRange(uint typeRid) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _methodLists.GetMemberRange(typeRid); } internal uint GetMethodDeclaringType(uint methodRid) { return _methodLists.GetMemberOwner(methodRid); } internal MetadataRange GetParameterRange(uint methodRid) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _paramLists.GetMemberRange(methodRid); } internal uint GetParameterOwner(uint paramRid) { return _paramLists.GetMemberOwner(paramRid); } internal MetadataRange GetPropertyRange(uint typeRid) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _propertyLists.GetMemberRange(typeRid); } internal uint GetPropertyDeclaringType(uint propertyRid) { return _propertyLists.GetMemberOwner(propertyRid); } internal MetadataRange GetEventRange(uint typeRid) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _eventLists.GetMemberRange(typeRid); } internal uint GetEventDeclaringType(uint eventRid) { return _eventLists.GetMemberOwner(eventRid); } [MemberNotNull("_semantics")] [MemberNotNull("_semanticMethods")] private void EnsureMethodSemanticsInitialized() { if (_semantics == null || _semanticMethods == null) { InitializeMethodSemantics(); } } [MemberNotNull("_semantics")] [MemberNotNull("_semanticMethods")] private void InitializeMethodSemantics() { //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_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) //IL_0060: 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) TablesStream tablesStream = ReaderContext.TablesStream; MetadataTable table = tablesStream.GetTable((TableIndex)24); IndexEncoder indexEncoder = tablesStream.GetIndexEncoder((CodedIndex)62); OneToManyRelation val = new OneToManyRelation(table.Count); Dictionary dictionary = new Dictionary(table.Count); MetadataToken value = default(MetadataToken); for (int i = 0; i < table.Count; i++) { MethodSemanticsRow val2 = table[i]; ((MetadataToken)(ref value))..ctor((TableIndex)24, (uint)(i + 1)); MetadataToken val3 = indexEncoder.DecodeIndex(((MethodSemanticsRow)(ref val2)).Association); val.Add(val3, ((MetadataToken)(ref value)).Rid); dictionary.Add(((MethodSemanticsRow)(ref val2)).Method, value); } Interlocked.CompareExchange(ref _semantics, val, null); Interlocked.CompareExchange(ref _semanticMethods, dictionary, null); } internal ValueSet GetMethodSemantics(MetadataToken owner) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureMethodSemanticsInitialized(); return _semantics.GetValues(owner); } internal MetadataToken GetMethodSemanticsOwner(uint semanticsRid) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) EnsureMethodSemanticsInitialized(); return _semantics.GetKey(semanticsRid); } internal MetadataToken GetMethodParentSemantics(uint methodRid) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) EnsureMethodSemanticsInitialized(); _semanticMethods.TryGetValue(methodRid, out var value); return value; } [MemberNotNull("_constants")] private void EnsureConstantsInitialized() { if (_constants == null) { Interlocked.CompareExchange(ref _constants, GetConstants(), null); } } private OneToOneRelation GetConstants() { //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_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_004a: Unknown result type (might be due to invalid IL or missing references) TablesStream tablesStream = ReaderContext.TablesStream; MetadataTable table = tablesStream.GetTable((TableIndex)11); IndexEncoder indexEncoder = tablesStream.GetIndexEncoder((CodedIndex)57); OneToOneRelation val = new OneToOneRelation(table.Count); for (int i = 0; i < table.Count; i++) { ConstantRow val2 = table[i]; MetadataToken val3 = indexEncoder.DecodeIndex(((ConstantRow)(ref val2)).Parent); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal uint GetConstantRid(MetadataToken ownerToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureConstantsInitialized(); return _constants.GetValue(ownerToken); } internal Constant? GetConstant(MetadataToken ownerToken) { //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) uint constantRid = GetConstantRid(ownerToken); if (!TryLookupMember(new MetadataToken((TableIndex)11, constantRid), out IMetadataMember member)) { return null; } return member as Constant; } internal MetadataToken GetConstantOwner(uint constantRid) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) EnsureConstantsInitialized(); return _constants.GetKey(constantRid); } [MemberNotNull("_customAttributes")] private void EnsureCustomAttributesInitialized() { if (_customAttributes == null) { Interlocked.CompareExchange(ref _customAttributes, InitializeCustomAttributes(), null); } } private OneToManyRelation InitializeCustomAttributes() { //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_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_004a: Unknown result type (might be due to invalid IL or missing references) TablesStream tablesStream = ReaderContext.TablesStream; MetadataTable table = tablesStream.GetTable((TableIndex)12); IndexEncoder indexEncoder = tablesStream.GetIndexEncoder((CodedIndex)58); OneToManyRelation val = new OneToManyRelation(table.Count); for (int i = 0; i < table.Count; i++) { CustomAttributeRow val2 = table[i]; MetadataToken val3 = indexEncoder.DecodeIndex(((CustomAttributeRow)(ref val2)).Parent); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } protected override IList GetCustomAttributes() { return GetCustomAttributeCollection(this); } internal ValueSet GetCustomAttributes(MetadataToken ownerToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureCustomAttributesInitialized(); return _customAttributes.GetValues(ownerToken); } internal MetadataToken GetCustomAttributeOwner(uint attributeRid) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) EnsureCustomAttributesInitialized(); return _customAttributes.GetKey(attributeRid); } internal IList GetCustomAttributeCollection(IHasCustomAttribute owner) { //IL_000d: 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_002b: 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) EnsureCustomAttributesInitialized(); ValueSet values = _customAttributes.GetValues(owner.MetadataToken); OwnedCollection val = new OwnedCollection(owner, values.Count); Enumerator enumerator = values.GetEnumerator(); try { while (enumerator.MoveNext()) { uint current = enumerator.Current; CustomAttribute customAttribute = (CustomAttribute)LookupMember(new MetadataToken((TableIndex)12, current)); ((LazyList)(object)val).Add(customAttribute); } return (IList)val; } finally { ((IDisposable)enumerator).Dispose(); } } [MemberNotNull("_securityDeclarations")] private void EnsureSecurityDeclarationsInitialized() { if (_securityDeclarations == null) { Interlocked.CompareExchange(ref _securityDeclarations, InitializeSecurityDeclarations(), null); } } private OneToManyRelation InitializeSecurityDeclarations() { //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_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_004a: Unknown result type (might be due to invalid IL or missing references) TablesStream tablesStream = ReaderContext.TablesStream; MetadataTable table = tablesStream.GetTable((TableIndex)14); IndexEncoder indexEncoder = tablesStream.GetIndexEncoder((CodedIndex)60); OneToManyRelation val = new OneToManyRelation(table.Count); for (int i = 0; i < table.Count; i++) { SecurityDeclarationRow val2 = table[i]; MetadataToken val3 = indexEncoder.DecodeIndex(((SecurityDeclarationRow)(ref val2)).Parent); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal MetadataToken GetSecurityDeclarationOwner(uint attributeRid) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) EnsureSecurityDeclarationsInitialized(); return _securityDeclarations.GetKey(attributeRid); } internal IList GetSecurityDeclarationCollection(IHasSecurityDeclaration owner) { //IL_000d: 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_002b: 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) EnsureSecurityDeclarationsInitialized(); ValueSet values = _securityDeclarations.GetValues(owner.MetadataToken); OwnedCollection val = new OwnedCollection(owner, values.Count); Enumerator enumerator = values.GetEnumerator(); try { while (enumerator.MoveNext()) { uint current = enumerator.Current; SecurityDeclaration securityDeclaration = (SecurityDeclaration)LookupMember(new MetadataToken((TableIndex)14, current)); ((LazyList)(object)val).Add(securityDeclaration); } return (IList)val; } finally { ((IDisposable)enumerator).Dispose(); } } [MemberNotNull("_genericParameters")] private void EnsureGenericParametersInitialized() { if (_genericParameters == null) { Interlocked.CompareExchange(ref _genericParameters, InitializeGenericParameters(), null); } } private OneToManyRelation InitializeGenericParameters() { //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_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_004a: Unknown result type (might be due to invalid IL or missing references) TablesStream tablesStream = ReaderContext.TablesStream; MetadataTable table = tablesStream.GetTable((TableIndex)42); IndexEncoder indexEncoder = tablesStream.GetIndexEncoder((CodedIndex)68); OneToManyRelation val = new OneToManyRelation(table.Count); for (int i = 0; i < table.Count; i++) { GenericParameterRow val2 = table[i]; MetadataToken val3 = indexEncoder.DecodeIndex(((GenericParameterRow)(ref val2)).Owner); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal MetadataToken GetGenericParameterOwner(uint parameterRid) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) EnsureGenericParametersInitialized(); return _genericParameters.GetKey(parameterRid); } internal ValueSet GetGenericParameters(MetadataToken ownerToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureGenericParametersInitialized(); return _genericParameters.GetValues(ownerToken); } [MemberNotNull("_genericParameterConstraints")] private void EnsureGenericParameterConstrainsInitialized() { if (_genericParameterConstraints == null) { Interlocked.CompareExchange(ref _genericParameterConstraints, InitializeGenericParameterConstraints(), null); } } private OneToManyRelation InitializeGenericParameterConstraints() { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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) MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)44); OneToManyRelation val = new OneToManyRelation(table.Count); MetadataToken val3 = default(MetadataToken); for (int i = 0; i < table.Count; i++) { GenericParameterConstraintRow val2 = table[i]; ((MetadataToken)(ref val3))..ctor((TableIndex)42, ((GenericParameterConstraintRow)(ref val2)).Owner); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal MetadataToken GetGenericParameterConstraintOwner(uint constraintRid) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) EnsureGenericParameterConstrainsInitialized(); return _genericParameterConstraints.GetKey(constraintRid); } internal ValueSet GetGenericParameterConstraints(MetadataToken ownerToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureGenericParameterConstrainsInitialized(); return _genericParameterConstraints.GetValues(ownerToken); } [MemberNotNull("_interfaces")] private void EnsureInterfacesInitialized() { if (_interfaces == null) { Interlocked.CompareExchange(ref _interfaces, InitializeInterfaces(), null); } } private OneToManyRelation InitializeInterfaces() { //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_0041: Unknown result type (might be due to invalid IL or missing references) MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)9); OneToManyRelation val = new OneToManyRelation(table.Count); MetadataToken val3 = default(MetadataToken); for (int i = 0; i < table.Count; i++) { InterfaceImplementationRow val2 = table[i]; ((MetadataToken)(ref val3))..ctor((TableIndex)2, ((InterfaceImplementationRow)(ref val2)).Class); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal MetadataToken GetInterfaceImplementationOwner(uint implementationRid) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) EnsureInterfacesInitialized(); return _interfaces.GetKey(implementationRid); } internal ValueSet GetInterfaceImplementationRids(MetadataToken ownerToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureInterfacesInitialized(); return _interfaces.GetValues(ownerToken); } [MemberNotNull("_methodImplementations")] private void EnsureMethodImplementationsInitialized() { if (_methodImplementations == null) { Interlocked.CompareExchange(ref _methodImplementations, InitializeMethodImplementations(), null); } } private OneToManyRelation InitializeMethodImplementations() { //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_0041: Unknown result type (might be due to invalid IL or missing references) MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)25); OneToManyRelation val = new OneToManyRelation(table.Count); MetadataToken val3 = default(MetadataToken); for (int i = 0; i < table.Count; i++) { MethodImplementationRow val2 = table[i]; ((MetadataToken)(ref val3))..ctor((TableIndex)2, ((MethodImplementationRow)(ref val2)).Class); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal ValueSet GetMethodImplementationRids(MetadataToken ownerToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureMethodImplementationsInitialized(); return _methodImplementations.GetValues(ownerToken); } [MemberNotNull("_classLayouts")] private void EnsureClassLayoutsInitialized() { if (_classLayouts == null) { Interlocked.CompareExchange(ref _classLayouts, InitializeClassLayouts(), null); } } private OneToOneRelation InitializeClassLayouts() { //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_0041: Unknown result type (might be due to invalid IL or missing references) MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)15); OneToOneRelation val = new OneToOneRelation(table.Count); MetadataToken val3 = default(MetadataToken); for (int i = 0; i < table.Count; i++) { ClassLayoutRow val2 = table[i]; ((MetadataToken)(ref val3))..ctor((TableIndex)2, ((ClassLayoutRow)(ref val2)).Parent); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal uint GetClassLayoutRid(MetadataToken ownerToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureClassLayoutsInitialized(); return _classLayouts.GetValue(ownerToken); } [MemberNotNull("_implementationMaps")] private void EnsureImplementationMapsInitialized() { if (_implementationMaps == null) { Interlocked.CompareExchange(ref _implementationMaps, InitializeImplementationMaps(), null); } } private OneToOneRelation InitializeImplementationMaps() { //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_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_004a: Unknown result type (might be due to invalid IL or missing references) TablesStream tablesStream = ReaderContext.TablesStream; MetadataTable table = tablesStream.GetTable((TableIndex)28); IndexEncoder indexEncoder = tablesStream.GetIndexEncoder((CodedIndex)68); OneToOneRelation val = new OneToOneRelation(table.Count); for (int i = 0; i < table.Count; i++) { ImplementationMapRow val2 = table[i]; MetadataToken val3 = indexEncoder.DecodeIndex(((ImplementationMapRow)(ref val2)).MemberForwarded); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal uint GetImplementationMapRid(MetadataToken ownerToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureImplementationMapsInitialized(); return _implementationMaps.GetValue(ownerToken); } internal MetadataToken GetImplementationMapOwner(uint mapRid) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) EnsureImplementationMapsInitialized(); return _implementationMaps.GetKey(mapRid); } [MemberNotNull("_fieldRvas")] private void EnsureFieldRvasInitialized() { if (_fieldRvas == null) { Interlocked.CompareExchange(ref _fieldRvas, InitializeFieldRvas(), null); } } private OneToOneRelation InitializeFieldRvas() { //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_0041: Unknown result type (might be due to invalid IL or missing references) MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)29); OneToOneRelation val = new OneToOneRelation(table.Count); MetadataToken val3 = default(MetadataToken); for (int i = 0; i < table.Count; i++) { FieldRvaRow val2 = table[i]; ((MetadataToken)(ref val3))..ctor((TableIndex)4, ((FieldRvaRow)(ref val2)).Field); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal uint GetFieldRvaRid(MetadataToken fieldToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureFieldRvasInitialized(); return _fieldRvas.GetValue(fieldToken); } [MemberNotNull("_fieldMarshals")] private void EnsureFieldMarshalsInitialized() { if (_fieldMarshals == null) { Interlocked.CompareExchange(ref _fieldMarshals, InitializeFieldMarshals(), null); } } private OneToOneRelation InitializeFieldMarshals() { //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_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_004a: Unknown result type (might be due to invalid IL or missing references) TablesStream tablesStream = ReaderContext.TablesStream; MetadataTable table = tablesStream.GetTable((TableIndex)13); IndexEncoder indexEncoder = tablesStream.GetIndexEncoder((CodedIndex)59); OneToOneRelation val = new OneToOneRelation(table.Count); for (int i = 0; i < table.Count; i++) { FieldMarshalRow val2 = table[i]; MetadataToken val3 = indexEncoder.DecodeIndex(((FieldMarshalRow)(ref val2)).Parent); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal uint GetFieldMarshalRid(MetadataToken fieldToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureFieldMarshalsInitialized(); return _fieldMarshals.GetValue(fieldToken); } internal MarshalDescriptor? GetFieldMarshal(MetadataToken ownerToken) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)13); BlobStream blobStream = ReaderContext.BlobStream; FieldMarshalRow val = default(FieldMarshalRow); BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !table.TryGetByRid(GetFieldMarshalRid(ownerToken), ref val) || !blobStream.TryGetBlobReaderByIndex(((FieldMarshalRow)(ref val)).NativeType, ref reader)) { return null; } return MarshalDescriptor.FromReader(this, ref reader); } [MemberNotNull("_fieldLayouts")] private void EnsureFieldLayoutsInitialized() { if (_fieldLayouts == null) { Interlocked.CompareExchange(ref _fieldLayouts, InitializeFieldLayouts(), null); } } private OneToOneRelation InitializeFieldLayouts() { //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_0041: Unknown result type (might be due to invalid IL or missing references) MetadataTable table = ReaderContext.TablesStream.GetTable((TableIndex)16); OneToOneRelation val = new OneToOneRelation(table.Count); MetadataToken val3 = default(MetadataToken); for (int i = 0; i < table.Count; i++) { FieldLayoutRow val2 = table[i]; ((MetadataToken)(ref val3))..ctor((TableIndex)4, ((FieldLayoutRow)(ref val2)).Field); uint num = (uint)(i + 1); val.Add(val3, num); } return val; } internal uint GetFieldLayoutRid(MetadataToken fieldToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureFieldLayoutsInitialized(); return _fieldLayouts.GetValue(fieldToken); } [MemberNotNull("_exportInfos")] private void EnsureExportInfosInitialized() { if (_exportInfos == null) { Interlocked.CompareExchange(ref _exportInfos, InitializeExportInfos(), null); } } private Dictionary InitializeExportInfos() { //IL_0051: 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_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_013d: 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) Dictionary dictionary = new Dictionary(); IExportDirectory exports = ReaderContext.Image.Exports; if (exports == null) { return dictionary; } IDotNetDirectory dotNetDirectory = ReaderContext.Image.DotNetDirectory; VTableFixupsDirectory val = ((dotNetDirectory != null) ? dotNetDirectory.VTableFixups : null); if (val == null || ((Collection)(object)val).Count == 0) { return dictionary; } Platform val2 = default(Platform); if (!Platform.TryGet(ReaderContext.Image.MachineType, ref val2)) { return dictionary; } Dictionary dictionary2 = new Dictionary(); uint key = default(uint); for (int i = 0; i < exports.Entries.Count; i++) { ExportedSymbol val3 = exports.Entries[i]; if (val3.Address.CanRead) { BinaryStreamReader val4 = val3.Address.CreateReader(); if (val2.TryExtractThunkAddress(ReaderContext.Image, val4, ref key)) { dictionary2.Add(key, val3); } } } for (int j = 0; j < ((Collection)(object)val).Count; j++) { VTableTokenCollection tokens = ((Collection)(object)val)[j].Tokens; for (int k = 0; k < ((Collection)(object)tokens).Count; k++) { uint key2 = tokens.Rva + tokens.GetOffsetToIndex(k); if (dictionary2.TryGetValue(key2, out var value)) { dictionary[((Collection)(object)tokens)[k]] = (value.IsByName ? new UnmanagedExportInfo(value.Name, tokens.Type) : new UnmanagedExportInfo((ushort)value.Ordinal, tokens.Type)); } } } return dictionary; } internal UnmanagedExportInfo? GetExportInfo(MetadataToken methodToken) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) EnsureExportInfosInitialized(); if (!_exportInfos.TryGetValue(methodToken, out var value)) { return null; } return value; } } public class SerializedModuleReference : ModuleReference { private readonly ModuleReaderContext _context; private readonly ModuleReferenceRow _row; public SerializedModuleReference(ModuleReaderContext context, MetadataToken token, in ModuleReferenceRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; ((IOwnedCollectionElement)(object)this).Owner = context.ParentModule; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((ModuleReferenceRow)(ref _row)).Name); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedParameterDefinition : ParameterDefinition { private readonly ModuleReaderContext _context; private readonly ParameterDefinitionRow _row; public SerializedParameterDefinition(ModuleReaderContext context, MetadataToken token, in ParameterDefinitionRow row) : base(token) { //IL_0001: 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_0037: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Sequence = ((ParameterDefinitionRow)(ref row)).Sequence; base.Attributes = ((ParameterDefinitionRow)(ref row)).Attributes; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((ParameterDefinitionRow)(ref _row)).Name); } protected override MethodDefinition? GetMethod() { //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_0031: 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_004c: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken token = default(MetadataToken); ((MetadataToken)(ref token))..ctor((TableIndex)6, parentModule.GetParameterOwner(((MetadataToken)(ref metadataToken)).Rid)); if (!_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Parameter " + ((object)(MetadataToken)(ref metadataToken)).ToString() + " is not in a range of a method."); } return member as MethodDefinition; } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } protected override Constant? GetConstant() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return _context.ParentModule.GetConstant(base.MetadataToken); } protected override MarshalDescriptor? GetMarshalDescriptor() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return _context.ParentModule.GetFieldMarshal(base.MetadataToken); } } public class SerializedPropertyDefinition : PropertyDefinition { private readonly ModuleReaderContext _context; private readonly PropertyDefinitionRow _row; public SerializedPropertyDefinition(ModuleReaderContext context, MetadataToken token, in PropertyDefinitionRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((PropertyDefinitionRow)(ref row)).Attributes; } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((PropertyDefinitionRow)(ref _row)).Name); } protected override PropertySignature? GetSignature() { //IL_0030: 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) BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((PropertyDefinitionRow)(ref _row)).Type, ref reader)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid signature blob index in property " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } BlobReaderContext context2 = new BlobReaderContext(_context); return PropertySignature.FromReader(ref context2, ref reader); } protected override TypeDefinition? GetDeclaringType() { //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_0029: 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_0044: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken token = default(MetadataToken); ((MetadataToken)(ref token))..ctor((TableIndex)2, parentModule.GetPropertyDeclaringType(((MetadataToken)(ref metadataToken)).Rid)); if (!parentModule.TryLookupMember(token, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Property " + ((object)(MetadataToken)(ref metadataToken)).ToString() + " is not in the range of a property map of a declaring type."); } return member as TypeDefinition; } protected override IList GetSemantics() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //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_004c: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; ValueSet methodSemantics = parentModule.GetMethodSemantics(base.MetadataToken); MethodSemanticsCollection methodSemanticsCollection = new MethodSemanticsCollection(this, methodSemantics.Count); methodSemanticsCollection.ValidateMembership = false; Enumerator enumerator = methodSemantics.GetEnumerator(); try { MetadataToken token = default(MetadataToken); while (enumerator.MoveNext()) { uint current = enumerator.Current; ((MetadataToken)(ref token))..ctor((TableIndex)24, current); ((LazyList)(object)methodSemanticsCollection).Add((MethodSemantics)parentModule.LookupMember(token)); } } finally { ((IDisposable)enumerator).Dispose(); } methodSemanticsCollection.ValidateMembership = true; return (IList)methodSemanticsCollection; } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } protected override Constant? GetConstant() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return _context.ParentModule.GetConstant(base.MetadataToken); } } public class SerializedSecurityDeclaration : SecurityDeclaration { private readonly ModuleReaderContext _context; private readonly SecurityDeclarationRow _row; public SerializedSecurityDeclaration(ModuleReaderContext context, MetadataToken token, in SecurityDeclarationRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Action = ((SecurityDeclarationRow)(ref row)).Action; } protected override IHasSecurityDeclaration? GetParent() { //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_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_0020: 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) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; MetadataToken securityDeclarationOwner = parentModule.GetSecurityDeclarationOwner(((MetadataToken)(ref metadataToken)).Rid); if (!parentModule.TryLookupMember(securityDeclarationOwner, out IMetadataMember member)) { ModuleReaderContext context = _context; metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid parent of security declaration " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } return member as IHasSecurityDeclaration; } protected override PermissionSetSignature? GetPermissionSet() { //IL_0030: 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) BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((SecurityDeclarationRow)(ref _row)).PermissionSet, ref reader)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid permission set blob index in security declaration " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } BlobReaderContext context2 = new BlobReaderContext(_context); return PermissionSetSignature.FromReader(in context2, ref reader); } } public class SerializedStandAloneSignature : StandAloneSignature { private readonly ModuleReaderContext _context; private readonly StandAloneSignatureRow _row; public SerializedStandAloneSignature(ModuleReaderContext context, MetadataToken token, in StandAloneSignatureRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; } protected override CallingConventionSignature? GetSignature() { //IL_0030: 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) BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((StandAloneSignatureRow)(ref _row)).Signature, ref reader)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid signature blob index in stand-alone signature " + ((object)(MetadataToken)(ref metadataToken)).ToString() + "."); } BlobReaderContext context2 = new BlobReaderContext(_context); return CallingConventionSignature.FromReader(ref context2, ref reader); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedTypeDefinition : TypeDefinition { private readonly ModuleReaderContext _context; private readonly TypeDefinitionRow _row; public SerializedTypeDefinition(ModuleReaderContext context, MetadataToken token, in TypeDefinitionRow row) : base(token) { //IL_0001: 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_002b: Unknown result type (might be due to invalid IL or missing references) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Attributes = ((TypeDefinitionRow)(ref row)).Attributes; ((IOwnedCollectionElement)(object)this).Owner = context.ParentModule; } protected override Utf8String? GetNamespace() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((TypeDefinitionRow)(ref _row)).Namespace); } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((TypeDefinitionRow)(ref _row)).Name); } protected override ITypeDefOrRef? GetBaseType() { //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_003d: Unknown result type (might be due to invalid IL or missing references) if (((TypeDefinitionRow)(ref _row)).Extends == 0) { return null; } MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)56).DecodeIndex(((TypeDefinitionRow)(ref _row)).Extends); return (ITypeDefOrRef)_context.ParentModule.LookupMember(token); } protected override IList GetNestedTypes() { //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_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_004c: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; ValueSet nestedTypeRids = parentModule.GetNestedTypeRids(((MetadataToken)(ref metadataToken)).Rid); OwnedCollection val = new OwnedCollection((TypeDefinition)this, nestedTypeRids.Count); Enumerator enumerator = nestedTypeRids.GetEnumerator(); try { while (enumerator.MoveNext()) { uint current = enumerator.Current; TypeDefinition typeDefinition = (TypeDefinition)_context.ParentModule.LookupMember(new MetadataToken((TableIndex)2, current)); ((LazyList)(object)val).Add(typeDefinition); } return (IList)val; } finally { ((IDisposable)enumerator).Dispose(); } } protected override TypeDefinition? GetDeclaringType() { //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_002c: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; uint parentTypeRid = parentModule.GetParentTypeRid(((MetadataToken)(ref metadataToken)).Rid); if (!_context.ParentModule.TryLookupMember(new MetadataToken((TableIndex)2, parentTypeRid), out IMetadataMember member)) { return null; } return member as TypeDefinition; } protected override IList GetFields() { //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_001a: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; return CreateMemberCollection(parentModule.GetFieldRange(((MetadataToken)(ref metadataToken)).Rid)); } protected override IList GetMethods() { //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_001a: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; return CreateMemberCollection(parentModule.GetMethodRange(((MetadataToken)(ref metadataToken)).Rid)); } protected override IList GetProperties() { //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_001a: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; return CreateMemberCollection(parentModule.GetPropertyRange(((MetadataToken)(ref metadataToken)).Rid)); } protected override IList GetEvents() { //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_001a: Unknown result type (might be due to invalid IL or missing references) SerializedModuleDefinition parentModule = _context.ParentModule; MetadataToken metadataToken = base.MetadataToken; return CreateMemberCollection(parentModule.GetEventRange(((MetadataToken)(ref metadataToken)).Rid)); } private IList CreateMemberCollection(MetadataRange range) where TMember : class, IMetadataMember, IOwnedCollectionElement { //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_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: Unknown result type (might be due to invalid IL or missing references) OwnedCollection val = new OwnedCollection((TypeDefinition)this, ((MetadataRange)(ref range)).Count); Enumerator enumerator = ((MetadataRange)(ref range)).GetEnumerator(); try { while (((Enumerator)(ref enumerator)).MoveNext()) { MetadataToken current = ((Enumerator)(ref enumerator)).Current; ((LazyList)(object)val).Add((TMember)_context.ParentModule.LookupMember(current)); } return (IList)val; } finally { ((IDisposable)(Enumerator)(ref enumerator)).Dispose(); } } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } protected override IList GetSecurityDeclarations() { return _context.ParentModule.GetSecurityDeclarationCollection(this); } protected override IList GetGenericParameters() { //IL_000c: 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_002a: 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) ValueSet genericParameters = _context.ParentModule.GetGenericParameters(base.MetadataToken); OwnedCollection val = new OwnedCollection((IHasGenericParameters)this, genericParameters.Count); Enumerator enumerator = genericParameters.GetEnumerator(); try { while (enumerator.MoveNext()) { uint current = enumerator.Current; if (_context.ParentModule.TryLookupMember(new MetadataToken((TableIndex)42, current), out IMetadataMember member) && member is GenericParameter genericParameter) { ((LazyList)(object)val).Add(genericParameter); } } return (IList)val; } finally { ((IDisposable)enumerator).Dispose(); } } protected override IList GetInterfaces() { //IL_000c: 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_002a: 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) ValueSet interfaceImplementationRids = _context.ParentModule.GetInterfaceImplementationRids(base.MetadataToken); OwnedCollection val = new OwnedCollection((TypeDefinition)this, interfaceImplementationRids.Count); Enumerator enumerator = interfaceImplementationRids.GetEnumerator(); try { while (enumerator.MoveNext()) { uint current = enumerator.Current; if (_context.ParentModule.TryLookupMember(new MetadataToken((TableIndex)9, current), out IMetadataMember member) && member is InterfaceImplementation interfaceImplementation) { ((LazyList)(object)val).Add(interfaceImplementation); } } return (IList)val; } finally { ((IDisposable)enumerator).Dispose(); } } protected override IList GetMethodImplementations() { //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_0043: 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_0057: 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_008c: Unknown result type (might be due to invalid IL or missing references) TablesStream tablesStream = _context.TablesStream; MetadataTable table = tablesStream.GetTable((TableIndex)25); IndexEncoder indexEncoder = tablesStream.GetIndexEncoder((CodedIndex)63); ValueSet methodImplementationRids = _context.ParentModule.GetMethodImplementationRids(base.MetadataToken); List list = new List(methodImplementationRids.Count); Enumerator enumerator = methodImplementationRids.GetEnumerator(); try { while (enumerator.MoveNext()) { uint current = enumerator.Current; MethodImplementationRow byRid = table.GetByRid(current); _context.ParentModule.TryLookupMember(indexEncoder.DecodeIndex(((MethodImplementationRow)(ref byRid)).MethodBody), out IMetadataMember member); _context.ParentModule.TryLookupMember(indexEncoder.DecodeIndex(((MethodImplementationRow)(ref byRid)).MethodDeclaration), out IMetadataMember member2); list.Add(new MethodImplementation(member2 as IMethodDefOrRef, member as IMethodDefOrRef)); } return list; } finally { ((IDisposable)enumerator).Dispose(); } } protected override ClassLayout? GetClassLayout() { //IL_000c: 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) uint classLayoutRid = _context.ParentModule.GetClassLayoutRid(base.MetadataToken); if (_context.ParentModule.TryLookupMember(new MetadataToken((TableIndex)15, classLayoutRid), out IMetadataMember member) && member is ClassLayout classLayout) { classLayout.Parent = this; return classLayout; } return null; } } public class SerializedTypeReference : TypeReference { private readonly ModuleReaderContext _context; private readonly TypeReferenceRow _row; public SerializedTypeReference(ModuleReaderContext context, MetadataToken token, in TypeReferenceRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; base.Module = context.ParentModule; } protected override Utf8String? GetNamespace() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((TypeReferenceRow)(ref _row)).Namespace); } protected override Utf8String? GetName() { StringsStream? stringsStream = _context.StringsStream; if (stringsStream == null) { return null; } return stringsStream.GetStringByIndex(((TypeReferenceRow)(ref _row)).Name); } protected override IResolutionScope? GetScope() { //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_0047: 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) if (((TypeReferenceRow)(ref _row)).ResolutionScope == 0) { return _context.ParentModule; } MetadataToken token = _context.TablesStream.GetIndexEncoder((CodedIndex)67).DecodeIndex(((TypeReferenceRow)(ref _row)).ResolutionScope); if (_context.ParentModule.TryLookupMember(token, out IMetadataMember member)) { return member as IResolutionScope; } return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)_context, $"Invalid resolution scope in type reference {base.MetadataToken}."); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } public class SerializedTypeSpecification : TypeSpecification { private readonly ModuleReaderContext _context; private readonly TypeSpecificationRow _row; public SerializedTypeSpecification(ModuleReaderContext context, MetadataToken token, in TypeSpecificationRow row) : base(token) { //IL_0001: 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) _context = context ?? throw new ArgumentNullException("context"); _row = row; } protected override TypeSignature? GetSignature() { //IL_0030: 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_005e: Unknown result type (might be due to invalid IL or missing references) BlobStream blobStream = _context.BlobStream; BinaryStreamReader reader = default(BinaryStreamReader); if (blobStream == null || !blobStream.TryGetBlobReaderByIndex(((TypeSpecificationRow)(ref _row)).Signature, ref reader)) { ModuleReaderContext context = _context; MetadataToken metadataToken = base.MetadataToken; return ErrorListenerExtensions.BadImageAndReturn((IErrorListener)(object)context, "Invalid blob signature for type specification " + ((object)(MetadataToken)(ref metadataToken)).ToString()); } BlobReaderContext context2 = new BlobReaderContext(_context); context2.StepInToken(base.MetadataToken); return TypeSignature.FromReader(ref context2, ref reader); } protected override IList GetCustomAttributes() { return _context.ParentModule.GetCustomAttributeCollection(this); } } } namespace AsmResolver.DotNet.Resources { public class DefaultResourceDataSerializer : IResourceDataSerializer { public static DefaultResourceDataSerializer Instance { get; } = new DefaultResourceDataSerializer(); public virtual void Serialize(IBinaryStreamWriter writer, ResourceType type, object? value) { if (value != null) { if (!(value is byte[] array)) { throw new NotSupportedException($"Invalid or unsupported object type {value.GetType()}."); } IOExtensions.WriteBytes(writer, array); } } public virtual object? Deserialize(ref BinaryStreamReader reader, ResourceType type) { return ((BinaryStreamReader)(ref reader)).ReadToEnd(); } } public class IntrinsicResourceType : ResourceType { private static readonly ConcurrentDictionary Instances = new ConcurrentDictionary(); public ResourceTypeCode TypeCode { get; } public override string FullName => TypeCode switch { ResourceTypeCode.Null => "null", ResourceTypeCode.String => "System.String", ResourceTypeCode.Boolean => "System.Boolean", ResourceTypeCode.Char => "System.Char", ResourceTypeCode.Byte => "System.Byte", ResourceTypeCode.SByte => "System.SByte", ResourceTypeCode.Int16 => "System.Int16", ResourceTypeCode.UInt16 => "System.UInt16", ResourceTypeCode.Int32 => "System.Int32", ResourceTypeCode.UInt32 => "System.UInt32", ResourceTypeCode.Int64 => "System.Int64", ResourceTypeCode.UInt64 => "System.UInt64", ResourceTypeCode.Single => "System.Single", ResourceTypeCode.Double => "System.Double", ResourceTypeCode.Decimal => "System.Decimal", ResourceTypeCode.DateTime => "System.DateTime", ResourceTypeCode.TimeSpan => "System.TimeSpan", ResourceTypeCode.ByteArray => "System.Byte[]", ResourceTypeCode.Stream => "System.IO.Stream", _ => throw new ArgumentOutOfRangeException(), }; public static IntrinsicResourceType Get(ResourceTypeCode code) { if (code >= ResourceTypeCode.StartOfUserTypes) { throw new ArgumentOutOfRangeException("code"); } IntrinsicResourceType value; while (!Instances.TryGetValue(code, out value)) { value = new IntrinsicResourceType(code); Instances.TryAdd(code, value); } return value; } private IntrinsicResourceType(ResourceTypeCode typeCode) { TypeCode = typeCode; } } public interface IResourceDataSerializer { void Serialize(IBinaryStreamWriter writer, ResourceType type, object? value); object? Deserialize(ref BinaryStreamReader reader, ResourceType type); } public static class KnownResourceReaderNames { public const string ResourceReader_mscorlib_v2_0_0_0 = "System.Resources.ResourceReader, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string ResourceReader_mscorlib_v4_0_0_0 = "System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string DeserializingResourceReader_SystemResourcesExtensions_v4_0_0_0 = "System.Resources.Extensions.DeserializingResourceReader, System.Resources.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51"; public const string RuntimeResourceSet = "System.Resources.RuntimeResourceSet"; public const string RuntimeResourceSet_SystemResourcesExtensions_v4_0_0_0 = "System.Resources.Extensions.RuntimeResourceSet, System.Resources.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51"; } public readonly struct ResourceManagerHeader : IWritable { public const uint Magic = 3203386062u; public static readonly ResourceManagerHeader Default_v2_0_0_0 = new ResourceManagerHeader("System.Resources.ResourceReader, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Resources.RuntimeResourceSet"); public static readonly ResourceManagerHeader Default_v4_0_0_0 = new ResourceManagerHeader("System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Resources.RuntimeResourceSet"); public static readonly ResourceManagerHeader Deserializing_v4_0_0_0 = new ResourceManagerHeader("System.Resources.Extensions.DeserializingResourceReader, System.Resources.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51", "System.Resources.Extensions.RuntimeResourceSet, System.Resources.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51"); public uint HeaderSize { get; } public string ResourceReaderName { get; } public string ResourceSetName { get; } public ResourceManagerHeader(string resourceReaderName, string resourceSetName) : this(Extensions.GetBinaryFormatterSize(resourceReaderName) + Extensions.GetBinaryFormatterSize(resourceSetName), resourceReaderName, resourceSetName) { } private ResourceManagerHeader(uint headerSize, string resourceReaderName, string resourceSetName) { HeaderSize = headerSize; ResourceReaderName = resourceReaderName; ResourceSetName = resourceSetName; } public static ResourceManagerHeader FromReader(ref BinaryStreamReader reader) { uint num = ((BinaryStreamReader)(ref reader)).ReadUInt32(); if (num != 3203386062u) { throw new FormatException($"Invalid magic number 0x{num:X8}."); } uint num2 = ((BinaryStreamReader)(ref reader)).ReadUInt32(); if (num2 != 1) { throw new NotSupportedException($"Invalid or unsupported header version {num2}."); } return new ResourceManagerHeader(((BinaryStreamReader)(ref reader)).ReadUInt32(), ((BinaryStreamReader)(ref reader)).ReadBinaryFormatterString(), ((BinaryStreamReader)(ref reader)).ReadBinaryFormatterString()); } public uint GetPhysicalSize() { return 12 + HeaderSize; } public void Write(IBinaryStreamWriter writer) { writer.WriteUInt32(3203386062u); writer.WriteUInt32(1u); writer.WriteUInt32(GetPhysicalSize() - 12); IOExtensions.WriteBinaryFormatterString(writer, ResourceReaderName); IOExtensions.WriteBinaryFormatterString(writer, ResourceSetName); } } public class ResourceSet : LazyList { public ResourceManagerHeader ManagerHeader { get; set; } public int FormatVersion { get; set; } public ResourceSet() : this(ResourceManagerHeader.Default_v4_0_0_0, 2) { } public ResourceSet(ResourceManagerHeader managerHeader) : this(managerHeader, 2) { } public ResourceSet(ResourceManagerHeader managerHeader, int formatVersion) { ManagerHeader = managerHeader; FormatVersion = formatVersion; } public static ResourceSet FromReader(in BinaryStreamReader reader) { return FromReader(in reader, DefaultResourceDataSerializer.Instance); } public static ResourceSet FromReader(in BinaryStreamReader reader, IResourceDataSerializer serializer) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return new SerializedResourceSet(reader, serializer); } protected override void Initialize() { } public void Write(IBinaryStreamWriter writer) { Write(writer, DefaultResourceDataSerializer.Instance); } public void Write(IBinaryStreamWriter writer, IResourceDataSerializer serializer) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown int formatVersion = FormatVersion; if (formatVersion != 1 && formatVersion != 2) { throw new NotSupportedException($"Invalid or unsupported format version {FormatVersion}."); } using MemoryStream memoryStream = new MemoryStream(); BinaryStreamWriter val = new BinaryStreamWriter((Stream)memoryStream); ResourceSetEntry[] array = base.Items.OrderBy((ResourceSetEntry item) => item.Name).ToArray(); ResourceSetEntryHeader[] array2 = new ResourceSetEntryHeader[((LazyList)(object)this).Count]; uint num = 0u; uint[] array3 = new uint[((LazyList)(object)this).Count]; uint[] array4 = new uint[((LazyList)(object)this).Count]; List list = new List(); Dictionary dictionary = new Dictionary(); for (int i = 0; i < array.Length; i++) { ResourceSetEntry resourceSetEntry = array[i]; if ((FormatVersion == 1 || !(resourceSetEntry.Type is IntrinsicResourceType)) && !dictionary.TryGetValue(resourceSetEntry.Type.FullName, out var value)) { value = list.Count; if (FormatVersion == 2) { value += 64; } dictionary[resourceSetEntry.Type.FullName] = value; list.Add(resourceSetEntry.Type.FullName); } else { if (!(resourceSetEntry.Type is IntrinsicResourceType intrinsicResourceType)) { throw new NotSupportedException("Invalid or unsupported resource type " + resourceSetEntry.Type.FullName + "."); } value = (int)intrinsicResourceType.TypeCode; } ResourceSetEntryHeader resourceSetEntryHeader = (array2[i] = new ResourceSetEntryHeader(resourceSetEntry.Name, (uint)val.Offset)); array3[i] = HashString(resourceSetEntry.Name); array4[i] = num; num += resourceSetEntryHeader.GetPhysicalSize(); resourceSetEntry.Write((IBinaryStreamWriter)(object)val, FormatVersion, value, serializer); } ManagerHeader.Write(writer); writer.WriteInt32(FormatVersion); writer.WriteInt32(((LazyList)(object)this).Count); writer.WriteInt32(list.Count); foreach (string item in list) { IOExtensions.WriteBinaryFormatterString(writer, item); } int num2 = 0; while ((writer.Offset & 7) != 0L) { writer.WriteByte((byte)"PAD"[num2++ % 3]); } Array.Sort(array3, array4); uint[] array5 = array3; foreach (uint num3 in array5) { writer.WriteUInt32(num3); } array5 = array4; foreach (uint num4 in array5) { writer.WriteUInt32(num4); } writer.WriteUInt32((uint)(writer.Offset + 4 + num)); ResourceSetEntryHeader[] array6 = array2; foreach (ResourceSetEntryHeader resourceSetEntryHeader2 in array6) { resourceSetEntryHeader2.Write(writer); } IOExtensions.WriteBytes(writer, memoryStream.ToArray()); } private static uint HashString(string key) { uint num = 5381u; foreach (char c in key) { num = ((num << 5) + num) ^ c; } return num; } } public class ResourceSetEntry { private readonly LazyVariable _data; public string Name { get; } public ResourceType Type { get; } public object? Data { get { return _data.Value; } set { _data.Value = value; } } public ResourceSetEntry(string name, ResourceTypeCode typeCode) { Name = name; Type = IntrinsicResourceType.Get(typeCode); _data = new LazyVariable((Func)GetData); } public ResourceSetEntry(string name, ResourceType type) { Name = name; Type = type; _data = new LazyVariable((Func)GetData); } public ResourceSetEntry(string name, ResourceTypeCode typeCode, object? data) { Name = name; Type = IntrinsicResourceType.Get(typeCode); _data = new LazyVariable(data); } public ResourceSetEntry(string name, ResourceType type, object? data) { Name = name; Type = type; _data = new LazyVariable(data); } protected virtual object? GetData() { return null; } public override string ToString() { return Name + " : " + Type.FullName; } internal void Write(IBinaryStreamWriter writer, int formatVersion, int typeCode, IResourceDataSerializer serializer) { IOExtensions.Write7BitEncodedInt32(writer, typeCode); switch (formatVersion) { case 1: WriteV1(writer, serializer); break; case 2: WriteV2(writer, serializer); break; default: throw new NotSupportedException("Invalid or unsupported format version number."); } } private void WriteV1(IBinaryStreamWriter writer, IResourceDataSerializer serializer) { if (Data != null) { string text = Type.FullName; int num = text.IndexOf(','); if (num >= 0) { text = text.Remove(num); } switch (text) { case "System.String": IOExtensions.WriteBinaryFormatterString(writer, (string)Data); break; case "System.Boolean": writer.WriteByte((byte)(((bool)Data) ? 1u : 0u)); break; case "System.Char": writer.WriteUInt16((ushort)(char)Data); break; case "System.Byte": writer.WriteByte((byte)Data); break; case "System.SByte": writer.WriteSByte((sbyte)Data); break; case "System.Int16": writer.WriteInt16((short)Data); break; case "System.UInt16": writer.WriteUInt16((ushort)Data); break; case "System.Int32": writer.WriteInt32((int)Data); break; case "System.UInt32": writer.WriteUInt32((uint)Data); break; case "System.Int64": writer.WriteInt64((long)Data); break; case "System.UInt64": writer.WriteUInt64((ulong)Data); break; case "System.Single": writer.WriteSingle((float)Data); break; case "System.Double": writer.WriteDouble((double)Data); break; case "System.Decimal": writer.WriteDecimal((decimal)Data); break; case "System.DateTime": writer.WriteInt64(((DateTime)Data).Ticks); break; case "System.TimeSpan": writer.WriteInt64(((TimeSpan)Data).Ticks); break; default: serializer.Serialize(writer, Type, Data); break; } } } private void WriteV2(IBinaryStreamWriter writer, IResourceDataSerializer serializer) { if (Data == null) { return; } if (!(Type is IntrinsicResourceType intrinsicResourceType)) { WriteV1(writer, serializer); return; } switch (intrinsicResourceType.TypeCode) { case ResourceTypeCode.String: IOExtensions.WriteBinaryFormatterString(writer, (string)Data); break; case ResourceTypeCode.Boolean: writer.WriteByte((byte)(((bool)Data) ? 1u : 0u)); break; case ResourceTypeCode.Char: writer.WriteUInt16((ushort)(char)Data); break; case ResourceTypeCode.Byte: writer.WriteByte((byte)Data); break; case ResourceTypeCode.SByte: writer.WriteSByte((sbyte)Data); break; case ResourceTypeCode.Int16: writer.WriteInt16((short)Data); break; case ResourceTypeCode.UInt16: writer.WriteUInt16((ushort)Data); break; case ResourceTypeCode.Int32: writer.WriteInt32((int)Data); break; case ResourceTypeCode.UInt32: writer.WriteUInt32((uint)Data); break; case ResourceTypeCode.Int64: writer.WriteInt64((long)Data); break; case ResourceTypeCode.UInt64: writer.WriteUInt64((ulong)Data); break; case ResourceTypeCode.Single: writer.WriteSingle((float)Data); break; case ResourceTypeCode.Double: writer.WriteDouble((double)Data); break; case ResourceTypeCode.Decimal: writer.WriteDecimal((decimal)Data); break; case ResourceTypeCode.DateTime: writer.WriteInt64(((DateTime)Data).Ticks); break; case ResourceTypeCode.TimeSpan: writer.WriteInt64(((TimeSpan)Data).Ticks); break; case ResourceTypeCode.ByteArray: case ResourceTypeCode.Stream: { byte[] array = (byte[])Data; writer.WriteInt32(array.Length); IOExtensions.WriteBytes(writer, array); break; } default: serializer.Serialize(writer, Type, Data); break; case ResourceTypeCode.Null: break; } } } internal readonly struct ResourceSetEntryHeader : IWritable { public string Name { get; } public uint Offset { get; } public ResourceSetEntryHeader(string name, uint offset) { Name = name; Offset = offset; } public static ResourceSetEntryHeader FromReader(ref BinaryStreamReader reader) { return new ResourceSetEntryHeader(((BinaryStreamReader)(ref reader)).ReadBinaryFormatterString(Encoding.Unicode), ((BinaryStreamReader)(ref reader)).ReadUInt32()); } public uint GetPhysicalSize() { return Extensions.GetBinaryFormatterSize(Name, Encoding.Unicode) + 4; } public void Write(IBinaryStreamWriter writer) { IOExtensions.WriteBinaryFormatterString(writer, Name, Encoding.Unicode); writer.WriteUInt32(Offset); } } public abstract class ResourceType { public abstract string FullName { get; } public override string ToString() { return FullName; } } public enum ResourceTypeCode { Null = 0, String = 1, Boolean = 2, Char = 3, Byte = 4, SByte = 5, Int16 = 6, UInt16 = 7, Int32 = 8, UInt32 = 9, Int64 = 10, UInt64 = 11, Single = 12, Double = 13, Decimal = 14, DateTime = 15, TimeSpan = 16, ByteArray = 32, Stream = 33, StartOfUserTypes = 64 } public class SerializedResourceSet : ResourceSet { private readonly int _originalCount; private readonly BinaryStreamReader _dataSectionReader; private readonly BinaryStreamReader _entryReader; public override int Count { get { if (!((LazyList)(object)this).IsInitialized) { return _originalCount; } return ((LazyList)(object)this).Items.Count; } } internal int OriginalFormatVersion { get; } internal UserDefinedResourceType[] OriginalUserTypes { get; } internal IResourceDataSerializer DataSerializer { get; } public SerializedResourceSet(BinaryStreamReader reader, IResourceDataSerializer dataSerializer) { //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0191: 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) DataSerializer = dataSerializer; uint relativeOffset = ((BinaryStreamReader)(ref reader)).RelativeOffset; base.ManagerHeader = ResourceManagerHeader.FromReader(ref reader); if (!base.ManagerHeader.ResourceReaderName.StartsWith("System.Resources.ResourceReader") && !base.ManagerHeader.ResourceReaderName.StartsWith("System.Resources.Extensions.DeserializingResourceReader")) { throw new NotSupportedException("Unsupported resource reader type " + base.ManagerHeader.ResourceReaderName + "."); } ((BinaryStreamReader)(ref reader)).RelativeOffset = relativeOffset + base.ManagerHeader.GetPhysicalSize(); base.FormatVersion = (OriginalFormatVersion = ((BinaryStreamReader)(ref reader)).ReadInt32()); int originalFormatVersion = OriginalFormatVersion; if (originalFormatVersion != 1 && originalFormatVersion != 2) { throw new NotSupportedException($"Invalid or unsupported resource set version {OriginalFormatVersion}."); } _originalCount = ((BinaryStreamReader)(ref reader)).ReadInt32(); if (_originalCount < 0) { throw new FormatException("Negative entry count."); } int num = ((BinaryStreamReader)(ref reader)).ReadInt32(); if (num < 0) { throw new FormatException("Negative user type count."); } OriginalUserTypes = new UserDefinedResourceType[num]; for (int i = 0; i < num; i++) { OriginalUserTypes[i] = new UserDefinedResourceType(((BinaryStreamReader)(ref reader)).ReadBinaryFormatterString()); } ((BinaryStreamReader)(ref reader)).AlignRelative(8u); ((BinaryStreamReader)(ref reader)).RelativeOffset = ((BinaryStreamReader)(ref reader)).RelativeOffset + (uint)(_originalCount * 4 * 2); _dataSectionReader = ((BinaryStreamReader)(ref reader)).ForkRelative(((BinaryStreamReader)(ref reader)).ReadUInt32()); _entryReader = ((BinaryStreamReader)(ref reader)).Fork(); } protected override void Initialize() { //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_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) base.Initialize(); ResourceSetEntryHeader[] array = new ResourceSetEntryHeader[_originalCount]; BinaryStreamReader reader = _entryReader; for (int i = 0; i < _originalCount; i++) { array[i] = ResourceSetEntryHeader.FromReader(ref reader); } Array.Sort(array, (ResourceSetEntryHeader a, ResourceSetEntryHeader b) => a.Offset.CompareTo(b.Offset)); for (int j = 0; j < _originalCount; j++) { uint num = ((j < _originalCount - 1) ? array[j + 1].Offset : ((BinaryStreamReader)(ref _dataSectionReader)).Length) - array[j].Offset; BinaryStreamReader contentsReader = ((BinaryStreamReader)(ref _dataSectionReader)).ForkRelative(array[j].Offset, num); ResourceType resourceType = GetResourceType(((BinaryStreamReader)(ref contentsReader)).Read7BitEncodedInt32()); ((LazyList)(object)this).Items.Add(new SerializedResourceSetEntry(this, array[j].Name, resourceType, in contentsReader)); } } private ResourceType GetResourceType(int typeCode) { return OriginalFormatVersion switch { 1 => GetResourceTypeV1(typeCode), 2 => GetResourceTypeV2(typeCode), _ => throw new NotSupportedException("Invalid or unsupported resource set data version."), }; } private ResourceType GetResourceTypeV1(int typeCode) { if (typeCode == -1) { return IntrinsicResourceType.Get(ResourceTypeCode.Null); } if (typeCode < 0 || typeCode >= OriginalUserTypes.Length) { throw new FormatException($"Invalid resource type code {typeCode}."); } return OriginalUserTypes[typeCode]; } private ResourceType GetResourceTypeV2(int typeCode) { if (typeCode < 64) { return IntrinsicResourceType.Get((ResourceTypeCode)typeCode); } int num = typeCode - 64; if (num >= OriginalUserTypes.Length) { throw new FormatException($"Invalid resource type code {typeCode}."); } return OriginalUserTypes[num]; } } public class SerializedResourceSetEntry : ResourceSetEntry { private readonly SerializedResourceSet _parentSet; private readonly BinaryStreamReader _contentsReader; public SerializedResourceSetEntry(SerializedResourceSet parentSet, string name, ResourceType type, in BinaryStreamReader contentsReader) : base(name, type) { //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) _parentSet = parentSet; _contentsReader = contentsReader; } protected override object? GetData() { return _parentSet.OriginalFormatVersion switch { 1 => GetDataV1(), 2 => GetDataV2(), _ => throw new NotSupportedException("Invalid or unsupported resource set data version."), }; } private object? GetDataV1() { //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) if (base.Type is IntrinsicResourceType intrinsicResourceType && intrinsicResourceType.TypeCode == ResourceTypeCode.Null) { return null; } string text = base.Type.FullName; int num = text.IndexOf(','); if (num >= 0) { text = text.Remove(num); } BinaryStreamReader reader = _contentsReader; return text switch { "System.String" => ((BinaryStreamReader)(ref reader)).ReadBinaryFormatterString(), "System.Boolean" => ((BinaryStreamReader)(ref reader)).ReadByte() != 0, "System.Char" => (char)((BinaryStreamReader)(ref reader)).ReadUInt16(), "System.Byte" => ((BinaryStreamReader)(ref reader)).ReadByte(), "System.SByte" => ((BinaryStreamReader)(ref reader)).ReadSByte(), "System.Int16" => ((BinaryStreamReader)(ref reader)).ReadInt16(), "System.UInt16" => ((BinaryStreamReader)(ref reader)).ReadUInt16(), "System.Int32" => ((BinaryStreamReader)(ref reader)).ReadInt32(), "System.UInt32" => ((BinaryStreamReader)(ref reader)).ReadUInt32(), "System.Int64" => ((BinaryStreamReader)(ref reader)).ReadInt64(), "System.UInt64" => ((BinaryStreamReader)(ref reader)).ReadUInt64(), "System.Single" => ((BinaryStreamReader)(ref reader)).ReadSingle(), "System.Double" => ((BinaryStreamReader)(ref reader)).ReadDouble(), "System.Decimal" => ((BinaryStreamReader)(ref reader)).ReadDecimal(), "System.DateTime" => new DateTime(((BinaryStreamReader)(ref reader)).ReadInt64()), "System.TimeSpan" => new TimeSpan(((BinaryStreamReader)(ref reader)).ReadInt64()), _ => _parentSet.DataSerializer.Deserialize(ref reader, base.Type), }; } private object? GetDataV2() { //IL_0003: 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) BinaryStreamReader reader = _contentsReader; if (!(base.Type is IntrinsicResourceType intrinsicResourceType)) { return _parentSet.DataSerializer.Deserialize(ref reader, base.Type); } return intrinsicResourceType.TypeCode switch { ResourceTypeCode.Null => null, ResourceTypeCode.String => ((BinaryStreamReader)(ref reader)).ReadBinaryFormatterString(), ResourceTypeCode.Boolean => ((BinaryStreamReader)(ref reader)).ReadByte() != 0, ResourceTypeCode.Char => (char)((BinaryStreamReader)(ref reader)).ReadUInt16(), ResourceTypeCode.Byte => ((BinaryStreamReader)(ref reader)).ReadByte(), ResourceTypeCode.SByte => ((BinaryStreamReader)(ref reader)).ReadSByte(), ResourceTypeCode.Int16 => ((BinaryStreamReader)(ref reader)).ReadInt16(), ResourceTypeCode.UInt16 => ((BinaryStreamReader)(ref reader)).ReadUInt16(), ResourceTypeCode.Int32 => ((BinaryStreamReader)(ref reader)).ReadInt32(), ResourceTypeCode.UInt32 => ((BinaryStreamReader)(ref reader)).ReadUInt32(), ResourceTypeCode.Int64 => ((BinaryStreamReader)(ref reader)).ReadInt64(), ResourceTypeCode.UInt64 => ((BinaryStreamReader)(ref reader)).ReadUInt64(), ResourceTypeCode.Single => ((BinaryStreamReader)(ref reader)).ReadSingle(), ResourceTypeCode.Double => ((BinaryStreamReader)(ref reader)).ReadDouble(), ResourceTypeCode.Decimal => ((BinaryStreamReader)(ref reader)).ReadDecimal(), ResourceTypeCode.DateTime => DateTime.FromBinary(((BinaryStreamReader)(ref reader)).ReadInt64()), ResourceTypeCode.TimeSpan => new TimeSpan(((BinaryStreamReader)(ref reader)).ReadInt64()), ResourceTypeCode.ByteArray => ReadByteArray(), ResourceTypeCode.Stream => ReadByteArray(), _ => _parentSet.DataSerializer.Deserialize(ref reader, base.Type), }; byte[] ReadByteArray() { int num = ((BinaryStreamReader)(ref reader)).ReadInt32(); if (num < 0) { throw new FormatException("Resource data length is negative."); } byte[] array = new byte[num]; ((BinaryStreamReader)(ref reader)).ReadBytes(array, 0, num); return array; } } } public class UserDefinedResourceType : ResourceType { public override string FullName { get; } public UserDefinedResourceType(string fullName) { FullName = fullName; } } } namespace AsmResolver.DotNet.Memory { [Serializable] public class CyclicStructureException : Exception { public CyclicStructureException() : base("The structure defines a field which introduces a cyclic dependency.") { } public CyclicStructureException(string message) : base(message) { } public CyclicStructureException(string message, Exception inner) : base(message, inner) { } protected CyclicStructureException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class FieldMemoryLayout { public FieldDefinition Field { get; } public uint Offset { get; } public TypeMemoryLayout ContentsLayout { get; } public FieldMemoryLayout(FieldDefinition field, uint offset, TypeMemoryLayout contentsLayout) { Field = field ?? throw new ArgumentNullException("field"); Offset = offset; ContentsLayout = contentsLayout; } } [Flags] public enum MemoryLayoutAttributes { Is32Bit = 0, Is64Bit = 1, BitnessMask = 1, IsPlatformDependent = 2 } internal class TypeAlignmentDetector : ITypeSignatureVisitor { private readonly Stack _traversedTypes = new Stack(); private readonly bool _is32Bit; private GenericContext _currentGenericContext; private uint PointerSize { get { if (!_is32Bit) { return 8u; } return 4u; } } public TypeAlignmentDetector(GenericContext currentGenericContext, bool is32Bit) { _currentGenericContext = currentGenericContext; _is32Bit = is32Bit; } public uint VisitArrayType(ArrayTypeSignature signature) { return PointerSize; } public uint VisitBoxedType(BoxedTypeSignature signature) { return PointerSize; } public uint VisitByReferenceType(ByReferenceTypeSignature signature) { return PointerSize; } public uint VisitCorLibType(CorLibTypeSignature signature) { //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_0009: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected I4, but got Unknown ElementType elementType = signature.ElementType; return (elementType - 2) switch { 0 => 1u, 1 => 2u, 2 => 1u, 3 => 1u, 4 => 2u, 5 => 2u, 6 => 4u, 7 => 4u, 8 => 8u, 9 => 8u, 10 => 4u, 11 => 8u, 12 => PointerSize, 22 => PointerSize, 23 => PointerSize, 26 => PointerSize, _ => throw new ArgumentOutOfRangeException("signature"), }; } public uint VisitCustomModifierType(CustomModifierTypeSignature signature) { return signature.BaseType.AcceptVisitor(this); } public uint VisitGenericInstanceType(GenericInstanceTypeSignature signature) { GenericContext currentGenericContext = _currentGenericContext; _currentGenericContext = _currentGenericContext.WithType(signature); uint result = VisitTypeDefOrRef(signature.GenericType); _currentGenericContext = currentGenericContext; return result; } public uint VisitGenericParameter(GenericParameterSignature signature) { return _currentGenericContext.GetTypeArgument(signature).AcceptVisitor(this); } public uint VisitPinnedType(PinnedTypeSignature signature) { return signature.BaseType.AcceptVisitor(this); } public uint VisitPointerType(PointerTypeSignature signature) { return PointerSize; } public uint VisitSentinelType(SentinelTypeSignature signature) { throw new ArgumentException("Sentinel types do not have a size."); } public uint VisitSzArrayType(SzArrayTypeSignature signature) { return PointerSize; } public uint VisitTypeDefOrRef(TypeDefOrRefSignature signature) { return VisitTypeDefOrRef(signature.Type); } public uint VisitFunctionPointerType(FunctionPointerTypeSignature signature) { return PointerSize; } public uint VisitTypeDefOrRef(ITypeDefOrRef 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_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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Invalid comparison between Unknown and I4 MetadataToken metadataToken = type.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; if ((int)table != 1) { if ((int)table == 2) { return VisitTypeDefinition((TypeDefinition)type); } throw new ArgumentException("Invalid type."); } return VisitTypeReference((TypeReference)type); } private uint VisitTypeReference(TypeReference type) { return VisitTypeDefinition(type.Resolve() ?? throw new ArgumentException("Could not resolve " + type.SafeToString() + ".")); } public uint VisitTypeDefinition(TypeDefinition type) { if (!type.IsValueType) { return PointerSize; } if (_traversedTypes.Contains(type)) { throw new CyclicStructureException(); } _traversedTypes.Push(type); uint num = 1u; for (int i = 0; i < type.Fields.Count; i++) { FieldDefinition fieldDefinition = type.Fields[i]; if (!fieldDefinition.IsStatic) { if (fieldDefinition.Signature == null) { throw new ArgumentException("Field " + fieldDefinition.SafeToString() + " does not have a field signature."); } num = Math.Max(num, fieldDefinition.Signature.FieldType.AcceptVisitor(this)); } } uint num2 = num; ClassLayout classLayout = type.ClassLayout; if (classLayout != null) { uint num3 = ((classLayout.PackingSize == 0) ? PointerSize : classLayout.PackingSize); if (classLayout.ClassSize == 0 || num3 <= classLayout.ClassSize) { num2 = Math.Min(num2, num3); } } _traversedTypes.Pop(); return num2; } } public class TypeMemoryLayout { private readonly Dictionary _fields = new Dictionary(); public ITypeDescriptor Type { get; } public FieldMemoryLayout this[FieldDefinition field] { get { return _fields[field]; } internal set { _fields[field] = value; } } public uint Size { get; internal set; } public MemoryLayoutAttributes Attributes { get; internal set; } public bool Is32Bit => (Attributes & MemoryLayoutAttributes.Is64Bit) == 0; public bool Is64Bit => (Attributes & MemoryLayoutAttributes.Is64Bit) == MemoryLayoutAttributes.Is64Bit; public bool IsPlatformDependent => (Attributes & MemoryLayoutAttributes.IsPlatformDependent) != 0; internal TypeMemoryLayout(ITypeDescriptor type) { Type = type ?? throw new ArgumentNullException("type"); } public TypeMemoryLayout(ITypeDescriptor type, uint size, MemoryLayoutAttributes attributes) { Type = type ?? throw new ArgumentNullException("type"); Size = size; Attributes = attributes; } private IEnumerable GetOrderedFields() { return from f in _fields.Values orderby f.Offset, f.ContentsLayout.Size select f; } public bool TryGetFieldAtOffset(uint offset, [NotNullWhen(true)] out FieldMemoryLayout? field) { foreach (FieldMemoryLayout orderedField in GetOrderedFields()) { if (orderedField.Offset == offset) { field = orderedField; return true; } } field = null; return false; } public bool TryGetFieldPath(uint offset, out IList path) { path = new List(); FieldMemoryLayout fieldMemoryLayout = null; TypeMemoryLayout typeMemoryLayout = this; bool flag = false; while (!flag) { flag = true; foreach (FieldMemoryLayout orderedField in typeMemoryLayout.GetOrderedFields()) { if (offset >= orderedField.Offset && offset < orderedField.Offset + orderedField.ContentsLayout.Size) { if (orderedField.Offset == offset) { fieldMemoryLayout = orderedField; } path.Add(orderedField); typeMemoryLayout = orderedField.ContentsLayout; offset -= orderedField.Offset; flag = false; break; } } } if (path.Count > 0) { return path[path.Count - 1] == fieldMemoryLayout; } return false; } } public static class TypeMemoryLayoutDetection { public static TypeMemoryLayout GetImpliedMemoryLayout(this ITypeDescriptor type, bool is32Bit) { if (!(type is TypeSignature type2)) { if (type is ITypeDefOrRef type3) { return type3.GetImpliedMemoryLayout(is32Bit); } throw new ArgumentOutOfRangeException(); } return type2.GetImpliedMemoryLayout(is32Bit); } public static TypeMemoryLayout GetImpliedMemoryLayout(this TypeSignature type, bool is32Bit) { TypeMemoryLayoutDetector visitor = new TypeMemoryLayoutDetector(is32Bit); return type.AcceptVisitor(visitor); } public static TypeMemoryLayout GetImpliedMemoryLayout(this ITypeDefOrRef type, bool is32Bit) { return new TypeMemoryLayoutDetector(is32Bit).VisitTypeDefOrRef(type); } } public class TypeMemoryLayoutDetector : ITypeSignatureVisitor { private readonly Stack _traversedTypes = new Stack(); private readonly MemoryLayoutAttributes _defaultAttributes; private GenericContext _currentGenericContext; private bool Is32Bit => (_defaultAttributes & MemoryLayoutAttributes.Is64Bit) == 0; private int PointerSize { get { if (!Is32Bit) { return 8; } return 4; } } public TypeMemoryLayoutDetector(bool is32Bit) : this(default(GenericContext), is32Bit) { } public TypeMemoryLayoutDetector(GenericContext currentGenericContext, bool is32Bit) { _currentGenericContext = currentGenericContext; _defaultAttributes = ((!is32Bit) ? MemoryLayoutAttributes.Is64Bit : MemoryLayoutAttributes.Is32Bit); } public TypeMemoryLayout VisitArrayType(ArrayTypeSignature signature) { return CreatePointerLayout(signature); } public TypeMemoryLayout VisitBoxedType(BoxedTypeSignature signature) { return CreatePointerLayout(signature); } public TypeMemoryLayout VisitByReferenceType(ByReferenceTypeSignature signature) { return CreatePointerLayout(signature); } public unsafe TypeMemoryLayout VisitCorLibType(CorLibTypeSignature signature) { //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_0009: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected I4, but got Unknown ElementType elementType = signature.ElementType; object obj = (elementType - 2) switch { 0 => (1, false), 1 => (2, false), 2 => (1, false), 3 => (1, false), 4 => (2, false), 5 => (2, false), 6 => (4, false), 7 => (4, false), 8 => (8, false), 9 => (8, false), 10 => (4, false), 11 => (8, false), 12 => (PointerSize, true), 22 => (PointerSize, true), 23 => (PointerSize, true), 26 => (PointerSize, true), 20 => (PointerSize * 2, true), _ => throw new ArgumentOutOfRangeException("signature"), }; int item = ((ValueTuple*)(&obj))->Item1; bool item2 = ((ValueTuple*)(&obj))->Item2; MemoryLayoutAttributes memoryLayoutAttributes = _defaultAttributes; if (item2) { memoryLayoutAttributes |= MemoryLayoutAttributes.IsPlatformDependent; } return new TypeMemoryLayout(signature, (uint)item, memoryLayoutAttributes); } public TypeMemoryLayout VisitCustomModifierType(CustomModifierTypeSignature signature) { return signature.BaseType.AcceptVisitor(this); } public TypeMemoryLayout VisitGenericInstanceType(GenericInstanceTypeSignature signature) { GenericContext currentGenericContext = _currentGenericContext; _currentGenericContext = _currentGenericContext.WithType(signature); TypeMemoryLayout result = VisitTypeDefOrRef(signature.GenericType); _currentGenericContext = currentGenericContext; return result; } public TypeMemoryLayout VisitGenericParameter(GenericParameterSignature signature) { return _currentGenericContext.GetTypeArgument(signature).AcceptVisitor(this); } public TypeMemoryLayout VisitPinnedType(PinnedTypeSignature signature) { return CreatePointerLayout(signature); } public TypeMemoryLayout VisitPointerType(PointerTypeSignature signature) { return CreatePointerLayout(signature); } public TypeMemoryLayout VisitSentinelType(SentinelTypeSignature signature) { throw new ArgumentException("Sentinel types do not have a size."); } public TypeMemoryLayout VisitSzArrayType(SzArrayTypeSignature signature) { return CreatePointerLayout(signature); } public TypeMemoryLayout VisitTypeDefOrRef(TypeDefOrRefSignature signature) { return VisitTypeDefOrRef(signature.Type); } public TypeMemoryLayout VisitFunctionPointerType(FunctionPointerTypeSignature signature) { return CreatePointerLayout(signature); } public TypeMemoryLayout VisitTypeDefOrRef(ITypeDefOrRef 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_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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Invalid comparison between Unknown and I4 MetadataToken metadataToken = type.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; if ((int)table != 1) { if ((int)table == 2) { return VisitTypeDefinition((TypeDefinition)type); } throw new ArgumentException("Invalid type."); } return VisitTypeReference((TypeReference)type); } private TypeMemoryLayout VisitTypeReference(TypeReference type) { return VisitTypeDefinition(type.Resolve() ?? throw new ArgumentException("Could not resolve type " + type.SafeToString() + ".")); } private TypeMemoryLayout VisitTypeDefinition(TypeDefinition type) { if (!type.IsValueType) { return CreatePointerLayout(type); } return VisitValueTypeDefinition(type); } private TypeMemoryLayout VisitValueTypeDefinition(TypeDefinition type) { if (_traversedTypes.Contains(type)) { throw new CyclicStructureException(); } _traversedTypes.Push(type); uint alignment = new TypeAlignmentDetector(_currentGenericContext, Is32Bit).VisitTypeDefinition(type); TypeMemoryLayout typeMemoryLayout = (type.IsExplicitLayout ? InferExplicitLayout(type, alignment) : InferSequentialLayout(type, alignment)); typeMemoryLayout.Size = Math.Max(1u, typeMemoryLayout.Size); ClassLayout classLayout = type.ClassLayout; if (classLayout != null) { typeMemoryLayout.Size = Math.Max(classLayout.ClassSize, typeMemoryLayout.Size); } _traversedTypes.Pop(); return typeMemoryLayout; } private TypeMemoryLayout InferSequentialLayout(TypeDefinition type, uint alignment) { TypeMemoryLayout typeMemoryLayout = new TypeMemoryLayout(type); typeMemoryLayout.Attributes = _defaultAttributes; uint num = 0u; for (int i = 0; i < type.Fields.Count; i++) { FieldDefinition fieldDefinition = type.Fields[i]; if (!fieldDefinition.IsStatic) { if (fieldDefinition.Signature == null) { throw new ArgumentException("Field " + fieldDefinition.SafeToString() + " does not have a field signature."); } TypeMemoryLayout typeMemoryLayout2 = fieldDefinition.Signature.FieldType.AcceptVisitor(this); if (typeMemoryLayout2.IsPlatformDependent) { typeMemoryLayout.Attributes |= MemoryLayoutAttributes.IsPlatformDependent; } num = Extensions.Align(num, Math.Min(typeMemoryLayout2.Size, alignment)); typeMemoryLayout[fieldDefinition] = new FieldMemoryLayout(fieldDefinition, num, typeMemoryLayout2); num += typeMemoryLayout2.Size; } } typeMemoryLayout.Size = Extensions.Align(num, alignment); return typeMemoryLayout; } private TypeMemoryLayout InferExplicitLayout(TypeDefinition type, uint alignment) { //IL_006b: Unknown result type (might be due to invalid IL or missing references) TypeMemoryLayout typeMemoryLayout = new TypeMemoryLayout(type); typeMemoryLayout.Attributes = _defaultAttributes; uint num = 0u; for (int i = 0; i < type.Fields.Count; i++) { FieldDefinition fieldDefinition = type.Fields[i]; if (!fieldDefinition.IsStatic) { if (!fieldDefinition.FieldOffset.HasValue) { throw new ArgumentException($"{fieldDefinition.FullName} ({fieldDefinition.MetadataToken}) is defined in a type with explicit layout, but does not have a field offset assigned."); } uint value = (uint)fieldDefinition.FieldOffset.Value; if (fieldDefinition.Signature == null) { throw new ArgumentException("Field " + fieldDefinition.SafeToString() + " does not have a field signature."); } TypeMemoryLayout typeMemoryLayout2 = fieldDefinition.Signature.FieldType.AcceptVisitor(this); if (typeMemoryLayout2.IsPlatformDependent) { typeMemoryLayout.Attributes |= MemoryLayoutAttributes.IsPlatformDependent; } typeMemoryLayout[fieldDefinition] = new FieldMemoryLayout(fieldDefinition, value, typeMemoryLayout2); num = Math.Max(num, value + typeMemoryLayout2.Size); } } typeMemoryLayout.Size = Extensions.Align(num, alignment); return typeMemoryLayout; } private TypeMemoryLayout CreatePointerLayout(ITypeDescriptor type) { return new TypeMemoryLayout(type, (uint)PointerSize, _defaultAttributes | MemoryLayoutAttributes.IsPlatformDependent); } } } namespace AsmResolver.DotNet.Config.Json { public class RuntimeConfiguration { public RuntimeOptions RuntimeOptions { get; set; } public static RuntimeConfiguration? FromFile(string path) { return FromJson(File.ReadAllText(path)); } public static RuntimeConfiguration? FromJson(string json) { return JsonSerializer.Deserialize(json, RuntimeConfigurationSerializerContext.Default.RuntimeConfiguration); } public RuntimeConfiguration() { RuntimeOptions = new RuntimeOptions(); } public RuntimeConfiguration(RuntimeOptions options) { RuntimeOptions = options; } public string ToJson() { return JsonSerializer.Serialize(this, RuntimeConfigurationSerializerContext.Default.RuntimeConfiguration); } public void Write(string path) { File.WriteAllText(path, ToJson()); } } [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] [JsonSerializable(typeof(RuntimeConfiguration))] [GeneratedCode("System.Text.Json.SourceGeneration", "6.0.7.2304")] internal class RuntimeConfigurationSerializerContext : JsonSerializerContext { private JsonTypeInfo? _String; private JsonTypeInfo? _JsonElement; private JsonTypeInfo>? _DictionaryStringJsonElement; private JsonTypeInfo? _RuntimeFramework; private JsonTypeInfo>? _ListRuntimeFramework; private JsonTypeInfo? _Boolean; private JsonTypeInfo? _NullableBoolean; private JsonTypeInfo? _Int32; private JsonTypeInfo? _NullableInt32; private JsonTypeInfo>? _ListString; private JsonTypeInfo? _RuntimeOptions; private JsonTypeInfo? _RuntimeConfiguration; private static RuntimeConfigurationSerializerContext? s_defaultContext; private static readonly JsonEncodedText PropName_runtimeOptions = JsonEncodedText.Encode("runtimeOptions"); private static readonly JsonEncodedText PropName_configProperties = JsonEncodedText.Encode("configProperties"); private static readonly JsonEncodedText PropName_tfm = JsonEncodedText.Encode("tfm"); private static readonly JsonEncodedText PropName_framework = JsonEncodedText.Encode("framework"); private static readonly JsonEncodedText PropName_includedFrameworks = JsonEncodedText.Encode("includedFrameworks"); private static readonly JsonEncodedText PropName_applyPatches = JsonEncodedText.Encode("applyPatches"); private static readonly JsonEncodedText PropName_rollForwardOnNoCandidateFx = JsonEncodedText.Encode("rollForwardOnNoCandidateFx"); private static readonly JsonEncodedText PropName_additionalProbingPaths = JsonEncodedText.Encode("additionalProbingPaths"); private static readonly JsonEncodedText PropName_name = JsonEncodedText.Encode("name"); private static readonly JsonEncodedText PropName_version = JsonEncodedText.Encode("version"); public JsonTypeInfo String { get { if (_String == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(string))) != null) { _String = JsonMetadataServices.CreateValueInfo(base.Options, runtimeProvidedCustomConverter); } else { _String = JsonMetadataServices.CreateValueInfo(base.Options, JsonMetadataServices.StringConverter); } } return _String; } } public JsonTypeInfo JsonElement { get { if (_JsonElement == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(JsonElement))) != null) { _JsonElement = JsonMetadataServices.CreateValueInfo(base.Options, runtimeProvidedCustomConverter); } else { _JsonElement = JsonMetadataServices.CreateValueInfo(base.Options, JsonMetadataServices.JsonElementConverter); } } return _JsonElement; } } public JsonTypeInfo> DictionaryStringJsonElement { get { if (_DictionaryStringJsonElement == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(Dictionary))) != null) { _DictionaryStringJsonElement = JsonMetadataServices.CreateValueInfo>(base.Options, runtimeProvidedCustomConverter); } else { JsonCollectionInfoValues> collectionInfo = new JsonCollectionInfoValues> { ObjectCreator = () => new Dictionary(), KeyInfo = String, ElementInfo = JsonElement, NumberHandling = JsonNumberHandling.Strict, SerializeHandler = DictionaryStringJsonElementSerializeHandler }; _DictionaryStringJsonElement = JsonMetadataServices.CreateDictionaryInfo, string, JsonElement>(base.Options, collectionInfo); } } return _DictionaryStringJsonElement; } } public JsonTypeInfo RuntimeFramework { get { if (_RuntimeFramework == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(RuntimeFramework))) != null) { _RuntimeFramework = JsonMetadataServices.CreateValueInfo(base.Options, runtimeProvidedCustomConverter); } else { JsonObjectInfoValues objectInfo = new JsonObjectInfoValues { ObjectCreator = () => new RuntimeFramework(), ObjectWithParameterizedConstructorCreator = null, PropertyMetadataInitializer = RuntimeFrameworkPropInit, ConstructorParameterMetadataInitializer = null, NumberHandling = JsonNumberHandling.Strict, SerializeHandler = RuntimeFrameworkSerializeHandler }; _RuntimeFramework = JsonMetadataServices.CreateObjectInfo(base.Options, objectInfo); } } return _RuntimeFramework; } } public JsonTypeInfo> ListRuntimeFramework { get { if (_ListRuntimeFramework == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(List))) != null) { _ListRuntimeFramework = JsonMetadataServices.CreateValueInfo>(base.Options, runtimeProvidedCustomConverter); } else { JsonCollectionInfoValues> collectionInfo = new JsonCollectionInfoValues> { ObjectCreator = () => new List(), KeyInfo = null, ElementInfo = RuntimeFramework, NumberHandling = JsonNumberHandling.Strict, SerializeHandler = ListRuntimeFrameworkSerializeHandler }; _ListRuntimeFramework = JsonMetadataServices.CreateListInfo, RuntimeFramework>(base.Options, collectionInfo); } } return _ListRuntimeFramework; } } public JsonTypeInfo Boolean { get { if (_Boolean == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(bool))) != null) { _Boolean = JsonMetadataServices.CreateValueInfo(base.Options, runtimeProvidedCustomConverter); } else { _Boolean = JsonMetadataServices.CreateValueInfo(base.Options, JsonMetadataServices.BooleanConverter); } } return _Boolean; } } public JsonTypeInfo NullableBoolean { get { if (_NullableBoolean == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(bool?))) != null) { _NullableBoolean = JsonMetadataServices.CreateValueInfo(base.Options, runtimeProvidedCustomConverter); } else { _NullableBoolean = JsonMetadataServices.CreateValueInfo(base.Options, JsonMetadataServices.GetNullableConverter(Boolean)); } } return _NullableBoolean; } } public JsonTypeInfo Int32 { get { if (_Int32 == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(int))) != null) { _Int32 = JsonMetadataServices.CreateValueInfo(base.Options, runtimeProvidedCustomConverter); } else { _Int32 = JsonMetadataServices.CreateValueInfo(base.Options, JsonMetadataServices.Int32Converter); } } return _Int32; } } public JsonTypeInfo NullableInt32 { get { if (_NullableInt32 == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(int?))) != null) { _NullableInt32 = JsonMetadataServices.CreateValueInfo(base.Options, runtimeProvidedCustomConverter); } else { _NullableInt32 = JsonMetadataServices.CreateValueInfo(base.Options, JsonMetadataServices.GetNullableConverter(Int32)); } } return _NullableInt32; } } public JsonTypeInfo> ListString { get { if (_ListString == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(List))) != null) { _ListString = JsonMetadataServices.CreateValueInfo>(base.Options, runtimeProvidedCustomConverter); } else { JsonCollectionInfoValues> collectionInfo = new JsonCollectionInfoValues> { ObjectCreator = () => new List(), KeyInfo = null, ElementInfo = String, NumberHandling = JsonNumberHandling.Strict, SerializeHandler = ListStringSerializeHandler }; _ListString = JsonMetadataServices.CreateListInfo, string>(base.Options, collectionInfo); } } return _ListString; } } public JsonTypeInfo RuntimeOptions { get { if (_RuntimeOptions == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(RuntimeOptions))) != null) { _RuntimeOptions = JsonMetadataServices.CreateValueInfo(base.Options, runtimeProvidedCustomConverter); } else { JsonObjectInfoValues objectInfo = new JsonObjectInfoValues { ObjectCreator = () => new RuntimeOptions(), ObjectWithParameterizedConstructorCreator = null, PropertyMetadataInitializer = RuntimeOptionsPropInit, ConstructorParameterMetadataInitializer = null, NumberHandling = JsonNumberHandling.Strict, SerializeHandler = RuntimeOptionsSerializeHandler }; _RuntimeOptions = JsonMetadataServices.CreateObjectInfo(base.Options, objectInfo); } } return _RuntimeOptions; } } public JsonTypeInfo RuntimeConfiguration { get { if (_RuntimeConfiguration == null) { JsonConverter runtimeProvidedCustomConverter; if (base.Options.Converters.Count > 0 && (runtimeProvidedCustomConverter = GetRuntimeProvidedCustomConverter(typeof(RuntimeConfiguration))) != null) { _RuntimeConfiguration = JsonMetadataServices.CreateValueInfo(base.Options, runtimeProvidedCustomConverter); } else { JsonObjectInfoValues objectInfo = new JsonObjectInfoValues { ObjectCreator = () => new RuntimeConfiguration(), ObjectWithParameterizedConstructorCreator = null, PropertyMetadataInitializer = RuntimeConfigurationPropInit, ConstructorParameterMetadataInitializer = null, NumberHandling = JsonNumberHandling.Strict, SerializeHandler = RuntimeConfigurationSerializeHandler }; _RuntimeConfiguration = JsonMetadataServices.CreateObjectInfo(base.Options, objectInfo); } } return _RuntimeConfiguration; } } private static JsonSerializerOptions s_defaultOptions { get; } = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, IgnoreReadOnlyFields = false, IgnoreReadOnlyProperties = false, IncludeFields = false, WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; public static RuntimeConfigurationSerializerContext Default => s_defaultContext ?? (s_defaultContext = new RuntimeConfigurationSerializerContext(new JsonSerializerOptions(s_defaultOptions))); protected override JsonSerializerOptions? GeneratedSerializerOptions { get; } = s_defaultOptions; private static void DictionaryStringJsonElementSerializeHandler(Utf8JsonWriter writer, Dictionary? value) { if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartObject(); foreach (KeyValuePair item in value) { writer.WritePropertyName(item.Key); JsonSerializer.Serialize(writer, item.Value, Default.JsonElement); } writer.WriteEndObject(); } private static JsonPropertyInfo[] RuntimeFrameworkPropInit(JsonSerializerContext context) { RuntimeConfigurationSerializerContext runtimeConfigurationSerializerContext = (RuntimeConfigurationSerializerContext)context; JsonSerializerOptions options = context.Options; JsonPropertyInfo[] array = new JsonPropertyInfo[2]; JsonPropertyInfoValues propertyInfo = new JsonPropertyInfoValues { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeFramework), PropertyTypeInfo = runtimeConfigurationSerializerContext.String, Converter = null, Getter = (object obj) => ((RuntimeFramework)obj).Name, Setter = delegate(object obj, string? value) { ((RuntimeFramework)obj).Name = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "Name", JsonPropertyName = null }; array[0] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo); JsonPropertyInfoValues propertyInfo2 = new JsonPropertyInfoValues { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeFramework), PropertyTypeInfo = runtimeConfigurationSerializerContext.String, Converter = null, Getter = (object obj) => ((RuntimeFramework)obj).Version, Setter = delegate(object obj, string? value) { ((RuntimeFramework)obj).Version = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "Version", JsonPropertyName = null }; array[1] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo2); return array; } private static void RuntimeFrameworkSerializeHandler(Utf8JsonWriter writer, RuntimeFramework? value) { if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartObject(); if (value.Name != null) { writer.WriteString(PropName_name, value.Name); } if (value.Version != null) { writer.WriteString(PropName_version, value.Version); } writer.WriteEndObject(); } private static void ListRuntimeFrameworkSerializeHandler(Utf8JsonWriter writer, List? value) { if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartArray(); for (int i = 0; i < value.Count; i++) { RuntimeFrameworkSerializeHandler(writer, value[i]); } writer.WriteEndArray(); } private static void ListStringSerializeHandler(Utf8JsonWriter writer, List? value) { if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartArray(); for (int i = 0; i < value.Count; i++) { writer.WriteStringValue(value[i]); } writer.WriteEndArray(); } private static JsonPropertyInfo[] RuntimeOptionsPropInit(JsonSerializerContext context) { RuntimeConfigurationSerializerContext runtimeConfigurationSerializerContext = (RuntimeConfigurationSerializerContext)context; JsonSerializerOptions options = context.Options; JsonPropertyInfo[] array = new JsonPropertyInfo[7]; JsonPropertyInfoValues> propertyInfo = new JsonPropertyInfoValues> { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeOptions), PropertyTypeInfo = runtimeConfigurationSerializerContext.DictionaryStringJsonElement, Converter = null, Getter = (object obj) => ((RuntimeOptions)obj).ConfigProperties, Setter = delegate(object obj, Dictionary? value) { ((RuntimeOptions)obj).ConfigProperties = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "ConfigProperties", JsonPropertyName = null }; array[0] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo); JsonPropertyInfoValues propertyInfo2 = new JsonPropertyInfoValues { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeOptions), PropertyTypeInfo = runtimeConfigurationSerializerContext.String, Converter = null, Getter = (object obj) => ((RuntimeOptions)obj).TargetFrameworkMoniker, Setter = delegate(object obj, string? value) { ((RuntimeOptions)obj).TargetFrameworkMoniker = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "TargetFrameworkMoniker", JsonPropertyName = "tfm" }; array[1] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo2); JsonPropertyInfoValues propertyInfo3 = new JsonPropertyInfoValues { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeOptions), PropertyTypeInfo = runtimeConfigurationSerializerContext.RuntimeFramework, Converter = null, Getter = (object obj) => ((RuntimeOptions)obj).Framework, Setter = delegate(object obj, RuntimeFramework? value) { ((RuntimeOptions)obj).Framework = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "Framework", JsonPropertyName = null }; array[2] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo3); JsonPropertyInfoValues> propertyInfo4 = new JsonPropertyInfoValues> { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeOptions), PropertyTypeInfo = runtimeConfigurationSerializerContext.ListRuntimeFramework, Converter = null, Getter = (object obj) => ((RuntimeOptions)obj).IncludedFrameworks, Setter = delegate(object obj, List? value) { ((RuntimeOptions)obj).IncludedFrameworks = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "IncludedFrameworks", JsonPropertyName = null }; array[3] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo4); JsonPropertyInfoValues propertyInfo5 = new JsonPropertyInfoValues { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeOptions), PropertyTypeInfo = runtimeConfigurationSerializerContext.NullableBoolean, Converter = null, Getter = (object obj) => ((RuntimeOptions)obj).ApplyPatches, Setter = delegate(object obj, bool? value) { ((RuntimeOptions)obj).ApplyPatches = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "ApplyPatches", JsonPropertyName = null }; array[4] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo5); JsonPropertyInfoValues propertyInfo6 = new JsonPropertyInfoValues { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeOptions), PropertyTypeInfo = runtimeConfigurationSerializerContext.NullableInt32, Converter = null, Getter = (object obj) => ((RuntimeOptions)obj).RollForwardOnNoCandidateFx, Setter = delegate(object obj, int? value) { ((RuntimeOptions)obj).RollForwardOnNoCandidateFx = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "RollForwardOnNoCandidateFx", JsonPropertyName = null }; array[5] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo6); JsonPropertyInfoValues> propertyInfo7 = new JsonPropertyInfoValues> { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeOptions), PropertyTypeInfo = runtimeConfigurationSerializerContext.ListString, Converter = null, Getter = (object obj) => ((RuntimeOptions)obj).AdditionalProbingPaths, Setter = delegate(object obj, List? value) { ((RuntimeOptions)obj).AdditionalProbingPaths = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "AdditionalProbingPaths", JsonPropertyName = null }; array[6] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo7); return array; } private static void RuntimeOptionsSerializeHandler(Utf8JsonWriter writer, RuntimeOptions? value) { if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartObject(); if (value.ConfigProperties != null) { writer.WritePropertyName(PropName_configProperties); DictionaryStringJsonElementSerializeHandler(writer, value.ConfigProperties); } if (value.TargetFrameworkMoniker != null) { writer.WriteString(PropName_tfm, value.TargetFrameworkMoniker); } if (value.Framework != null) { writer.WritePropertyName(PropName_framework); RuntimeFrameworkSerializeHandler(writer, value.Framework); } if (value.IncludedFrameworks != null) { writer.WritePropertyName(PropName_includedFrameworks); ListRuntimeFrameworkSerializeHandler(writer, value.IncludedFrameworks); } if (value.ApplyPatches.HasValue) { writer.WritePropertyName(PropName_applyPatches); JsonSerializer.Serialize(writer, value.ApplyPatches, Default.NullableBoolean); } if (value.RollForwardOnNoCandidateFx.HasValue) { writer.WritePropertyName(PropName_rollForwardOnNoCandidateFx); JsonSerializer.Serialize(writer, value.RollForwardOnNoCandidateFx, Default.NullableInt32); } if (value.AdditionalProbingPaths != null) { writer.WritePropertyName(PropName_additionalProbingPaths); ListStringSerializeHandler(writer, value.AdditionalProbingPaths); } writer.WriteEndObject(); } private static JsonPropertyInfo[] RuntimeConfigurationPropInit(JsonSerializerContext context) { RuntimeConfigurationSerializerContext runtimeConfigurationSerializerContext = (RuntimeConfigurationSerializerContext)context; JsonSerializerOptions options = context.Options; JsonPropertyInfo[] array = new JsonPropertyInfo[1]; JsonPropertyInfoValues propertyInfo = new JsonPropertyInfoValues { IsProperty = true, IsPublic = true, IsVirtual = false, DeclaringType = typeof(RuntimeConfiguration), PropertyTypeInfo = runtimeConfigurationSerializerContext.RuntimeOptions, Converter = null, Getter = (object obj) => ((RuntimeConfiguration)obj).RuntimeOptions, Setter = delegate(object obj, RuntimeOptions? value) { ((RuntimeConfiguration)obj).RuntimeOptions = value; }, IgnoreCondition = null, HasJsonInclude = false, IsExtensionData = false, NumberHandling = null, PropertyName = "RuntimeOptions", JsonPropertyName = null }; array[0] = JsonMetadataServices.CreatePropertyInfo(options, propertyInfo); return array; } private static void RuntimeConfigurationSerializeHandler(Utf8JsonWriter writer, RuntimeConfiguration? value) { if (value == null) { writer.WriteNullValue(); return; } writer.WriteStartObject(); if (value.RuntimeOptions != null) { writer.WritePropertyName(PropName_runtimeOptions); RuntimeOptionsSerializeHandler(writer, value.RuntimeOptions); } writer.WriteEndObject(); } public RuntimeConfigurationSerializerContext() : base(null) { } public RuntimeConfigurationSerializerContext(JsonSerializerOptions options) : base(options) { } private JsonConverter? GetRuntimeProvidedCustomConverter(Type type) { IList converters = base.Options.Converters; for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (!jsonConverter.CanConvert(type)) { continue; } if (jsonConverter is JsonConverterFactory jsonConverterFactory) { jsonConverter = jsonConverterFactory.CreateConverter(type, base.Options); if (jsonConverter == null || jsonConverter is JsonConverterFactory) { throw new InvalidOperationException($"The converter '{jsonConverterFactory.GetType()}' cannot return null or a JsonConverterFactory instance."); } } return jsonConverter; } return null; } public override JsonTypeInfo GetTypeInfo(Type type) { if (type == typeof(RuntimeConfiguration)) { return RuntimeConfiguration; } if (type == typeof(bool)) { return Boolean; } if (type == typeof(int)) { return Int32; } return null; } } public class RuntimeFramework { public string? Name { get; set; } public string? Version { get; set; } public RuntimeFramework() { } public RuntimeFramework(string name, string version) { Name = name; Version = version; } public override string ToString() { return "Name: " + Name + ", Version: " + Version; } } public class RuntimeOptions { public Dictionary? ConfigProperties { get; set; } [JsonPropertyName("tfm")] public string? TargetFrameworkMoniker { get; set; } public RuntimeFramework? Framework { get; set; } public List? IncludedFrameworks { get; set; } public bool? ApplyPatches { get; set; } public int? RollForwardOnNoCandidateFx { get; set; } public List? AdditionalProbingPaths { get; set; } public RuntimeOptions() { } public RuntimeOptions(string tfm, RuntimeFramework framework) { TargetFrameworkMoniker = tfm; Framework = framework; } public RuntimeOptions(string tfm, string runtimeName, string runtimeVersion) { TargetFrameworkMoniker = tfm; Framework = new RuntimeFramework(runtimeName, runtimeVersion); } public IEnumerable GetAllFrameworks() { RuntimeFramework framework = Framework; if (framework != null) { yield return framework; } List includedFrameworks = IncludedFrameworks; if (includedFrameworks == null) { yield break; } foreach (RuntimeFramework item in includedFrameworks) { yield return item; } } } } namespace AsmResolver.DotNet.Collections { internal class LazyRidListRelation where TAssociationRow : struct, IMetadataRow { public delegate uint GetOwnerRidDelegate(uint rid, TAssociationRow row); public delegate MetadataRange GetMemberListDelegate(uint rid); private readonly IMetadata _metadata; private readonly TableIndex _associationTable; private readonly TableIndex _memberTable; private readonly GetOwnerRidDelegate _getOwnerRid; private readonly GetMemberListDelegate _getMemberRange; private readonly object _lock = new object(); private Dictionary? _memberRanges; private uint[]? _memberOwnerRids; public LazyRidListRelation(IMetadata metadata, TableIndex memberTable, TableIndex associationTable, GetOwnerRidDelegate getOwnerRid, GetMemberListDelegate getMemberList) { //IL_0056: 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_005d: 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) _metadata = metadata ?? throw new ArgumentNullException("metadata"); _getOwnerRid = getOwnerRid ?? throw new ArgumentNullException("getOwnerRid"); _getMemberRange = getMemberList ?? throw new ArgumentNullException("getMemberList"); _associationTable = associationTable; _memberTable = memberTable; } [MemberNotNull("_memberRanges")] [MemberNotNull("_memberOwnerRids")] private void EnsureIsInitialized() { if (_memberRanges == null || _memberOwnerRids == null) { Initialize(); } } [MemberNotNull("_memberRanges")] [MemberNotNull("_memberOwnerRids")] private void Initialize() { //IL_0033: 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_0085: 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_008f: 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_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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) lock (_lock) { if (_memberRanges != null && _memberOwnerRids != null) { return; } TablesStream stream = _metadata.GetStream(); MetadataTable table = stream.GetTable(_associationTable); IMetadataTable table2 = stream.GetTable(_memberTable); Dictionary dictionary = new Dictionary(); uint[] array = new uint[((ICollection)table2).Count]; for (int i = 0; i < table.Count; i++) { uint rid = (uint)(i + 1); uint num = _getOwnerRid(rid, table[i]); MetadataRange val2 = (dictionary[num] = _getMemberRange(rid)); Enumerator enumerator = ((MetadataRange)(ref val2)).GetEnumerator(); try { while (((Enumerator)(ref enumerator)).MoveNext()) { MetadataToken current = ((Enumerator)(ref enumerator)).Current; array[((MetadataToken)(ref current)).Rid - 1] = num; } } finally { ((IDisposable)(Enumerator)(ref enumerator)).Dispose(); } } _memberOwnerRids = array; _memberRanges = dictionary; } } public MetadataRange GetMemberRange(uint ownerRid) { //IL_001c: 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) EnsureIsInitialized(); if (!_memberRanges.TryGetValue(ownerRid, out var value)) { return MetadataRange.Empty; } return value; } public uint GetMemberOwner(uint memberRid) { EnsureIsInitialized(); if (memberRid - 1 >= _memberOwnerRids.Length) { return 0u; } return _memberOwnerRids[memberRid - 1]; } } public class MethodSemanticsCollection : OwnedCollection { internal bool ValidateMembership { get; set; } = true; public MethodSemanticsCollection(IHasSemantics owner) : base(owner) { } public MethodSemanticsCollection(IHasSemantics owner, int capacity) : base(owner, capacity) { } private void AssertSemanticsValidity([NotNull] MethodSemantics item) { if (ValidateMembership) { if (item.Method == null) { throw new ArgumentException("Method semantics is not assigned to a method."); } if (item.Method.Semantics != null) { throw new ArgumentException($"Method {item.Method} is already assigned semantics."); } } } protected override void OnInsertItem(int index, MethodSemantics item) { AssertSemanticsValidity(item); base.OnInsertItem(index, item); item.Method.Semantics = item; } protected override void OnSetItem(int index, MethodSemantics item) { AssertSemanticsValidity(item); ((LazyList)(object)this).Items[index].Method.Semantics = null; base.OnSetItem(index, item); item.Method.Semantics = item; } protected override void OnInsertRange(int index, IEnumerable items) { MethodSemantics[] array = (items as MethodSemantics[]) ?? items.ToArray(); MethodSemantics[] array2 = array; foreach (MethodSemantics item in array2) { AssertSemanticsValidity(item); } base.OnInsertRange(index, (IEnumerable)array); array2 = array; foreach (MethodSemantics methodSemantics in array2) { methodSemantics.Method.Semantics = methodSemantics; } } protected override void OnRemoveItem(int index) { ((LazyList)(object)this).Items[index].Method.Semantics = null; base.OnRemoveItem(index); } protected override void OnClearItems() { foreach (MethodSemantics item in ((LazyList)(object)this).Items) { item.Method.Semantics = null; } base.OnClearItems(); } } public class Parameter : INameProvider { private static readonly List CachedArgNames = new List(); private ParameterCollection? _parentCollection; private TypeSignature _parameterType; public int Index { get; internal set; } public ushort Sequence => (ushort)(Index + 1); public int MethodSignatureIndex { get; } public TypeSignature ParameterType { get { return _parameterType; } set { if (Index < 0) { throw new InvalidOperationException("Cannot update parameter type of return or this parameters."); } _parameterType = value; _parentCollection?.PushParameterUpdateToSignature(this); } } public ParameterDefinition? Definition => _parentCollection?.GetParameterDefinition(Sequence); public string Name => Utf8String.op_Implicit(Definition?.Name ?? Utf8String.op_Implicit(GetDummyArgumentName(MethodSignatureIndex))); internal Parameter(ParameterCollection parentCollection, int index, int methodSignatureIndex) { _parentCollection = parentCollection ?? throw new ArgumentNullException("parentCollection"); Index = index; MethodSignatureIndex = methodSignatureIndex; } private static string GetDummyArgumentName(int index) { if (index >= CachedArgNames.Count) { lock (CachedArgNames) { while (index >= CachedArgNames.Count) { CachedArgNames.Add("A_" + CachedArgNames.Count); } } } return CachedArgNames[index]; } internal void Remove() { _parentCollection = null; Index = -1; } internal void SetParameterTypeInternal(TypeSignature type) { _parameterType = type; } public override string ToString() { return $"{ParameterType} {Name}"; } } [DebuggerDisplay("Count = {Count}")] public class ParameterCollection : IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection { private readonly List _parameters = new List(); private readonly MethodDefinition _owner; private bool _hasThis; public int Count => _parameters.Count; public int MethodSignatureIndexBase { get { if (!_hasThis) { return 0; } return 1; } } public Parameter this[int index] => _parameters[index]; public Parameter ReturnParameter { get; } public Parameter? ThisParameter { get; private set; } internal ParameterCollection(MethodDefinition owner) { _owner = owner ?? throw new ArgumentNullException("owner"); ReturnParameter = new Parameter(this, -1, -1); PullUpdatesFromMethodSignature(); } public void PullUpdatesFromMethodSignature() { bool flag = _owner.Signature?.HasThis ?? false; if (flag != _hasThis) { _parameters.Clear(); _hasThis = flag; } EnsureAllParametersCreated(); UpdateParameterTypes(); } private void EnsureAllParametersCreated() { if (!_hasThis) { ThisParameter = null; } else if (ThisParameter == null) { Parameter parameter2 = (ThisParameter = new Parameter(this, -1, 0)); } int num = _owner.Signature?.ParameterTypes.Count ?? 0; while (_parameters.Count < num) { int count = _parameters.Count; Parameter item = new Parameter(this, count, count + MethodSignatureIndexBase); _parameters.Add(item); } while (_parameters.Count > num) { _parameters[_parameters.Count - 1].Remove(); _parameters.RemoveAt(_parameters.Count - 1); } } private void UpdateParameterTypes() { if (_owner.Signature != null) { ReturnParameter.SetParameterTypeInternal(_owner.Signature.ReturnType); TypeSignature thisParameterType = GetThisParameterType(); if (thisParameterType != null) { ThisParameter?.SetParameterTypeInternal(thisParameterType); } for (int i = 0; i < _parameters.Count; i++) { _parameters[i].SetParameterTypeInternal(_owner.Signature.ParameterTypes[i]); } } } private TypeSignature? GetThisParameterType() { if (_owner.DeclaringType == null) { return null; } TypeSignature typeSignature = _owner.DeclaringType.ToTypeSignature(); if (_owner.DeclaringType.IsValueType) { typeSignature = typeSignature.MakeByReferenceType(); } return typeSignature; } internal ParameterDefinition? GetParameterDefinition(int sequence) { return _owner.ParameterDefinitions.FirstOrDefault((ParameterDefinition p) => p.Sequence == sequence); } internal void PushParameterUpdateToSignature(Parameter parameter) { if (_owner.Signature == null) { return; } if (parameter.Index == -2) { _owner.Signature.ReturnType = parameter.ParameterType; return; } if (parameter.Index == -1) { throw new InvalidOperationException("Cannot update the parameter type of the this parameter."); } _owner.Signature.ParameterTypes[parameter.Index] = parameter.ParameterType; } public bool ContainsSignatureIndex(int index) { int num = index - MethodSignatureIndexBase; int num2 = (_hasThis ? (-1) : 0); if (num >= num2) { return num < Count; } return false; } public Parameter GetBySignatureIndex(int index) { int num = index - MethodSignatureIndexBase; if (num != -1 || !_hasThis) { return this[num]; } return ThisParameter ?? throw new IndexOutOfRangeException(); } public IEnumerator GetEnumerator() { return _parameters.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } namespace AsmResolver.DotNet.Code { public interface IMethodBodySerializer { ISegmentReference SerializeMethodBody(MethodBodySerializationContext context, MethodDefinition method); } public abstract class MethodBody { public MethodDefinition Owner { get; } public ISegmentReference? Address { get; set; } protected MethodBody(MethodDefinition owner) { Owner = owner ?? throw new ArgumentNullException("owner"); } } public class MethodBodySerializationContext { public IMetadataTokenProvider TokenProvider { get; } public INativeSymbolsProvider SymbolsProvider { get; } public IErrorListener ErrorListener { get; } public MethodBodySerializationContext(IMetadataTokenProvider tokenProvider, INativeSymbolsProvider symbolsProvider, IErrorListener errorListener) { TokenProvider = tokenProvider ?? throw new ArgumentNullException("tokenProvider"); SymbolsProvider = symbolsProvider ?? throw new ArgumentNullException("symbolsProvider"); ErrorListener = errorListener ?? throw new ArgumentNullException("errorListener"); } } public class MultiMethodBodySerializer : IMethodBodySerializer { public IMethodBodySerializer ManagedSerializer { get; set; } public IMethodBodySerializer UnmanagedSerializer { get; set; } public MultiMethodBodySerializer(IMethodBodySerializer managedSerializer, IMethodBodySerializer unmanagedSerializer) { ManagedSerializer = managedSerializer; UnmanagedSerializer = unmanagedSerializer; } public ISegmentReference SerializeMethodBody(MethodBodySerializationContext context, MethodDefinition method) { return ((method.MethodBody is CilMethodBody) ? ManagedSerializer : UnmanagedSerializer).SerializeMethodBody(context, method); } } public class UnresolvedMethodBody : MethodBody { public UnresolvedMethodBody(MethodDefinition owner, ISegmentReference address) : base(owner) { base.Address = address; } } } namespace AsmResolver.DotNet.Code.Native { public interface INativeSymbolsProvider { ISymbol ImportSymbol(ISymbol symbol); void RegisterBaseRelocation(BaseRelocation relocation); void RegisterExportedSymbol(ExportedSymbol symbol); void RegisterExportedSymbol(ExportedSymbol symbol, uint? newOrdinal); } public class NativeLocalSymbol : ISymbol { public NativeMethodBody Body { get; } public uint Offset { get; } public NativeLocalSymbol(NativeMethodBody body, uint offset) { Body = body; Offset = offset; } public ISegmentReference? GetReference() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown if (Body.Address == null) { return null; } return (ISegmentReference?)new RelativeReference((IOffsetProvider)(object)Body.Address, (int)Offset); } public override string ToString() { return $"{Body.Owner.SafeToString()}+{Offset:X}"; } } public class NativeMethodBody : MethodBody { public byte[] Code { get; set; } public IList AddressFixups { get; } = new List(); public NativeMethodBody(MethodDefinition owner) : base(owner) { Code = Array.Empty(); } public NativeMethodBody(MethodDefinition owner, byte[] code) : base(owner) { Code = code; } } public class NativeMethodBodySerializer : IMethodBodySerializer { public ISegmentReference SerializeMethodBody(MethodBodySerializationContext context, MethodDefinition method) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown //IL_0060: 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_0082: 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) MethodBody methodBody = method.MethodBody; if (methodBody != null) { ISegmentReference address = methodBody.Address; if (address != null && address.IsBounded) { return methodBody.Address; } } if (!(method.MethodBody is NativeMethodBody nativeMethodBody)) { return SegmentReference.Null; } INativeSymbolsProvider symbolsProvider = context.SymbolsProvider; PatchedSegment val = Extensions.AsPatchedSegment((ISegment)new DataSegment(nativeMethodBody.Code)); for (int i = 0; i < nativeMethodBody.AddressFixups.Count; i++) { AddressFixup fixup = nativeMethodBody.AddressFixups[i]; ISymbol val2 = FinalizeSymbol((ISegment)(object)val, symbolsProvider, ((AddressFixup)(ref fixup)).Symbol); AddressFixupExtensions.Patch(val, ((AddressFixup)(ref fixup)).Offset, ((AddressFixup)(ref fixup)).Type, val2); AddBaseRelocations((ISegment)(object)val, symbolsProvider, fixup); } return Extensions.ToReference((ISegment)(object)val); } protected virtual void AddBaseRelocations(ISegment segment, INativeSymbolsProvider provider, AddressFixup fixup) { //IL_0002: 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_001f: 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_000d: Invalid comparison between Unknown and I4 //IL_003a: Unknown result type (might be due to invalid IL or missing references) AddressFixupType type = ((AddressFixup)(ref fixup)).Type; if ((int)type != 0) { if ((int)type == 1) { provider.RegisterBaseRelocation(new BaseRelocation((RelocationType)10, Extensions.ToReference(segment, (int)((AddressFixup)(ref fixup)).Offset))); } } else { provider.RegisterBaseRelocation(new BaseRelocation((RelocationType)3, Extensions.ToReference(segment, (int)((AddressFixup)(ref fixup)).Offset))); } } protected virtual ISymbol FinalizeSymbol(ISegment result, INativeSymbolsProvider provider, ISymbol symbol) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if (symbol is NativeLocalSymbol nativeLocalSymbol) { return (ISymbol)new Symbol(Extensions.ToReference(result, (int)nativeLocalSymbol.Offset)); } return provider.ImportSymbol(symbol); } } public class NativeSymbolsProvider : INativeSymbolsProvider { private readonly Dictionary _modules = new Dictionary(); private readonly Dictionary _relocations = new Dictionary(); private readonly Dictionary _fixedExportedSymbols = new Dictionary(); private uint _minExportedOrdinal = uint.MaxValue; private uint _maxExportedOrdinal; private readonly List _floatingExportedSymbols = new List(); public ISymbol ImportSymbol(ISymbol symbol) { ImportedSymbol val = (ImportedSymbol)(object)((symbol is ImportedSymbol) ? symbol : null); if (val != null) { return (ISymbol)(object)GetImportedSymbol(val); } throw new NotSupportedException($"Symbols of type {((object)symbol).GetType()} are not supported."); } private ImportedSymbol GetImportedSymbol(ImportedSymbol symbol) { //IL_00bb: 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_00c1: Expected O, but got Unknown if (symbol.DeclaringModule == null) { throw new ArgumentException($"Symbol {symbol} is not added to a module."); } string name = symbol.DeclaringModule.Name; if (name == null) { throw new ArgumentException($"Parent module for symbol {symbol} has no name."); } IImportedModule moduleByName = GetModuleByName(name); if (TryGetSimilarSymbol(symbol, moduleByName, out ImportedSymbol existingSymbol)) { return existingSymbol; } ImportedSymbol val = (symbol.IsImportByName ? new ImportedSymbol(symbol.Hint, symbol.Name) : new ImportedSymbol(symbol.Ordinal)); moduleByName.Symbols.Add(val); return val; } private IImportedModule GetModuleByName(string name) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown if (!_modules.TryGetValue(name, out IImportedModule value)) { value = (IImportedModule)new ImportedModule(name); _modules.Add(value.Name, value); } return value; } private static bool TryGetSimilarSymbol(ImportedSymbol symbol, IImportedModule module, [NotNullWhen(true)] out ImportedSymbol? existingSymbol) { for (int i = 0; i < module.Symbols.Count; i++) { ImportedSymbol val = module.Symbols[i]; if (symbol.IsImportByName != val.IsImportByName) { continue; } if (symbol.IsImportByName) { if (symbol.Name == val.Name) { existingSymbol = val; return true; } } else if (symbol.Ordinal == val.Ordinal) { existingSymbol = val; return true; } } existingSymbol = null; return false; } public void RegisterBaseRelocation(BaseRelocation relocation) { //IL_0070: 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_001f: Unknown result type (might be due to invalid IL or missing references) if (_relocations.TryGetValue(((BaseRelocation)(ref relocation)).Location, out var value)) { if (((BaseRelocation)(ref value)).Type != ((BaseRelocation)(ref relocation)).Type) { throw new ArgumentException($"Conflicting base relocations for reference {((BaseRelocation)(ref relocation)).Location}."); } } else { _relocations.Add(((BaseRelocation)(ref relocation)).Location, relocation); } } public void RegisterExportedSymbol(ExportedSymbol symbol) { RegisterExportedSymbol(symbol, null); } public void RegisterExportedSymbol(ExportedSymbol symbol, uint? newOrdinal) { if (!newOrdinal.HasValue) { _floatingExportedSymbols.Add(symbol); return; } uint value = newOrdinal.Value; if (_fixedExportedSymbols.ContainsKey(value)) { throw new ArgumentException("Ordinal " + value + " was already claimed by another exported symbol."); } _fixedExportedSymbols.Add(value, symbol); _minExportedOrdinal = Math.Min(value, _minExportedOrdinal); _maxExportedOrdinal = Math.Max(value, _maxExportedOrdinal); } public IEnumerable GetImportedModules() { return _modules.Values; } public IEnumerable GetBaseRelocations() { return _relocations.Values; } public IEnumerable GetExportedSymbols(out uint baseOrdinal) { //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Expected O, but got Unknown //IL_01be: Expected O, but got Unknown baseOrdinal = 1u; if (_fixedExportedSymbols.Count == 0 && _floatingExportedSymbols.Count == 0) { return Array.Empty(); } if (_fixedExportedSymbols.Count == 0) { return _floatingExportedSymbols; } baseOrdinal = _minExportedOrdinal; List list = ((IEnumerable)(object)new ExportedSymbol[_maxExportedOrdinal - _minExportedOrdinal + 1]).ToList(); foreach (KeyValuePair fixedExportedSymbol in _fixedExportedSymbols) { list[(int)(fixedExportedSymbol.Key - _minExportedOrdinal)] = fixedExportedSymbol.Value; } int i = (int)_minExportedOrdinal; int j; for (j = 0; j < _floatingExportedSymbols.Count; j++) { if (i >= list.Count) { break; } ExportedSymbol value = _floatingExportedSymbols[j]; for (; i < list.Count && list[i] != null; i++) { } if (i < list.Count) { list[i] = value; } } if (j != _floatingExportedSymbols.Count) { int num = Math.Min((int)(_minExportedOrdinal - 1), _floatingExportedSymbols.Count - j); if (num > 0) { baseOrdinal -= (uint)num; list.InsertRange(0, (IEnumerable)(object)new ExportedSymbol[num]); i = 0; for (; j < num; j++) { list[i++] = _floatingExportedSymbols[j]; } } for (; j < _floatingExportedSymbols.Count; j++) { list.Add(_floatingExportedSymbols[j]); } } for (i = 0; i < list.Count; i++) { List list2 = list; int index = i; if (list2[index] == null) { ExportedSymbol val = new ExportedSymbol(SegmentReference.Null); ExportedSymbol val2 = val; list2[index] = val; } } return list; } } } namespace AsmResolver.DotNet.Code.Cil { public class CilExceptionHandler { public const uint TinyExceptionHandlerSize = 12u; public const uint FatExceptionHandlerSize = 24u; public CilExceptionHandlerType HandlerType { get; set; } public ICilLabel? TryStart { get; set; } public ICilLabel? TryEnd { get; set; } public ICilLabel? HandlerStart { get; set; } public ICilLabel? HandlerEnd { get; set; } public ICilLabel? FilterStart { get; set; } public ITypeDefOrRef? ExceptionType { get; set; } public bool IsFat { get { ICilLabel? tryStart = TryStart; if (tryStart == null || tryStart.Offset < 65535) { ICilLabel? handlerStart = HandlerStart; if (handlerStart == null || handlerStart.Offset < 65535) { ICilLabel? tryEnd = TryEnd; int? num = ((tryEnd != null) ? new int?(tryEnd.Offset) : null); ICilLabel? tryStart2 = TryStart; if (!(num - ((tryStart2 != null) ? new int?(tryStart2.Offset) : null) >= 255)) { ICilLabel? handlerEnd = HandlerEnd; int? num2 = ((handlerEnd != null) ? new int?(handlerEnd.Offset) : null); ICilLabel? handlerStart2 = HandlerStart; return num2 - ((handlerStart2 != null) ? new int?(handlerStart2.Offset) : null) >= 255; } } } return true; } } public static CilExceptionHandler FromReader(CilMethodBody body, ref BinaryStreamReader reader, bool isFat) { //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) CilExceptionHandlerType handlerType; int num; int offset; int num2; int offset2; if (isFat) { handlerType = (CilExceptionHandlerType)((BinaryStreamReader)(ref reader)).ReadUInt32(); num = ((BinaryStreamReader)(ref reader)).ReadInt32(); offset = num + ((BinaryStreamReader)(ref reader)).ReadInt32(); num2 = ((BinaryStreamReader)(ref reader)).ReadInt32(); offset2 = num2 + ((BinaryStreamReader)(ref reader)).ReadInt32(); } else { handlerType = (CilExceptionHandlerType)((BinaryStreamReader)(ref reader)).ReadUInt16(); num = ((BinaryStreamReader)(ref reader)).ReadUInt16(); offset = num + ((BinaryStreamReader)(ref reader)).ReadByte(); num2 = ((BinaryStreamReader)(ref reader)).ReadUInt16(); offset2 = num2 + ((BinaryStreamReader)(ref reader)).ReadByte(); } int num3 = ((BinaryStreamReader)(ref reader)).ReadInt32(); CilExceptionHandler cilExceptionHandler = new CilExceptionHandler { HandlerType = handlerType, TryStart = body.Instructions.GetLabel(num), TryEnd = body.Instructions.GetLabel(offset), HandlerStart = body.Instructions.GetLabel(num2), HandlerEnd = body.Instructions.GetLabel(offset2) }; switch (cilExceptionHandler.HandlerType) { case CilExceptionHandlerType.Exception: { if (body.Owner.Module.TryLookupMember(MetadataToken.op_Implicit(num3), out IMetadataMember member)) { cilExceptionHandler.ExceptionType = member as ITypeDefOrRef; } break; } case CilExceptionHandlerType.Filter: { CilInstruction byOffset = CilInstructionCollectionExtensions.GetByOffset((IList)body.Instructions, num3); cilExceptionHandler.FilterStart = (ICilLabel?)(((object)((byOffset != null) ? byOffset.CreateLabel() : null)) ?? ((object)new CilOffsetLabel(num3))); break; } } return cilExceptionHandler; } public override string ToString() { return string.Format("{0}: {1}, {2}: {3}, {4}: {5}, {6}: {7}, {8}: {9}, {10}: {11}, {12}: {13}", "HandlerType", HandlerType, "TryStart", TryStart, "TryEnd", TryEnd, "HandlerStart", HandlerStart, "HandlerEnd", HandlerEnd, "FilterStart", FilterStart, "ExceptionType", ExceptionType); } } public enum CilExceptionHandlerType : uint { Exception = 0u, Filter = 1u, Finally = 2u, Fault = 4u } [DebuggerDisplay("Count = {Count}")] public class CilInstructionCollection : IList, ICollection, IEnumerable, IEnumerable { public struct Enumerator : IEnumerator, IEnumerator, IDisposable { private List.Enumerator _enumerator; public CilInstruction Current => _enumerator.Current; object IEnumerator.Current => Current; public Enumerator(CilInstructionCollection collection) { _enumerator = collection._items.GetEnumerator(); } public bool MoveNext() { return _enumerator.MoveNext(); } public void Reset() { ((IEnumerator)_enumerator).Reset(); } public void Dispose() { _enumerator.Dispose(); } } private sealed class CilEndLabel : ICilLabel, IEquatable { private readonly CilInstructionCollection _collection; public int Offset { get { if (_collection.Count == 0) { return 0; } CilInstruction val = _collection[_collection.Count - 1]; return val.Offset + val.Size; } } public CilEndLabel(CilInstructionCollection collection) { _collection = collection ?? throw new ArgumentNullException("collection"); } public bool Equals(ICilLabel? other) { if (other != null) { return Offset == other.Offset; } return false; } public override string ToString() { return $"IL_{Offset:X4}"; } } private readonly List _items = new List(); private ICilLabel? _endLabel; public CilMethodBody Owner { get; } public int Count => _items.Count; public bool IsReadOnly => false; public int Size => _items.Sum((CilInstruction x) => x.Size); public CilInstruction this[int index] { get { return _items[index]; } set { _items[index] = value; } } public ICilLabel EndLabel { get { if (_endLabel == null) { Interlocked.CompareExchange(ref _endLabel, (ICilLabel)(object)new CilEndLabel(this), null); } return _endLabel; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, ICilLabel label) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, label); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, params ICilLabel[] labels) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, (IEnumerable)labels); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, IEnumerable labels) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, labels); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, int constant) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, constant); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, long constant) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, constant); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, float constant) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, constant); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, double constant) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, constant); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, string constant) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, constant); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, CilLocalVariable variable) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, variable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, Parameter parameter) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, parameter); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, IFieldDescriptor field) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, field); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, IMethodDescriptor method) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, method); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, MemberReference member) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, member); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, ITypeDefOrRef type) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, type); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, IMetadataMember member) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, member); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, StandAloneSignature signature) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Insert(Count, code, signature); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CilInstruction Add(CilOpCode code, MetadataToken token) { //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) return Insert(Count, code, token); } public CilInstructionCollection(CilMethodBody body) { Owner = body ?? throw new ArgumentNullException("body"); } public void Add(CilInstruction item) { _items.Add(item); } public void AddRange(IEnumerable items) { _items.AddRange(items); } public void InsertRange(int index, IEnumerable items) { _items.InsertRange(index, items); } public void Clear() { _items.Clear(); } public bool Contains(CilInstruction item) { return _items.Contains(item); } public void CopyTo(CilInstruction[] array, int arrayIndex) { _items.CopyTo(array, arrayIndex); } public bool Remove(CilInstruction item) { return _items.Remove(item); } public void RemoveRange(int index, int count) { _items.RemoveRange(index, count); } public void RemoveRange(IEnumerable items) { foreach (CilInstruction item in items) { _items.Remove(item); } } public int IndexOf(CilInstruction item) { return _items.IndexOf(item); } public void Insert(int index, CilInstruction item) { _items.Insert(index, item); } public void RemoveAt(int index) { _items.RemoveAt(index); } public void RemoveAt(int baseIndex, params int[] relativeIndices) { RemoveAt(baseIndex, relativeIndices.AsEnumerable()); } public void RemoveAt(int baseIndex, IEnumerable relativeIndices) { List list = new List(); foreach (int item in relativeIndices.Distinct()) { int num = baseIndex + item; if (num < 0 || num >= _items.Count) { throw new ArgumentOutOfRangeException("relativeIndices"); } list.Add(num); } list.Sort(); for (int i = 0; i < list.Count; i++) { int index = list[i]; _items.RemoveAt(index); for (int j = i + 1; j < list.Count; j++) { list[j]--; } } } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public ICilLabel GetLabel(int offset) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown if (offset >= EndLabel.Offset) { return EndLabel; } CilInstruction byOffset = CilInstructionCollectionExtensions.GetByOffset((IList)this, offset); if (byOffset != null) { return byOffset.CreateLabel(); } return (ICilLabel)new CilOffsetLabel(offset); } public void CalculateOffsets() { int num = 0; foreach (CilInstruction item in _items) { item.Offset = num; num += item.Size; } } public void ExpandMacros() { int num = 0; foreach (CilInstruction item in _items) { item.Offset = num; ExpandMacro(item); num += item.Size; } } private void ExpandMacro(CilInstruction instruction) { //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_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_000f: 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_00ef: Expected I4, but got Unknown //IL_0135: 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_019f: 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_014d: 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_010d: 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_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: 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_023b: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Invalid comparison between Unknown and I4 //IL_0247: Unknown result type (might be due to invalid IL or missing references) CilOpCode opCode = instruction.OpCode; CilCode code = ((CilOpCode)(ref opCode)).Code; switch (code - 2) { case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: instruction.Operand = instruction.GetLdcI4Constant(); instruction.OpCode = CilOpCodes.Ldc_I4; return; case 0: case 1: case 2: case 3: case 12: instruction.Operand = instruction.GetParameter(Owner.Owner.Parameters); instruction.OpCode = CilOpCodes.Ldarg; return; case 13: instruction.OpCode = CilOpCodes.Ldarga; return; case 14: instruction.OpCode = CilOpCodes.Starg; return; case 4: case 5: case 6: case 7: case 15: instruction.Operand = instruction.GetLocalVariable(Owner.LocalVariables); instruction.OpCode = CilOpCodes.Ldloc; return; case 16: instruction.OpCode = CilOpCodes.Ldloca; return; case 8: case 9: case 10: case 11: case 17: instruction.Operand = instruction.GetLocalVariable(Owner.LocalVariables); instruction.OpCode = CilOpCodes.Stloc; return; case 44: instruction.OpCode = CilOpCodes.Beq; return; case 45: instruction.OpCode = CilOpCodes.Bge; return; case 46: instruction.OpCode = CilOpCodes.Bgt; return; case 47: instruction.OpCode = CilOpCodes.Ble; return; case 48: instruction.OpCode = CilOpCodes.Blt; return; case 41: instruction.OpCode = CilOpCodes.Br; return; case 42: instruction.OpCode = CilOpCodes.Brfalse; return; case 43: instruction.OpCode = CilOpCodes.Brtrue; return; case 50: instruction.OpCode = CilOpCodes.Bge_Un; return; case 51: instruction.OpCode = CilOpCodes.Bgt_Un; return; case 52: instruction.OpCode = CilOpCodes.Ble_Un; return; case 53: instruction.OpCode = CilOpCodes.Blt_Un; return; case 49: instruction.OpCode = CilOpCodes.Bne_Un; return; case 18: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: return; } if ((int)code == 222) { instruction.OpCode = CilOpCodes.Leave; } } public void OptimizeMacros() { while (OptimizeMacrosPass()) { } CalculateOffsets(); } private bool OptimizeMacrosPass() { CalculateOffsets(); bool flag = false; foreach (CilInstruction item in _items) { flag |= TryOptimizeMacro(item); } return flag; } private bool TryOptimizeMacro(CilInstruction instruction) { //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_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_000f: 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_0014: Invalid comparison between Unknown and I4 //IL_0016: 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_003b: Expected I4, but got Unknown CilOpCode opCode = instruction.OpCode; CilOperandType operandType = ((CilOpCode)(ref opCode)).OperandType; if ((int)operandType != 0) { if ((int)operandType != 2) { switch (operandType - 14) { case 1: return TryOptimizeBranch(instruction); case 2: if (instruction.IsLdcI4()) { return TryOptimizeLdc(instruction); } break; case 0: return TryOptimizeVariable(instruction); case 4: return TryOptimizeVariable(instruction); case 5: return TryOptimizeArgument(instruction); case 6: return TryOptimizeArgument(instruction); } return false; } return TryOptimizeLdc(instruction); } return TryOptimizeBranch(instruction); } private bool TryOptimizeBranch(CilInstruction instruction) { //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0122: 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_012b: 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_0131: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Expected I4, but got Unknown //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_004e: 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_0055: 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_0093: Expected I4, but got Unknown //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: 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_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_017e: 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_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_018e: 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_0196: 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_01d6: 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_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: 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_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Invalid comparison between Unknown and I4 //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: 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_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: 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_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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_00ab: 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_00b3: 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_00bb: 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_00fe: 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_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_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: 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_00f3: 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_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Invalid comparison between Unknown and I4 //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0116: 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_010b: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01f5: 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_01ec: 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_0114: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) object operand = instruction.Operand; object obj = ((operand is ICilLabel) ? operand : null) ?? throw new ArgumentException("Branch target is null."); int num = instruction.Offset + instruction.Size; int num2 = ((ICilLabel)obj).Offset - num; CilOpCode opCode; CilOpCode val; if (num2 >= -128 && num2 <= 127) { opCode = instruction.OpCode; CilCode code = ((CilOpCode)(ref opCode)).Code; val = (CilOpCode)((code - 56) switch { 3 => CilOpCodes.Beq_S, 4 => CilOpCodes.Bge_S, 5 => CilOpCodes.Bgt_S, 6 => CilOpCodes.Ble_S, 7 => CilOpCodes.Blt_S, 0 => CilOpCodes.Br_S, 1 => CilOpCodes.Brfalse_S, 2 => CilOpCodes.Brtrue_S, 9 => CilOpCodes.Bge_Un_S, 10 => CilOpCodes.Bgt_Un_S, 11 => CilOpCodes.Ble_Un_S, 12 => CilOpCodes.Blt_Un_S, 8 => CilOpCodes.Bne_Un_S, _ => ((int)code != 221) ? instruction.OpCode : CilOpCodes.Leave_S, }); } else { opCode = instruction.OpCode; CilCode code = ((CilOpCode)(ref opCode)).Code; val = (CilOpCode)((code - 43) switch { 3 => CilOpCodes.Beq, 4 => CilOpCodes.Bge, 5 => CilOpCodes.Bgt, 6 => CilOpCodes.Ble, 7 => CilOpCodes.Blt, 0 => CilOpCodes.Br, 1 => CilOpCodes.Brfalse, 2 => CilOpCodes.Brtrue, 9 => CilOpCodes.Bge_Un, 10 => CilOpCodes.Bgt_Un, 11 => CilOpCodes.Ble_Un, 12 => CilOpCodes.Blt_Un, 8 => CilOpCodes.Bne_Un, _ => ((int)code != 222) ? instruction.OpCode : CilOpCodes.Leave, }); } if (instruction.OpCode != val) { instruction.OpCode = val; return true; } return false; } private static bool TryOptimizeLdc(CilInstruction instruction) { //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_0018: 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_0027: Unknown result type (might be due to invalid IL or missing references) var (val, operand) = CilInstruction.GetLdcI4OpCodeOperand(instruction.GetLdcI4Constant()); if (val != instruction.OpCode) { instruction.OpCode = val; instruction.Operand = operand; return true; } return false; } private unsafe bool TryOptimizeVariable(CilInstruction instruction) { //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_016b: Unknown result type (might be due to invalid IL or missing references) //IL_016d: 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_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_011f: 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_00bd: 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_0167: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_014b: 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) //IL_013c: Unknown result type (might be due to invalid IL or missing references) CilLocalVariable localVariable = instruction.GetLocalVariable(Owner.LocalVariables); CilOpCode val = instruction.OpCode; object operand = instruction.Operand; if (instruction.IsLdloc()) { int index = localVariable.Index; object obj = index switch { 0 => (object)(CilOpCodes.Ldloc_0, null), 1 => (object)(CilOpCodes.Ldloc_1, null), 2 => (object)(CilOpCodes.Ldloc_2, null), 3 => (object)(CilOpCodes.Ldloc_3, null), _ => (index < 0 || index > 255) ? (CilOpCodes.Ldloc, localVariable) : (CilOpCodes.Ldloc_S, localVariable), }; object item = ((ValueTuple*)(&obj))->Item2; val = ((ValueTuple*)(&obj))->Item1; operand = item; } else if (instruction.IsStloc()) { int index2 = localVariable.Index; object obj2 = index2 switch { 0 => (object)(CilOpCodes.Stloc_0, null), 1 => (object)(CilOpCodes.Stloc_1, null), 2 => (object)(CilOpCodes.Stloc_2, null), 3 => (object)(CilOpCodes.Stloc_3, null), _ => (index2 < 0 || index2 > 255) ? (CilOpCodes.Stloc, localVariable) : (CilOpCodes.Stloc_S, localVariable), }; object item = ((ValueTuple*)(&obj2))->Item2; val = ((ValueTuple*)(&obj2))->Item1; operand = item; } if (val != instruction.OpCode) { instruction.OpCode = val; instruction.Operand = operand; return true; } return false; } private unsafe bool TryOptimizeArgument(CilInstruction instruction) { //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_00ea: 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_004f: 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) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: 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_00e9: 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_0097: Unknown result type (might be due to invalid IL or missing references) Parameter parameter = instruction.GetParameter(Owner.Owner.Parameters); CilOpCode val = instruction.OpCode; object operand = instruction.Operand; if (instruction.IsLdarg()) { int methodSignatureIndex = parameter.MethodSignatureIndex; object obj = methodSignatureIndex switch { 0 => (object)(CilOpCodes.Ldarg_0, null), 1 => (object)(CilOpCodes.Ldarg_1, null), 2 => (object)(CilOpCodes.Ldarg_2, null), 3 => (object)(CilOpCodes.Ldarg_3, null), _ => (methodSignatureIndex < 0 || methodSignatureIndex > 255) ? (CilOpCodes.Ldarg, parameter) : (CilOpCodes.Ldarg_S, parameter), }; object item = ((ValueTuple*)(&obj))->Item2; val = ((ValueTuple*)(&obj))->Item1; operand = item; } else if (instruction.IsStarg()) { val = ((parameter.MethodSignatureIndex <= 255) ? CilOpCodes.Starg_S : CilOpCodes.Starg); } if (val != instruction.OpCode) { instruction.OpCode = val; instruction.Operand = operand; return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private CilInstruction InsertAndReturn(int index, CilOpCode code, object? operand = null) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown CilInstruction val = new CilInstruction(code, operand); Insert(index, val); return val; } public CilInstruction Insert(int index, CilOpCode code) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0013: 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) if ((int)((CilOpCode)(ref code)).OperandType != 5) { throw new InvalidCilInstructionException(code); } return InsertAndReturn(index, code); } public CilInstruction Insert(int index, CilOpCode code, ICilLabel label) { //IL_0002: 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_0012: Invalid comparison between Unknown and I4 //IL_002b: 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 ((int)((CilOpCode)(ref code)).OperandType != 0 && (int)((CilOpCode)(ref code)).OperandType != 15) { throw new InvalidCilInstructionException(code); } if (label == null) { throw new ArgumentNullException("label"); } return InsertAndReturn(index, code, label); } public CilInstruction Insert(int index, CilOpCode code, params ICilLabel[] labels) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Add(code, (IEnumerable)labels); } public CilInstruction Insert(int index, CilOpCode code, IEnumerable labels) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000b: 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 ((int)((CilOpCode)(ref code)).OperandType != 11) { throw new InvalidCilInstructionException(code); } if (labels == null) { throw new ArgumentNullException("labels"); } return InsertAndReturn(index, code, labels.ToList()); } public CilInstruction Insert(int index, CilOpCode code, int constant) { //IL_0002: 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_000a: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_0031: 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) CilOperandType operandType = ((CilOpCode)(ref code)).OperandType; object obj; if ((int)operandType != 2) { if ((int)operandType != 16) { throw new InvalidCilInstructionException(code); } obj = (sbyte)constant; } else { obj = constant; } object operand = obj; return InsertAndReturn(index, code, operand); } public CilInstruction Insert(int index, CilOpCode code, long constant) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0013: 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) if ((int)((CilOpCode)(ref code)).OperandType != 3) { throw new InvalidCilInstructionException(code); } return InsertAndReturn(index, code, constant); } public CilInstruction Insert(int index, CilOpCode code, float constant) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_0014: 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) if ((int)((CilOpCode)(ref code)).OperandType != 17) { throw new InvalidCilInstructionException(code); } return InsertAndReturn(index, code, constant); } public CilInstruction Insert(int index, CilOpCode code, double constant) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0013: 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) if ((int)((CilOpCode)(ref code)).OperandType != 7) { throw new InvalidCilInstructionException(code); } return InsertAndReturn(index, code, constant); } public CilInstruction Insert(int index, CilOpCode code, string constant) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000b: 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 ((int)((CilOpCode)(ref code)).OperandType != 10) { throw new InvalidCilInstructionException(code); } if (constant == null) { throw new ArgumentNullException("constant"); } return InsertAndReturn(index, code, constant); } public CilInstruction Insert(int index, CilOpCode code, CilLocalVariable variable) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_002d: 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) if ((int)((CilOpCode)(ref code)).OperandType != 14 && (int)((CilOpCode)(ref code)).OperandType != 18) { throw new InvalidCilInstructionException(code); } if (variable == null) { throw new ArgumentNullException("variable"); } return InsertAndReturn(index, code, variable); } public CilInstruction Insert(int index, CilOpCode code, Parameter parameter) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_002d: 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) if ((int)((CilOpCode)(ref code)).OperandType != 19 && (int)((CilOpCode)(ref code)).OperandType != 20) { throw new InvalidCilInstructionException(code); } if (parameter == null) { throw new ArgumentNullException("parameter"); } return InsertAndReturn(index, code, parameter); } public CilInstruction Insert(int index, CilOpCode code, IFieldDescriptor field) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_002c: 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) if ((int)((CilOpCode)(ref code)).OperandType != 1 && (int)((CilOpCode)(ref code)).OperandType != 12) { throw new InvalidCilInstructionException(code); } if (field == null) { throw new ArgumentNullException("field"); } return InsertAndReturn(index, code, field); } public CilInstruction Insert(int index, CilOpCode code, IMethodDescriptor method) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_002c: 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) if ((int)((CilOpCode)(ref code)).OperandType != 4 && (int)((CilOpCode)(ref code)).OperandType != 12) { throw new InvalidCilInstructionException(code); } if (method == null) { throw new ArgumentNullException("method"); } return InsertAndReturn(index, code, method); } public CilInstruction Insert(int index, CilOpCode code, MemberReference member) { //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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0037: Unknown result type (might be due to invalid IL or missing references) if (member == null) { throw new ArgumentNullException("member"); } CilOperandType operandType = ((CilOpCode)(ref code)).OperandType; if ((int)operandType != 1) { if ((int)operandType != 4) { if ((int)operandType != 12) { goto IL_0037; } } else if (!member.IsMethod) { goto IL_0037; } } else if (!member.IsField) { goto IL_0037; } return InsertAndReturn(index, code, member); IL_0037: throw new InvalidCilInstructionException(code); } public CilInstruction Insert(int index, CilOpCode code, ITypeDefOrRef type) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_002d: 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) if ((int)((CilOpCode)(ref code)).OperandType != 13 && (int)((CilOpCode)(ref code)).OperandType != 12) { throw new InvalidCilInstructionException(code); } if (type == null) { throw new ArgumentNullException("type"); } return InsertAndReturn(index, code, type); } public CilInstruction Insert(int index, CilOpCode code, IMetadataMember member) { //IL_0002: 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_000a: Invalid comparison between Unknown and I4 //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0039: 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) CilOperandType operandType = ((CilOpCode)(ref code)).OperandType; if ((int)operandType <= 4) { if ((int)operandType != 1 && (int)operandType != 4) { goto IL_0022; } } else if ((int)operandType != 9 && operandType - 12 > 1) { goto IL_0022; } if (member == null) { throw new ArgumentNullException("member"); } return InsertAndReturn(index, code, member); IL_0022: throw new InvalidCilInstructionException(code); } public CilInstruction Insert(int index, CilOpCode code, StandAloneSignature signature) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_0014: 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) if ((int)((CilOpCode)(ref code)).OperandType != 9) { throw new InvalidCilInstructionException(code); } return InsertAndReturn(index, code, signature); } public CilInstruction Insert(int index, CilOpCode code, MetadataToken token) { //IL_0002: 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_000a: Invalid comparison between Unknown and I4 //IL_0016: 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: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //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_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_001d: 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_0022: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Invalid comparison between Unknown and I4 //IL_0038: 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_0058: Expected I4, but got Unknown //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Invalid comparison between Unknown and I4 //IL_0073: 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_005b: Invalid comparison between Unknown and I4 //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Invalid comparison between Unknown and I4 //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Invalid comparison between Unknown and I4 CilOperandType operandType = ((CilOpCode)(ref code)).OperandType; if ((int)operandType <= 4) { if ((int)operandType != 1 && (int)operandType != 4) { goto IL_0024; } } else if (operandType - 9 > 1 && operandType - 12 > 1) { goto IL_0024; } TableIndex table = ((MetadataToken)(ref token)).Table; if ((int)table <= 17) { switch (table - 1) { default: if ((int)table != 10 && (int)table != 17) { break; } goto IL_007a; case 2: case 4: break; case 0: case 1: case 3: case 5: goto IL_007a; } } else if ((int)table == 27 || (int)table == 43 || (int)table == 112) { goto IL_007a; } throw new InvalidCilInstructionException(code); IL_007a: return InsertAndReturn(index, code, token); IL_0024: throw new InvalidCilInstructionException(code); } } public static class CilInstructionExtensions { public static int GetStackPopCount(this CilInstruction instruction, CilMethodBody? parent) { return instruction.GetStackPopCount(parent == null || !(parent.Owner.Signature?.ReturnsValue ?? true)); } public static int GetStackPopCount(this CilInstruction instruction, bool isVoid) { //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_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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected I4, but got Unknown CilOpCode opCode = instruction.OpCode; CilStackBehaviour stackBehaviourPop = ((CilOpCode)(ref opCode)).StackBehaviourPop; switch ((int)stackBehaviourPop) { case 0: return 0; case 1: case 3: case 10: return 1; case 2: case 4: case 5: case 6: case 8: case 9: case 11: case 12: return 2; case 7: case 13: case 14: case 15: case 16: case 17: case 18: return 3; case 28: return DetermineVarPopCount(instruction, isVoid); case 19: return -1; default: throw new ArgumentOutOfRangeException(); } } private static int DetermineVarPopCount(CilInstruction instruction, bool isVoid) { //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_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) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Invalid comparison between Unknown and I4 //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Invalid comparison between Unknown and I4 //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Invalid comparison between Unknown and I4 CilOpCode opCode = instruction.OpCode; object operand = instruction.Operand; MethodSignature methodSignature = ((operand is IMethodDescriptor methodDescriptor) ? methodDescriptor.Signature : ((!(operand is StandAloneSignature standAloneSignature)) ? null : (standAloneSignature.Signature as MethodSignature))); MethodSignature methodSignature2 = methodSignature; if (methodSignature2 == null) { if ((int)((CilOpCode)(ref opCode)).Code == 42) { if (!isVoid) { return 1; } return 0; } return 0; } int num = methodSignature2.GetTotalParameterCount(); CilCode code = ((CilOpCode)(ref opCode)).Code; if ((int)code != 41) { if ((int)code == 115) { num--; } } else { num++; } return num; } public static int GetStackPushCount(this CilInstruction instruction) { //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_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_000f: 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_0040: Expected I4, but got Unknown CilOpCode opCode = instruction.OpCode; CilStackBehaviour stackBehaviourPush = ((CilOpCode)(ref opCode)).StackBehaviourPush; switch (stackBehaviourPush - 20) { case 0: return 0; case 1: case 3: case 4: case 5: case 6: case 7: return 1; case 2: return 2; case 9: return DetermineVarPushCount(instruction); default: throw new ArgumentOutOfRangeException(); } } private static int DetermineVarPushCount(CilInstruction instruction) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Invalid comparison between Unknown and I4 object operand = instruction.Operand; MethodSignature methodSignature = ((operand is IMethodDescriptor methodDescriptor) ? methodDescriptor.Signature : ((!(operand is StandAloneSignature standAloneSignature)) ? null : (standAloneSignature.Signature as MethodSignature))); MethodSignature methodSignature2 = methodSignature; if (methodSignature2 == null) { return 0; } if (!methodSignature2.ReturnsValue) { CilOpCode opCode = instruction.OpCode; if ((int)((CilOpCode)(ref opCode)).Code != 115) { return 0; } } return 1; } public static CilLocalVariable GetLocalVariable(this CilInstruction instruction, IReadOnlyList variables) { //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_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_000f: 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_004f: Expected I4, but got Unknown //IL_004f: 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_0057: Invalid comparison between Unknown and I4 CilOpCode opCode = instruction.OpCode; CilCode code = ((CilOpCode)(ref opCode)).Code; switch (code - 6) { default: if (code - 65036 > 2) { break; } goto case 11; case 11: case 12: case 13: return (CilLocalVariable)instruction.Operand; case 0: case 4: return variables[0]; case 1: case 5: return variables[1]; case 2: case 6: return variables[2]; case 3: case 7: return variables[3]; case 8: case 9: case 10: break; } throw new ArgumentException("Instruction is not a ldloc or stloc instruction."); } public static Parameter GetParameter(this CilInstruction instruction, ParameterCollection parameters) { //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_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_000f: 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_0027: Expected I4, but got Unknown //IL_0027: 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_002c: Invalid comparison between Unknown and I4 //IL_002e: 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_0036: Invalid comparison between Unknown and I4 CilOpCode opCode = instruction.OpCode; CilCode code = ((CilOpCode)(ref opCode)).Code; switch (code - 2) { default: if (code - 14 <= 2 || code - 65033 <= 2) { return (Parameter)instruction.Operand; } throw new ArgumentException("Instruction is not a ldarg or starg instruction."); case 0: return parameters.GetBySignatureIndex(0); case 1: return parameters.GetBySignatureIndex(1); case 2: return parameters.GetBySignatureIndex(2); case 3: return parameters.GetBySignatureIndex(3); } } } internal struct CilLabelVerifier { private readonly CilMethodBody _body; private List? _diagnostics; private string? _cachedName; public CilLabelVerifier(CilMethodBody body) { _body = body ?? throw new ArgumentNullException("body"); _diagnostics = null; _cachedName = null; } public void Verify() { VerifyInstructions(); VerifyExceptionHandlers(); if (_diagnostics != null) { switch (_diagnostics.Count) { case 1: throw _diagnostics[0]; default: throw new AggregateException("Method body of " + _cachedName + " contains multiple invalid labels.", _diagnostics); case 0: break; } } } private void VerifyInstructions() { //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_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_002e: 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_0034: Invalid comparison between Unknown and I4 //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 foreach (CilInstruction instruction in _body.Instructions) { CilOpCode opCode = instruction.OpCode; CilOperandType operandType = ((CilOpCode)(ref opCode)).OperandType; if ((int)operandType != 0) { if ((int)operandType == 11) { if (!(instruction.Operand is IList list)) { AddDiagnostic($"Switch table of IL_{instruction.Offset:X4} is null."); } else { for (int i = 0; i < list.Count; i++) { VerifyBranchLabel(instruction.Offset, list[i]); } } continue; } if ((int)operandType != 15) { continue; } } int offset = instruction.Offset; object operand = instruction.Operand; VerifyBranchLabel(offset, (ICilLabel?)((operand is ICilLabel) ? operand : null)); } } private void VerifyExceptionHandlers() { for (int i = 0; i < _body.ExceptionHandlers.Count; i++) { CilExceptionHandler cilExceptionHandler = _body.ExceptionHandlers[i]; VerifyHandlerLabel(i, "Try Start", cilExceptionHandler.TryStart); VerifyHandlerLabel(i, "Try End", cilExceptionHandler.TryEnd); VerifyHandlerLabel(i, "Handler Start", cilExceptionHandler.HandlerStart); VerifyHandlerLabel(i, "Handler End", cilExceptionHandler.HandlerEnd); if (cilExceptionHandler.HandlerType == CilExceptionHandlerType.Filter) { VerifyHandlerLabel(i, "Filter Start", cilExceptionHandler.FilterStart); } } } private void VerifyBranchLabel(int offset, ICilLabel? label) { if (label != null) { CilInstructionLabel val = (CilInstructionLabel)(object)((label is CilInstructionLabel) ? label : null); if (val != null) { CilInstruction instruction = val.Instruction; if (instruction != null) { if (!IsPresentInBody(instruction)) { AddDiagnostic($"IL_{offset:X4} references an instruction that is not present in the method body."); } return; } } if (!IsPresentInBody(label.Offset)) { AddDiagnostic($"IL_{offset:X4} references an offset that is not present in the method body."); } } else { AddDiagnostic($"Branch target of IL_{offset:X4} is null."); } } private void VerifyHandlerLabel(int handlerIndex, string labelName, ICilLabel? label) { if (label != null) { CilInstructionLabel val = (CilInstructionLabel)(object)((label is CilInstructionLabel) ? label : null); if (val != null) { CilInstruction instruction = val.Instruction; if (instruction != null) { if (!IsPresentInBody(instruction)) { AddDiagnostic(labelName + " of exception handler " + handlerIndex + " references an instruction that is not present in the method body."); } return; } } if (!IsPresentInBody(label.Offset)) { AddDiagnostic(labelName + " of exception handler " + handlerIndex + " references an offset that is not present in the method body."); } } else { AddDiagnostic(labelName + " of exception handler " + handlerIndex + " is null."); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsPresentInBody(CilInstruction instruction) { return CilInstructionCollectionExtensions.GetByOffset((IList)_body.Instructions, instruction.Offset) == instruction; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsPresentInBody(int offset) { if (CilInstructionCollectionExtensions.GetIndexByOffset((IList)_body.Instructions, offset) < 0) { return _body.Instructions.EndLabel.Offset == offset; } return true; } private void AddDiagnostic(string message) { if (_diagnostics == null) { _diagnostics = new List(); } if (_cachedName == null) { _cachedName = _body.Owner.SafeToString(); } _diagnostics.Add(new InvalidCilInstructionException("[In " + _cachedName + "]: " + message)); } } public class CilLocalVariable { public int Index { get; internal set; } = -1; public TypeSignature VariableType { get; set; } public CilLocalVariable(TypeSignature variableType) { VariableType = variableType; } public override string ToString() { return "V_" + Index; } } [DebuggerDisplay("Count = {Count}")] public class CilLocalVariableCollection : Collection { private static void AssertHasNoOwner(CilLocalVariable item) { if (item.Index != -1) { throw new ArgumentException("Variable is already added to another list of variables."); } } protected override void ClearItems() { lock (base.Items) { foreach (CilLocalVariable item in base.Items) { item.Index = -1; } base.ClearItems(); } } protected override void InsertItem(int index, CilLocalVariable item) { lock (base.Items) { AssertHasNoOwner(item); for (int i = index; i < base.Count; i++) { base.Items[i].Index++; } item.Index = index; base.InsertItem(index, item); } } protected override void RemoveItem(int index) { lock (base.Items) { for (int i = index; i < base.Count; i++) { base.Items[i].Index--; } base.Items[index].Index = -1; base.RemoveItem(index); } } protected override void SetItem(int index, CilLocalVariable item) { lock (base.Items) { AssertHasNoOwner(item); base.Items[index].Index = -1; base.SetItem(index, item); item.Index = index; } } } internal readonly ref struct CilMaxStackCalculator { private readonly struct StackState { public readonly int InstructionIndex; public readonly int StackSize; public StackState(int instructionIndex, int stackSize) { InstructionIndex = instructionIndex; StackSize = stackSize; } } private readonly CilMethodBody _body; private readonly Stack _agenda; private readonly int?[] _recordedStackSizes; public CilMaxStackCalculator(CilMethodBody body) { _body = body ?? throw new ArgumentNullException("body"); if (_body.Instructions.Count > 0) { _agenda = new Stack(); _recordedStackSizes = new int?[_body.Instructions.Count]; } else { _agenda = null; _recordedStackSizes = null; } } public int Compute() { if (_body.Instructions.Count == 0) { return 0; } int num = 0; ScheduleEntryPoints(); while (_agenda.Count > 0) { StackState currentState = _agenda.Pop(); if (currentState.InstructionIndex >= _body.Instructions.Count) { CilInstruction val = _body.Instructions[_body.Instructions.Count - 1]; throw new StackImbalanceException(_body, val.Offset + val.Size); } int? num2 = _recordedStackSizes[currentState.InstructionIndex]; if (num2.HasValue) { if (num2.Value != currentState.StackSize) { throw new StackImbalanceException(_body, _body.Instructions[currentState.InstructionIndex].Offset); } } else { _recordedStackSizes[currentState.InstructionIndex] = currentState.StackSize; ScheduleSuccessors(in currentState); } if (currentState.StackSize > num) { num = currentState.StackSize; } } return num; } private void ScheduleEntryPoints() { _agenda.Push(new StackState(0, 0)); CilInstructionCollection instructions = _body.Instructions; for (int i = 0; i < _body.ExceptionHandlers.Count; i++) { CilExceptionHandler cilExceptionHandler = _body.ExceptionHandlers[i]; int stackSize = cilExceptionHandler.HandlerType switch { CilExceptionHandlerType.Exception => 1, CilExceptionHandlerType.Filter => 1, CilExceptionHandlerType.Finally => 0, CilExceptionHandlerType.Fault => 0, _ => throw new ArgumentOutOfRangeException("HandlerType"), }; ICilLabel tryStart = cilExceptionHandler.TryStart; if (tryStart != null) { int offset = tryStart.Offset; _agenda.Push(new StackState(CilInstructionCollectionExtensions.GetIndexByOffset((IList)instructions, offset), 0)); } tryStart = cilExceptionHandler.HandlerStart; if (tryStart != null) { int offset2 = tryStart.Offset; _agenda.Push(new StackState(CilInstructionCollectionExtensions.GetIndexByOffset((IList)instructions, offset2), stackSize)); } tryStart = cilExceptionHandler.FilterStart; if (tryStart != null) { int offset3 = tryStart.Offset; _agenda.Push(new StackState(CilInstructionCollectionExtensions.GetIndexByOffset((IList)instructions, offset3), 1)); } } } private void ScheduleSuccessors(in StackState currentState) { //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_0063: Invalid comparison between Unknown and I4 //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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_00b8: Expected I4, 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_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Invalid comparison between Unknown and I4 //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Expected O, but got Unknown CilInstruction val = _body.Instructions[currentState.InstructionIndex]; int stackPopCount = val.GetStackPopCount(_body); int num = ((stackPopCount != -1) ? (currentState.StackSize - stackPopCount) : 0); if (num < 0) { throw new StackImbalanceException(_body, val.Offset); } num += val.GetStackPushCount(); CilOpCode opCode = val.OpCode; if ((int)((CilOpCode)(ref opCode)).Code == 39) { if (num != 0) { throw new StackImbalanceException(_body, val.Offset); } return; } opCode = val.OpCode; CilFlowControl flowControl = ((CilOpCode)(ref opCode)).FlowControl; switch ((int)flowControl) { case 0: { object operand = val.Operand; if (!(operand is sbyte offsetDelta)) { if (!(operand is int offsetDelta2)) { ICilLabel val2 = (ICilLabel)((operand is ICilLabel) ? operand : null); if (val2 == null) { throw new NotSupportedException($"Invalid or unsupported operand type at offset IL_{val.Offset:X4}."); } ScheduleLabel(currentState.InstructionIndex, val2, num); } else { ScheduleDelta(currentState.InstructionIndex, offsetDelta2, num); } } else { ScheduleDelta(currentState.InstructionIndex, offsetDelta, num); } break; } case 3: opCode = val.OpCode; if ((int)((CilOpCode)(ref opCode)).Code == 69) { IList list = (IList)val.Operand; for (int i = 0; i < list.Count; i++) { ScheduleLabel(currentState.InstructionIndex, list[i], num); } ScheduleNext(currentState.InstructionIndex, num); } else { ScheduleLabel(currentState.InstructionIndex, (ICilLabel)val.Operand, num); ScheduleNext(currentState.InstructionIndex, num); } break; case 1: case 2: case 4: case 5: case 6: ScheduleNext(currentState.InstructionIndex, num); break; case 7: if (num != 0) { throw new StackImbalanceException(_body, val.Offset); } break; default: throw new NotSupportedException($"Invalid or unsupported operand type at offset IL_{val.Offset:X4}."); case 8: break; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ScheduleLabel(int currentIndex, ICilLabel label, int nextStackSize) { int indexByOffset = CilInstructionCollectionExtensions.GetIndexByOffset((IList)_body.Instructions, label.Offset); ScheduleIndex(currentIndex, indexByOffset, label.Offset, nextStackSize); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ScheduleDelta(int currentIndex, int offsetDelta, int nextStackSize) { int num = _body.Instructions[currentIndex].Offset + offsetDelta; int indexByOffset = CilInstructionCollectionExtensions.GetIndexByOffset((IList)_body.Instructions, num); ScheduleIndex(currentIndex, indexByOffset, num, nextStackSize); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ScheduleNext(int currentIndex, int nextStackSize) { CilInstruction val = _body.Instructions[currentIndex]; ScheduleIndex(currentIndex, currentIndex + 1, val.Offset + val.Size, nextStackSize); } private void ScheduleIndex(int currentIndex, int nextIndex, int nextOffset, int nextStackSize) { if (nextIndex < 0 && nextIndex >= _body.Instructions.Count) { CilInstruction val = _body.Instructions[currentIndex]; throw new InvalidProgramException($"Instruction at offset IL_{val.Offset:X4} transfers control to a non-existing offset IL_{nextOffset:X4}."); } _agenda.Push(new StackState(nextIndex, nextStackSize)); } } public class CilMethodBody : MethodBody { public CilInstructionCollection Instructions { get; } public int MaxStack { get; set; } public bool InitializeLocals { get; set; } public bool IsFat { get { if (ExceptionHandlers.Count > 0 || LocalVariables.Count > 0 || MaxStack > 8) { return true; } if (Instructions.Count == 0) { return false; } CilInstruction val = Instructions[Instructions.Count - 1]; return val.Offset + val.Size >= 64; } } public CilLocalVariableCollection LocalVariables { get; } = new CilLocalVariableCollection(); public IList ExceptionHandlers { get; } = new List(); public CilMethodBodyBuildFlags BuildFlags { get; set; } = CilMethodBodyBuildFlags.FullValidation; public bool ComputeMaxStackOnBuild { get { return (BuildFlags & CilMethodBodyBuildFlags.ComputeMaxStack) == CilMethodBodyBuildFlags.ComputeMaxStack; } set { BuildFlags = (BuildFlags & ~CilMethodBodyBuildFlags.ComputeMaxStack) | (value ? CilMethodBodyBuildFlags.ComputeMaxStack : ((CilMethodBodyBuildFlags)0)); } } public bool VerifyLabelsOnBuild { get { return (BuildFlags & CilMethodBodyBuildFlags.VerifyLabels) == CilMethodBodyBuildFlags.VerifyLabels; } set { BuildFlags = (BuildFlags & ~CilMethodBodyBuildFlags.VerifyLabels) | (value ? CilMethodBodyBuildFlags.VerifyLabels : ((CilMethodBodyBuildFlags)0)); } } public CilMethodBody(MethodDefinition owner) : base(owner) { Instructions = new CilInstructionCollection(this); } public static CilMethodBody FromRawMethodBody(ModuleReaderContext context, MethodDefinition method, CilRawMethodBody rawBody, ICilOperandResolver? operandResolver = null) { CilMethodBody cilMethodBody = new CilMethodBody(method); CilRawFatMethodBody val = (CilRawFatMethodBody)(object)((rawBody is CilRawFatMethodBody) ? rawBody : null); if (val != null) { cilMethodBody.MaxStack = val.MaxStack; cilMethodBody.InitializeLocals = val.InitLocals; ReadLocalVariables(context, cilMethodBody, val); } else { cilMethodBody.MaxStack = 8; cilMethodBody.InitializeLocals = false; } if (operandResolver == null) { operandResolver = (ICilOperandResolver?)(object)new PhysicalCilOperandResolver(context.ParentModule, cilMethodBody); } ReadInstructions(context, cilMethodBody, operandResolver, rawBody); if (val != null) { ReadExceptionHandlers(context, val, cilMethodBody); } return cilMethodBody; } private static void ReadLocalVariables(ModuleReaderContext context, CilMethodBody result, CilRawFatMethodBody fatBody) { //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_001a: Unknown result type (might be due to invalid IL or missing references) if (fatBody.LocalVarSigToken == MetadataToken.Zero) { return; } if (!context.ParentModule.TryLookupMember(fatBody.LocalVarSigToken, out IMetadataMember member) || !(member is StandAloneSignature standAloneSignature) || !(standAloneSignature.Signature is LocalVariablesSignature localVariablesSignature)) { ErrorListenerExtensions.BadImage((IErrorListener)(object)context, "Method body of " + result.Owner.SafeToString() + " contains an invalid local variable signature token."); return; } IList variableTypes = localVariablesSignature.VariableTypes; for (int i = 0; i < variableTypes.Count; i++) { result.LocalVariables.Add(new CilLocalVariable(variableTypes[i])); } } private static void ReadInstructions(ModuleReaderContext context, CilMethodBody result, ICilOperandResolver operandResolver, CilRawMethodBody rawBody) { //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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown try { BinaryStreamReader val = Extensions.CreateReader(rawBody.Code); CilDisassembler val2 = new CilDisassembler(ref val, operandResolver); result.Instructions.AddRange(val2.ReadInstructions()); } catch (Exception inner) { context.RegisterException(new BadImageFormatException("Method body of " + result.Owner.SafeToString() + " contains an invalid CIL code stream.", inner)); } } private static void ReadExceptionHandlers(ModuleReaderContext context, CilRawFatMethodBody fatBody, CilMethodBody result) { try { BinaryStreamReader reader = default(BinaryStreamReader); for (int i = 0; i < fatBody.ExtraSections.Count; i++) { CilExtraSection val = fatBody.ExtraSections[i]; if (val.IsEHTable) { ((BinaryStreamReader)(ref reader))..ctor(val.Data); uint num = (val.IsFat ? 24u : 12u); while (((BinaryStreamReader)(ref reader)).CanRead(num)) { CilExceptionHandler item = CilExceptionHandler.FromReader(result, ref reader, val.IsFat); result.ExceptionHandlers.Add(item); } } } } catch (Exception inner) { context.RegisterException(new BadImageFormatException("Method body of " + result.Owner.SafeToString() + " contains invalid extra sections.", inner)); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void VerifyLabels() { VerifyLabels(calculateOffsets: true); } public void VerifyLabels(bool calculateOffsets) { if (calculateOffsets) { Instructions.CalculateOffsets(); } new CilLabelVerifier(this).Verify(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int ComputeMaxStack() { return ComputeMaxStack(calculateOffsets: true); } public int ComputeMaxStack(bool calculateOffsets) { if (calculateOffsets) { Instructions.CalculateOffsets(); } return new CilMaxStackCalculator(this).Compute(); } } [Flags] public enum CilMethodBodyBuildFlags { VerifyLabels = 1, ComputeMaxStack = 2, FullValidation = 3 } public class CilMethodBodySerializer : IMethodBodySerializer { private readonly MemoryStreamWriterPool _writerPool = new MemoryStreamWriterPool(); public bool? ComputeMaxStackOnBuildOverride { get; set; } public bool? VerifyLabelsOnBuildOverride { get; set; } public ISegmentReference SerializeMethodBody(MethodBodySerializationContext context, MethodDefinition method) { if (method.CilMethodBody == null) { return SegmentReference.Null; } CilMethodBody cilMethodBody = method.CilMethodBody; cilMethodBody.Instructions.CalculateOffsets(); try { if (ComputeMaxStackOnBuildOverride ?? cilMethodBody.ComputeMaxStackOnBuild) { cilMethodBody.VerifyLabels(calculateOffsets: false); cilMethodBody.MaxStack = cilMethodBody.ComputeMaxStack(calculateOffsets: false); } else if (VerifyLabelsOnBuildOverride ?? cilMethodBody.VerifyLabelsOnBuild) { cilMethodBody.VerifyLabels(calculateOffsets: false); } } catch (Exception ex) { context.ErrorListener.RegisterException(ex); } byte[] code = BuildRawCodeStream(context, cilMethodBody); return Extensions.ToReference((ISegment)(object)(cilMethodBody.IsFat ? BuildFatMethodBody(context, cilMethodBody, code) : BuildTinyMethodBody(code))); } private static CilRawMethodBody BuildTinyMethodBody(byte[] code) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return (CilRawMethodBody)new CilRawTinyMethodBody(code); } private CilRawMethodBody BuildFatMethodBody(MethodBodySerializationContext context, CilMethodBody body, byte[] code) { //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_006e: 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_007a: Expected O, but got Unknown //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_0060: 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_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Expected O, but got Unknown //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) MetadataToken val; if (body.LocalVariables.Count == 0) { val = MetadataToken.Zero; } else { LocalVariablesSignature localVariablesSignature = new LocalVariablesSignature(); for (int i = 0; i < body.LocalVariables.Count; i++) { localVariablesSignature.VariableTypes.Add(body.LocalVariables[i].VariableType); } StandAloneSignature signature = new StandAloneSignature(localVariablesSignature); val = context.TokenProvider.GetStandAloneSignatureToken(signature); } CilRawFatMethodBody val2 = new CilRawFatMethodBody((CilMethodBodyAttributes)3, (ushort)body.MaxStack, val, (IReadableSegment)new DataSegment(code)); val2.InitLocals = body.InitializeLocals; if (body.ExceptionHandlers.Count > 0) { val2.HasSections = true; bool flag = body.ExceptionHandlers.Any((CilExceptionHandler e) => e.IsFat); CilExtraSectionAttributes val3 = (CilExtraSectionAttributes)1; if (flag) { val3 = (CilExtraSectionAttributes)(val3 | 0x40); } byte[] array = SerializeExceptionHandlers(context, body.ExceptionHandlers, flag); CilExtraSection item = new CilExtraSection(val3, array); val2.ExtraSections.Add(item); } return (CilRawMethodBody)(object)val2; } private byte[] BuildRawCodeStream(MethodBodySerializationContext context, CilMethodBody body) { //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_0038: Unknown result type (might be due to invalid IL or missing references) IErrorListener errorListener = context.ErrorListener; RentedWriter val = _writerPool.Rent(); try { new CilAssembler((IBinaryStreamWriter)(object)((RentedWriter)(ref val)).Writer, (ICilOperandBuilder)(object)new CilOperandBuilder(context.TokenProvider, errorListener), (Func)body.Owner.SafeToString, errorListener).WriteInstructions((IList)body.Instructions); return ((RentedWriter)(ref val)).GetData(); } finally { ((RentedWriter)(ref val)).Dispose(); } } private byte[] SerializeExceptionHandlers(MethodBodySerializationContext context, IList exceptionHandlers, bool needsFatFormat) { //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) RentedWriter val = _writerPool.Rent(); try { for (int i = 0; i < exceptionHandlers.Count; i++) { CilExceptionHandler handler = exceptionHandlers[i]; WriteExceptionHandler(context, (IBinaryStreamWriter)(object)((RentedWriter)(ref val)).Writer, handler, needsFatFormat); } return ((RentedWriter)(ref val)).GetData(); } finally { ((RentedWriter)(ref val)).Dispose(); } } private void WriteExceptionHandler(MethodBodySerializationContext context, IBinaryStreamWriter writer, CilExceptionHandler handler, bool useFatFormat) { //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_017a: 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_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014a: 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_0178: Unknown result type (might be due to invalid IL or missing references) if (handler.IsFat && !useFatFormat) { throw new InvalidOperationException("Can only serialize fat exception handlers in fat format."); } ICilLabel? tryStart = handler.TryStart; uint num = ((tryStart != null) ? ((uint)tryStart.Offset) : 0u); ICilLabel? tryEnd = handler.TryEnd; uint num2 = ((tryEnd != null) ? ((uint)tryEnd.Offset) : 0u); ICilLabel? handlerStart = handler.HandlerStart; uint num3 = ((handlerStart != null) ? ((uint)handlerStart.Offset) : 0u); ICilLabel? handlerEnd = handler.HandlerEnd; uint num4 = ((handlerEnd != null) ? ((uint)handlerEnd.Offset) : 0u); if (useFatFormat) { writer.WriteUInt32((uint)handler.HandlerType); writer.WriteUInt32(num); writer.WriteUInt32(num2 - num); writer.WriteUInt32(num3); writer.WriteUInt32(num4 - num3); } else { writer.WriteUInt16((ushort)handler.HandlerType); writer.WriteUInt16((ushort)num); writer.WriteByte((byte)(num2 - num)); writer.WriteUInt16((ushort)num3); writer.WriteByte((byte)(num4 - num3)); } switch (handler.HandlerType) { case CilExceptionHandlerType.Exception: { IMetadataTokenProvider tokenProvider = context.TokenProvider; ITypeDefOrRef exceptionType = handler.ExceptionType; MetadataToken val = ((exceptionType is TypeReference type) ? tokenProvider.GetTypeReferenceToken(type) : ((exceptionType is TypeDefinition type2) ? tokenProvider.GetTypeDefinitionToken(type2) : ((!(exceptionType is TypeSpecification type3)) ? ErrorListenerExtensions.RegisterExceptionAndReturnDefault(context.ErrorListener, (Exception)new ArgumentOutOfRangeException("Invalid or unsupported exception type (" + handler.ExceptionType.SafeToString() + ")")) : tokenProvider.GetTypeSpecificationToken(type3)))); MetadataToken val2 = val; writer.WriteUInt32(((MetadataToken)(ref val2)).ToUInt32()); break; } case CilExceptionHandlerType.Filter: { ICilLabel? filterStart = handler.FilterStart; writer.WriteUInt32((filterStart != null) ? ((uint)filterStart.Offset) : 0u); break; } case CilExceptionHandlerType.Finally: case CilExceptionHandlerType.Fault: writer.WriteUInt32(0u); break; default: context.ErrorListener.RegisterException((Exception)new ArgumentOutOfRangeException("Invalid or unsupported handler type (" + handler.HandlerType.SafeToString())); break; } } } public class CilOperandBuilder : ICilOperandBuilder { private readonly IMetadataTokenProvider _provider; private readonly IErrorListener _errorListener; public CilOperandBuilder(IMetadataTokenProvider provider, IErrorListener errorListener) { _provider = provider ?? throw new ArgumentNullException("provider"); _errorListener = errorListener ?? throw new ArgumentNullException("errorListener"); } public int GetVariableIndex(object? operand) { if (!(operand is CilLocalVariable cilLocalVariable)) { if (!(operand is byte result)) { if (operand is ushort result2) { return result2; } return ErrorListenerExtensions.NotSupportedAndReturn(_errorListener, "Invalid or unsupported variable operand (" + operand.SafeToString() + ")."); } return result; } return cilLocalVariable.Index; } public int GetArgumentIndex(object? operand) { if (!(operand is Parameter parameter)) { if (!(operand is byte result)) { if (operand is ushort result2) { return result2; } return ErrorListenerExtensions.NotSupportedAndReturn(_errorListener, "Invalid or unsupported argument operand (" + operand.SafeToString() + ")."); } return result; } return parameter.MethodSignatureIndex; } public uint GetStringToken(object? operand) { //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 (!(operand is string value)) { if (!(operand is MetadataToken val)) { if (operand is uint result) { return result; } return ErrorListenerExtensions.NotSupportedAndReturn(_errorListener, "Invalid or unsupported string operand (" + operand.SafeToString() + ")."); } return ((MetadataToken)(ref val)).ToUInt32(); } return 0x70000000u | _provider.GetUserStringIndex(value); } public MetadataToken GetMemberToken(object? operand) { //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_0069: Unknown result type (might be due to invalid IL or missing references) //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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0036: 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_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) if (!(operand is IMetadataMember member)) { if (!(operand is MetadataToken result)) { if (operand is uint num) { return MetadataToken.op_Implicit(num); } return MetadataToken.op_Implicit(ErrorListenerExtensions.NotSupportedAndReturn(_errorListener, "Invalid or unsupported member operand (" + operand.SafeToString() + ").")); } return result; } return GetMemberToken(member); } private MetadataToken GetMemberToken(IMetadataMember member) { //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_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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Invalid comparison between Unknown and I4 //IL_0014: 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_0034: Expected I4, but got Unknown //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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Invalid comparison between Unknown and I4 //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: 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_00a6: 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_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: 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_0037: Invalid comparison between Unknown and I4 //IL_0109: 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) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Invalid comparison between Unknown and I4 //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: 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_00d3: Unknown result type (might be due to invalid IL or missing references) MetadataToken metadataToken = member.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; if ((int)table <= 10) { switch (table - 1) { default: if ((int)table != 10) { break; } return _provider.GetMemberReferenceToken((MemberReference)member); case 0: return _provider.GetTypeReferenceToken((TypeReference)member); case 1: return _provider.GetTypeDefinitionToken((TypeDefinition)member); case 3: return _provider.GetFieldDefinitionToken((FieldDefinition)member); case 5: return _provider.GetMethodDefinitionToken((MethodDefinition)member); case 2: case 4: break; } } else { if ((int)table == 17) { return _provider.GetStandAloneSignatureToken((StandAloneSignature)member); } if ((int)table == 27) { return _provider.GetTypeSpecificationToken((TypeSpecification)member); } if ((int)table == 43) { return _provider.GetMethodSpecificationToken((MethodSpecification)member); } } throw new ArgumentOutOfRangeException("member"); } } public interface IMetadataTokenProvider { MetadataToken GetTypeReferenceToken(TypeReference type); MetadataToken GetTypeDefinitionToken(TypeDefinition type); MetadataToken GetFieldDefinitionToken(FieldDefinition field); MetadataToken GetMethodDefinitionToken(MethodDefinition method); MetadataToken GetMemberReferenceToken(MemberReference member); MetadataToken GetStandAloneSignatureToken(StandAloneSignature signature); MetadataToken GetAssemblyReferenceToken(AssemblyReference assembly); MetadataToken GetTypeSpecificationToken(TypeSpecification type); MetadataToken GetMethodSpecificationToken(MethodSpecification method); uint GetUserStringIndex(string value); } [Serializable] public class InvalidCilInstructionException : Exception { public InvalidCilInstructionException() : base("Invalid combination of CIL operation code and operand in the instruction.") { } public InvalidCilInstructionException(CilOpCode code) : base(((int)((CilOpCode)(ref code)).OperandType == 5) ? ("Operation code " + ((CilOpCode)(ref code)).Mnemonic + " cannot have an operand.") : $"Operation code {((CilOpCode)(ref code)).Mnemonic} requires an {((CilOpCode)(ref code)).OperandType} operand.") { }//IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_003f: Unknown result type (might be due to invalid IL or missing references) public InvalidCilInstructionException(string message) : base(message) { } public InvalidCilInstructionException(string message, Exception inner) : base(message, inner) { } protected InvalidCilInstructionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class OriginalMetadataTokenProvider : IMetadataTokenProvider { private readonly ModuleDefinition? _module; public OriginalMetadataTokenProvider(ModuleDefinition? module) { _module = module; } private MetadataToken GetToken(IMetadataMember member) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (_module != null && member is IModuleProvider moduleProvider && moduleProvider.Module != _module) { throw new MemberNotImportedException(member); } return member.MetadataToken; } public MetadataToken GetTypeReferenceToken(TypeReference type) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetToken(type); } public MetadataToken GetTypeDefinitionToken(TypeDefinition type) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetToken(type); } public MetadataToken GetFieldDefinitionToken(FieldDefinition field) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetToken(field); } public MetadataToken GetMethodDefinitionToken(MethodDefinition method) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetToken(method); } public MetadataToken GetMemberReferenceToken(MemberReference member) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetToken(member); } public MetadataToken GetStandAloneSignatureToken(StandAloneSignature signature) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetToken(signature); } public MetadataToken GetAssemblyReferenceToken(AssemblyReference assembly) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetToken(assembly); } public MetadataToken GetTypeSpecificationToken(TypeSpecification type) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetToken(type); } public MetadataToken GetMethodSpecificationToken(MethodSpecification method) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetToken(method); } public uint GetUserStringIndex(string value) { ModuleDefinition? module = _module; bool? obj; UserStringsStream val = default(UserStringsStream); if (module == null) { obj = null; } else { IDotNetDirectory? dotNetDirectory = module.DotNetDirectory; if (dotNetDirectory == null) { obj = null; } else { IMetadata metadata = dotNetDirectory.Metadata; obj = ((metadata != null) ? new bool?(metadata.TryGetStream(ref val)) : null); } } bool? flag = obj; uint result = default(uint); if (flag.GetValueOrDefault() && val.TryFindStringIndex(value, ref result)) { return result; } return 0u; } } public class PhysicalCilOperandResolver : ICilOperandResolver { private readonly ModuleDefinition _contextModule; private readonly CilMethodBody _methodBody; public PhysicalCilOperandResolver(ModuleDefinition contextModule, CilMethodBody methodBody) { _contextModule = contextModule ?? throw new ArgumentNullException("contextModule"); _methodBody = methodBody ?? throw new ArgumentNullException("methodBody"); } public virtual object? ResolveMember(MetadataToken token) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) _contextModule.TryLookupMember(token, out IMetadataMember member); return member; } public virtual object? ResolveString(MetadataToken token) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) _contextModule.TryLookupString(token, out string value); return value; } public virtual object? ResolveLocalVariable(int index) { CilLocalVariableCollection localVariables = _methodBody.LocalVariables; if (index < 0 || index >= localVariables.Count) { return null; } return localVariables[index]; } public virtual object? ResolveParameter(int index) { ParameterCollection parameters = _methodBody.Owner.Parameters; if (!parameters.ContainsSignatureIndex(index)) { return null; } return parameters.GetBySignatureIndex(index); } } public class StackImbalanceException : Exception { public CilMethodBody Body { get; } public int Offset { get; } public StackImbalanceException(CilMethodBody body, int offset) : base($"Stack imbalance was detected at offset IL_{offset:X4} in method body of {body.Owner}") { Body = body; Offset = offset; } } } namespace AsmResolver.DotNet.Cloning { public class CallbackClonerListener : MemberClonerListener { private readonly Action _callback; public static CallbackClonerListener EmptyInstance { get; } = new CallbackClonerListener(delegate { }); public CallbackClonerListener(Action callback) { _callback = callback; } public override void OnClonedMember(IMemberDefinition original, IMemberDefinition cloned) { _callback(original, cloned); } } public class CloneContextAwareReferenceImporter : ReferenceImporter { private readonly MemberCloneContext _context; protected MemberCloneContext Context => _context; public CloneContextAwareReferenceImporter(MemberCloneContext context) : base(context.Module) { _context = context; } protected override ITypeDefOrRef ImportType(TypeDefinition type) { if (!_context.ClonedMembers.TryGetValue(type, out IMemberDescriptor value)) { return base.ImportType(type); } return (ITypeDefOrRef)value; } public override IFieldDescriptor ImportField(IFieldDescriptor field) { if (!_context.ClonedMembers.TryGetValue(field, out IMemberDescriptor value)) { return base.ImportField(field); } return (IFieldDescriptor)value; } public override IMethodDefOrRef ImportMethod(IMethodDefOrRef method) { if (!_context.ClonedMembers.TryGetValue(method, out IMemberDescriptor value)) { return base.ImportMethod(method); } return (IMethodDefOrRef)value; } protected override ITypeDefOrRef ImportType(TypeReference type) { if (!(type.Namespace == "System") || !(type.Name == "Object") || !(type.Scope?.GetAssembly()?.IsCorLib).GetValueOrDefault()) { return base.ImportType(type); } return _context.Module.CorLibTypeFactory.Object.Type; } } public class FieldRvaCloner : IFieldRvaCloner { public ISegment? CloneFieldRvaData(FieldDefinition field) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown ISegment fieldRva = field.FieldRva; if (fieldRva != null) { IReadableSegment val = (IReadableSegment)(object)((fieldRva is IReadableSegment) ? fieldRva : null); if (val == null) { if (fieldRva is ICloneable cloneable) { return (ISegment)cloneable.Clone(); } throw new ArgumentOutOfRangeException(); } return (ISegment?)new DataSegment(Extensions.ToArray(val)); } return null; } } public interface IFieldRvaCloner { ISegment? CloneFieldRvaData(FieldDefinition field); } public interface IMemberClonerListener { void OnClonedMember(IMemberDefinition original, IMemberDefinition cloned); void OnClonedType(TypeDefinition original, TypeDefinition cloned); void OnClonedMethod(MethodDefinition original, MethodDefinition cloned); void OnClonedField(FieldDefinition original, FieldDefinition cloned); void OnClonedProperty(PropertyDefinition original, PropertyDefinition cloned); void OnClonedEvent(EventDefinition original, EventDefinition cloned); } public class InjectTypeClonerListener : MemberClonerListener { public ModuleDefinition TargetModule { get; } public InjectTypeClonerListener(ModuleDefinition targetModule) { TargetModule = targetModule; } public override void OnClonedType(TypeDefinition original, TypeDefinition cloned) { if (!original.IsNested) { TargetModule.TopLevelTypes.Add(cloned); } base.OnClonedType(original, cloned); } } public class MemberCloneContext { public ModuleDefinition Module { get; } public CloneContextAwareReferenceImporter Importer { get; } public IDictionary ClonedMembers { get; } = new Dictionary(); public MemberCloneContext(ModuleDefinition module) : this(module, null) { } public MemberCloneContext(ModuleDefinition module, Func? importerFactory) { Module = module ?? throw new ArgumentNullException("module"); Importer = importerFactory?.Invoke(this) ?? new CloneContextAwareReferenceImporter(this); } } public class MemberCloner { private readonly IMemberClonerListener _clonerListener; private readonly Func? _importerFactory; private readonly ModuleDefinition _targetModule; private readonly HashSet _typesToClone = new HashSet(); private readonly HashSet _methodsToClone = new HashSet(); private readonly HashSet _fieldsToClone = new HashSet(); private readonly HashSet _propertiesToClone = new HashSet(); private readonly HashSet _eventsToClone = new HashSet(); public IFieldRvaCloner FieldRvaCloner { get; set; } = new FieldRvaCloner(); public MemberCloner(ModuleDefinition targetModule) : this(targetModule, delegate { }) { } public MemberCloner(ModuleDefinition targetModule, Func? importerFactory) : this(targetModule, importerFactory, null) { } public MemberCloner(ModuleDefinition targetModule, Action callback) : this(targetModule, new CallbackClonerListener(callback)) { } public MemberCloner(ModuleDefinition targetModule, IMemberClonerListener listener) : this(targetModule, null, listener) { } public MemberCloner(ModuleDefinition targetModule, Func? importerFactory, IMemberClonerListener? clonerListener) { _targetModule = targetModule ?? throw new ArgumentNullException("targetModule"); _importerFactory = importerFactory; _clonerListener = clonerListener ?? CallbackClonerListener.EmptyInstance; } public MemberCloner Include(IMemberDefinition member) { return Include(member, recursive: true); } public MemberCloner Include(IMemberDefinition member, bool recursive) { //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_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_000f: 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_002b: Expected I4, but got Unknown //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 MetadataToken metadataToken = member.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; switch (table - 2) { default: if ((int)table != 20) { if ((int)table != 23) { break; } return Include((PropertyDefinition)member); } return Include((EventDefinition)member); case 0: return Include((TypeDefinition)member, recursive); case 2: return Include((FieldDefinition)member); case 4: return Include((MethodDefinition)member); case 1: case 3: break; } throw new ArgumentOutOfRangeException(); } public MemberCloner Include(params IMemberDefinition[] members) { foreach (IMemberDefinition member in members) { Include(member); } return this; } public MemberCloner Include(IEnumerable members) { foreach (IMemberDefinition member in members) { Include(member); } return this; } public MemberCloner Include(TypeDefinition type) { return Include(type, recursive: true); } public MemberCloner Include(TypeDefinition type, bool recursive) { Stack stack = new Stack(); stack.Push(type); while (stack.Count > 0) { type = stack.Pop(); _typesToClone.Add(type); foreach (MethodDefinition method in type.Methods) { Include(method); } foreach (FieldDefinition field in type.Fields) { Include(field); } foreach (PropertyDefinition property in type.Properties) { Include(property); } foreach (EventDefinition @event in type.Events) { Include(@event); } if (!recursive) { continue; } foreach (TypeDefinition nestedType in type.NestedTypes) { stack.Push(nestedType); } } return this; } public MemberCloner Include(params TypeDefinition[] types) { return Include((IEnumerable)types); } public MemberCloner Include(IEnumerable types) { foreach (TypeDefinition type in types) { Include(type); } return this; } public MemberCloner Include(MethodDefinition method) { _methodsToClone.Add(method); return this; } public MemberCloner Include(FieldDefinition field) { _fieldsToClone.Add(field); return this; } public MemberCloner Include(PropertyDefinition property) { _propertiesToClone.Add(property); return this; } public MemberCloner Include(EventDefinition @event) { _eventsToClone.Add(@event); return this; } public MemberCloneResult Clone() { MemberCloneContext memberCloneContext = new MemberCloneContext(_targetModule, _importerFactory); CreateMemberStubs(memberCloneContext); DeepCopyMembers(memberCloneContext); return new MemberCloneResult(memberCloneContext.ClonedMembers); } private void CreateMemberStubs(MemberCloneContext context) { CreateTypeStubs(context); CreateMethodStubs(context); CreateFieldStubs(context); } private void CreateTypeStubs(MemberCloneContext context) { foreach (TypeDefinition item in _typesToClone) { CreateTypeStub(context, item); } } private static void CreateTypeStub(MemberCloneContext context, TypeDefinition type) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (type.Name == null) { throw new ArgumentException("Type " + type.SafeToString() + " has no name."); } TypeDefinition value = new TypeDefinition(type.Namespace, type.Name, type.Attributes); context.ClonedMembers.Add(type, value); } private void DeepCopyMembers(MemberCloneContext context) { DeepCopyTypes(context); DeepCopyMethods(context); DeepCopyFields(context); DeepCopyProperties(context); DeepCopyEvents(context); } private void DeepCopyTypes(MemberCloneContext context) { foreach (TypeDefinition item in _typesToClone) { DeepCopyType(context, item); TypeDefinition cloned = (TypeDefinition)context.ClonedMembers[item]; _clonerListener.OnClonedMember(item, cloned); _clonerListener.OnClonedType(item, cloned); } } private void DeepCopyType(MemberCloneContext context, TypeDefinition type) { TypeDefinition typeDefinition = (TypeDefinition)context.ClonedMembers[type]; ITypeDefOrRef baseType = type.BaseType; if (baseType != null) { typeDefinition.BaseType = context.Importer.ImportType(baseType); } foreach (InterfaceImplementation @interface in type.Interfaces) { typeDefinition.Interfaces.Add(CloneInterfaceImplementation(context, @interface)); } foreach (MethodImplementation methodImplementation in type.MethodImplementations) { typeDefinition.MethodImplementations.Add(new MethodImplementation(context.Importer.ImportMethodOrNull(methodImplementation.Declaration), context.Importer.ImportMethodOrNull(methodImplementation.Body))); } if (type.IsNested && type.DeclaringType != null && context.ClonedMembers.TryGetValue(type.DeclaringType, out IMemberDescriptor value) && value is TypeDefinition typeDefinition2) { typeDefinition2.NestedTypes.Add(typeDefinition); } ClassLayout classLayout = type.ClassLayout; if (classLayout != null) { typeDefinition.ClassLayout = new ClassLayout(classLayout.PackingSize, classLayout.ClassSize); } CloneCustomAttributes(context, type, typeDefinition); CloneGenericParameters(context, type, typeDefinition); CloneSecurityDeclarations(context, type, typeDefinition); } private static InterfaceImplementation CloneInterfaceImplementation(MemberCloneContext context, InterfaceImplementation implementation) { InterfaceImplementation interfaceImplementation = new InterfaceImplementation(context.Importer.ImportTypeOrNull(implementation.Interface)); CloneCustomAttributes(context, implementation, interfaceImplementation); return interfaceImplementation; } private static void CloneCustomAttributes(MemberCloneContext context, IHasCustomAttribute sourceProvider, IHasCustomAttribute clonedProvider) { foreach (CustomAttribute customAttribute in sourceProvider.CustomAttributes) { clonedProvider.CustomAttributes.Add(CloneCustomAttribute(context, customAttribute)); } } private static CustomAttribute CloneCustomAttribute(MemberCloneContext context, CustomAttribute attribute) { CustomAttributeSignature customAttributeSignature = new CustomAttributeSignature(); if (attribute.Signature != null) { foreach (CustomAttributeArgument fixedArgument in attribute.Signature.FixedArguments) { customAttributeSignature.FixedArguments.Add(CloneCustomAttributeArgument(context, fixedArgument)); } foreach (AsmResolver.DotNet.Signatures.CustomAttributeNamedArgument namedArgument in attribute.Signature.NamedArguments) { AsmResolver.DotNet.Signatures.CustomAttributeNamedArgument item = new AsmResolver.DotNet.Signatures.CustomAttributeNamedArgument(namedArgument.MemberType, namedArgument.MemberName, namedArgument.ArgumentType, CloneCustomAttributeArgument(context, namedArgument.Argument)); customAttributeSignature.NamedArguments.Add(item); } } ICustomAttributeType constructor = attribute.Constructor; if (constructor == null) { throw new ArgumentException("Custom attribute of " + attribute.Parent.SafeToString() + " does not have a constructor defined."); } return new CustomAttribute((ICustomAttributeType)context.Importer.ImportMethod(constructor), customAttributeSignature); } private static CustomAttributeArgument CloneCustomAttributeArgument(MemberCloneContext context, CustomAttributeArgument argument) { CustomAttributeArgument customAttributeArgument = new CustomAttributeArgument(context.Importer.ImportTypeSignature(argument.ArgumentType)); customAttributeArgument.IsNullArray = argument.IsNullArray; for (int i = 0; i < argument.Elements.Count; i++) { customAttributeArgument.Elements.Add(argument.Elements[i]); } return customAttributeArgument; } private static ImplementationMap? CloneImplementationMap(MemberCloneContext context, ImplementationMap? map) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (map == null) { return null; } if (map.Scope == null) { throw new ArgumentException("Scope of implementation map " + map.SafeToString() + " is null."); } return new ImplementationMap(context.Importer.ImportModule(map.Scope), map.Name, map.Attributes); } private static Constant? CloneConstant(Constant? constant) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (constant == null) { return null; } return new Constant(constant.Type, (constant.Value == null) ? null : new DataBlobSignature(constant.Value.Data)); } private void CloneGenericParameters(MemberCloneContext context, IHasGenericParameters sourceProvider, IHasGenericParameters clonedProvider) { foreach (GenericParameter genericParameter in sourceProvider.GenericParameters) { clonedProvider.GenericParameters.Add(CloneGenericParameter(context, genericParameter)); } } private static GenericParameter CloneGenericParameter(MemberCloneContext context, GenericParameter parameter) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) GenericParameter genericParameter = new GenericParameter(parameter.Name, parameter.Attributes); foreach (GenericParameterConstraint constraint in parameter.Constraints) { genericParameter.Constraints.Add(CloneGenericParameterConstraint(context, constraint)); } CloneCustomAttributes(context, parameter, genericParameter); return genericParameter; } private static GenericParameterConstraint CloneGenericParameterConstraint(MemberCloneContext context, GenericParameterConstraint constraint) { GenericParameterConstraint genericParameterConstraint = new GenericParameterConstraint(context.Importer.ImportTypeOrNull(constraint.Constraint)); CloneCustomAttributes(context, constraint, genericParameterConstraint); return genericParameterConstraint; } private static MarshalDescriptor? CloneMarshalDescriptor(MemberCloneContext context, MarshalDescriptor? marshalDescriptor) { if (marshalDescriptor != null) { if (!(marshalDescriptor is ComInterfaceMarshalDescriptor comInterfaceMarshalDescriptor)) { if (!(marshalDescriptor is CustomMarshalDescriptor customMarshalDescriptor)) { if (!(marshalDescriptor is FixedArrayMarshalDescriptor fixedArrayMarshalDescriptor)) { if (!(marshalDescriptor is FixedSysStringMarshalDescriptor fixedSysStringMarshalDescriptor)) { if (!(marshalDescriptor is LPArrayMarshalDescriptor lPArrayMarshalDescriptor)) { if (!(marshalDescriptor is SafeArrayMarshalDescriptor safeArrayMarshalDescriptor)) { if (marshalDescriptor is SimpleMarshalDescriptor simpleMarshalDescriptor) { return new SimpleMarshalDescriptor(simpleMarshalDescriptor.NativeType); } throw new ArgumentOutOfRangeException("marshalDescriptor"); } return new SafeArrayMarshalDescriptor(safeArrayMarshalDescriptor.VariantType, safeArrayMarshalDescriptor.VariantTypeFlags, context.Importer.ImportTypeSignatureOrNull(safeArrayMarshalDescriptor.UserDefinedSubType)); } return new LPArrayMarshalDescriptor(lPArrayMarshalDescriptor.ArrayElementType); } return new FixedSysStringMarshalDescriptor(fixedSysStringMarshalDescriptor.Size); } return new FixedArrayMarshalDescriptor { Size = fixedArrayMarshalDescriptor.Size, ArrayElementType = fixedArrayMarshalDescriptor.ArrayElementType }; } return new CustomMarshalDescriptor(customMarshalDescriptor.Guid, customMarshalDescriptor.NativeTypeName, context.Importer.ImportTypeSignatureOrNull(customMarshalDescriptor.MarshalType), customMarshalDescriptor.Cookie); } return new ComInterfaceMarshalDescriptor(comInterfaceMarshalDescriptor.NativeType); } return null; } private static void CloneSecurityDeclarations(MemberCloneContext context, IHasSecurityDeclaration sourceProvider, IHasSecurityDeclaration clonedProvider) { foreach (SecurityDeclaration securityDeclaration in sourceProvider.SecurityDeclarations) { clonedProvider.SecurityDeclarations.Add(CloneSecurityDeclaration(context, securityDeclaration)); } } private static SecurityDeclaration CloneSecurityDeclaration(MemberCloneContext context, SecurityDeclaration declaration) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return new SecurityDeclaration(declaration.Action, ClonePermissionSet(context, declaration.PermissionSet)); } private static PermissionSetSignature? ClonePermissionSet(MemberCloneContext context, PermissionSetSignature? permissionSet) { if (permissionSet == null) { return null; } PermissionSetSignature permissionSetSignature = new PermissionSetSignature(); foreach (SecurityAttribute attribute in permissionSet.Attributes) { permissionSetSignature.Attributes.Add(CloneSecurityAttribute(context, attribute)); } return permissionSetSignature; } private static SecurityAttribute CloneSecurityAttribute(MemberCloneContext context, SecurityAttribute attribute) { SecurityAttribute securityAttribute = new SecurityAttribute(context.Importer.ImportTypeSignature(attribute.AttributeType)); foreach (AsmResolver.DotNet.Signatures.CustomAttributeNamedArgument namedArgument in attribute.NamedArguments) { AsmResolver.DotNet.Signatures.CustomAttributeNamedArgument item = new AsmResolver.DotNet.Signatures.CustomAttributeNamedArgument(namedArgument.MemberType, namedArgument.MemberName, context.Importer.ImportTypeSignature(namedArgument.ArgumentType), CloneCustomAttributeArgument(context, namedArgument.Argument)); securityAttribute.NamedArguments.Add(item); } return securityAttribute; } private void CreateFieldStubs(MemberCloneContext context) { foreach (FieldDefinition item2 in _fieldsToClone) { FieldDefinition item = CreateFieldStub(context, item2); if (item2.DeclaringType != null && context.ClonedMembers.TryGetValue(item2.DeclaringType, out IMemberDescriptor value) && value is TypeDefinition typeDefinition) { typeDefinition.Fields.Add(item); } } } private static FieldDefinition CreateFieldStub(MemberCloneContext context, FieldDefinition field) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (field.Name == null) { throw new ArgumentException("Field " + field.SafeToString() + " has no name."); } if (field.Signature == null) { throw new ArgumentException("Field " + field.SafeToString() + " has no signature."); } FieldDefinition fieldDefinition = new FieldDefinition(field.Name, field.Attributes, context.Importer.ImportFieldSignature(field.Signature)); context.ClonedMembers.Add(field, fieldDefinition); return fieldDefinition; } private void DeepCopyFields(MemberCloneContext context) { foreach (FieldDefinition item in _fieldsToClone) { DeepCopyField(context, item); FieldDefinition cloned = (FieldDefinition)context.ClonedMembers[item]; _clonerListener.OnClonedMember(item, cloned); _clonerListener.OnClonedField(item, cloned); } } private void DeepCopyField(MemberCloneContext context, FieldDefinition field) { FieldDefinition fieldDefinition = (FieldDefinition)context.ClonedMembers[field]; CloneCustomAttributes(context, field, fieldDefinition); fieldDefinition.ImplementationMap = CloneImplementationMap(context, field.ImplementationMap); fieldDefinition.Constant = CloneConstant(field.Constant); fieldDefinition.FieldRva = FieldRvaCloner.CloneFieldRvaData(field); fieldDefinition.MarshalDescriptor = CloneMarshalDescriptor(context, field.MarshalDescriptor); fieldDefinition.FieldOffset = field.FieldOffset; } private void CreateMethodStubs(MemberCloneContext context) { foreach (MethodDefinition item2 in _methodsToClone) { MethodDefinition item = CreateMethodStub(context, item2); if (item2.DeclaringType != null && context.ClonedMembers.TryGetValue(item2.DeclaringType, out IMemberDescriptor value) && value is TypeDefinition typeDefinition) { typeDefinition.Methods.Add(item); } } } private static MethodDefinition CreateMethodStub(MemberCloneContext context, MethodDefinition method) { //IL_004d: 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) if (method.Name == null) { throw new ArgumentException("Method " + method.SafeToString() + " has no name."); } if (method.Signature == null) { throw new ArgumentException("Method " + method.SafeToString() + " has no signature."); } MethodDefinition methodDefinition = new MethodDefinition(method.Name, method.Attributes, context.Importer.ImportMethodSignature(method.Signature)); methodDefinition.ImplAttributes = method.ImplAttributes; methodDefinition.Parameters.PullUpdatesFromMethodSignature(); context.ClonedMembers[method] = methodDefinition; return methodDefinition; } private static ParameterDefinition CloneParameterDefinition(MemberCloneContext context, ParameterDefinition parameterDef) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) ParameterDefinition parameterDefinition = new ParameterDefinition(parameterDef.Sequence, parameterDef.Name, parameterDef.Attributes); CloneCustomAttributes(context, parameterDef, parameterDefinition); parameterDefinition.Constant = CloneConstant(parameterDef.Constant); parameterDefinition.MarshalDescriptor = CloneMarshalDescriptor(context, parameterDef.MarshalDescriptor); return parameterDefinition; } private void DeepCopyMethods(MemberCloneContext context) { foreach (MethodDefinition item in _methodsToClone) { DeepCopyMethod(context, item); MethodDefinition cloned = (MethodDefinition)context.ClonedMembers[item]; _clonerListener.OnClonedMember(item, cloned); _clonerListener.OnClonedMethod(item, cloned); } } private void DeepCopyMethod(MemberCloneContext context, MethodDefinition method) { MethodDefinition methodDefinition = (MethodDefinition)context.ClonedMembers[method]; CloneParameterDefinitionsInMethod(context, method, methodDefinition); if (method.CilMethodBody != null) { methodDefinition.CilMethodBody = CloneCilMethodBody(context, method); } CloneCustomAttributes(context, method, methodDefinition); CloneGenericParameters(context, method, methodDefinition); CloneSecurityDeclarations(context, method, methodDefinition); methodDefinition.ImplementationMap = CloneImplementationMap(context, method.ImplementationMap); } private void CloneParameterDefinitionsInMethod(MemberCloneContext context, MethodDefinition method, MethodDefinition clonedMethod) { foreach (ParameterDefinition parameterDefinition in method.ParameterDefinitions) { clonedMethod.ParameterDefinitions.Add(CloneParameterDefinition(context, parameterDefinition)); } } private static CilMethodBody CloneCilMethodBody(MemberCloneContext context, MethodDefinition method) { CilMethodBody cilMethodBody = method.CilMethodBody; CilMethodBody cilMethodBody2 = new CilMethodBody((MethodDefinition)context.ClonedMembers[method]); cilMethodBody2.InitializeLocals = cilMethodBody.InitializeLocals; cilMethodBody2.MaxStack = cilMethodBody.MaxStack; CloneLocalVariables(context, cilMethodBody, cilMethodBody2); CloneCilInstructions(context, cilMethodBody, cilMethodBody2); CloneExceptionHandlers(context, cilMethodBody, cilMethodBody2); return cilMethodBody2; } private static void CloneLocalVariables(MemberCloneContext context, CilMethodBody body, CilMethodBody clonedBody) { foreach (CilLocalVariable localVariable in body.LocalVariables) { CilLocalVariable item = new CilLocalVariable(context.Importer.ImportTypeSignature(localVariable.VariableType)); clonedBody.LocalVariables.Add(item); } } private static void CloneCilInstructions(MemberCloneContext context, CilMethodBody body, CilMethodBody clonedBody) { //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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Invalid comparison between Unknown and I4 //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown List list = new List(); List list2 = new List(); foreach (CilInstruction instruction in body.Instructions) { CilInstruction val = CloneInstruction(context, clonedBody, instruction); CilOpCode opCode = val.OpCode; if ((int)((CilOpCode)(ref opCode)).Code == 69) { list2.Add(val); } else if (val.IsBranch()) { list.Add(val); } clonedBody.Instructions.Add(val); } foreach (CilInstruction item in list) { ICilLabel val2 = (ICilLabel)item.Operand; item.Operand = clonedBody.Instructions.GetLabel(val2.Offset); } foreach (CilInstruction item2 in list2) { IList list3 = (IList)item2.Operand; List list4 = new List(list3.Count); for (int i = 0; i < list3.Count; i++) { list4.Add(clonedBody.Instructions.GetLabel(list3[i].Offset)); } item2.Operand = list4; } } private static CilInstruction CloneInstruction(MemberCloneContext context, CilMethodBody clonedBody, CilInstruction instruction) { //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_0012: Expected O, but got Unknown //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_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected I4, but got Unknown CilInstruction val = new CilInstruction(instruction.Offset, instruction.OpCode); CilOpCode opCode = instruction.OpCode; CilOperandType operandType = ((CilOpCode)(ref opCode)).OperandType; switch ((int)operandType) { case 0: case 11: case 15: val.Operand = instruction.Operand; break; case 1: if (instruction.Operand is IFieldDescriptor field) { val.Operand = context.Importer.ImportField(field); break; } goto case 2; case 4: if (instruction.Operand is IMethodDescriptor method) { val.Operand = context.Importer.ImportMethod(method); break; } goto case 2; case 9: if (instruction.Operand is StandAloneSignature standAloneSignature) { BlobSignature signature = standAloneSignature.Signature; BlobSignature signature4; if (!(signature is MethodSignature signature2)) { if (!(signature is GenericInstanceMethodSignature signature3)) { throw new NotImplementedException(); } signature4 = context.Importer.ImportGenericInstanceMethodSignature(signature3); } else { signature4 = context.Importer.ImportMethodSignature(signature2); } instruction.Operand = new StandAloneSignature(signature4); break; } goto default; case 13: if (instruction.Operand is ITypeDefOrRef type) { val.Operand = context.Importer.ImportType(type); break; } goto case 2; case 2: case 3: case 5: case 7: case 10: case 16: case 17: val.Operand = instruction.Operand; break; case 12: val.Operand = CloneInlineTokOperand(context, instruction); break; case 14: case 18: val.Operand = ((instruction.Operand is CilLocalVariable cilLocalVariable) ? clonedBody.LocalVariables[cilLocalVariable.Index] : instruction.Operand); break; case 19: case 20: val.Operand = ((instruction.Operand is Parameter parameter) ? clonedBody.Owner.Parameters.GetBySignatureIndex(parameter.MethodSignatureIndex) : instruction.Operand); break; default: throw new ArgumentOutOfRangeException(); } return val; } private static object CloneInlineTokOperand(MemberCloneContext context, CilInstruction instruction) { object operand = instruction.Operand; if (!(operand is ITypeDefOrRef type)) { if (operand is MemberReference memberReference) { if (memberReference.IsField) { return context.Importer.ImportField(memberReference); } if (memberReference.IsMethod) { MemberReference method = memberReference; return context.Importer.ImportMethod(method); } } else { if (operand is MethodDefinition method2) { return context.Importer.ImportMethod(method2); } if (operand is FieldDefinition field) { return context.Importer.ImportField(field); } } throw new NotSupportedException(); } return context.Importer.ImportType(type); } private static void CloneExceptionHandlers(MemberCloneContext context, CilMethodBody body, CilMethodBody clonedBody) { CilMethodBody clonedBody2 = clonedBody; foreach (CilExceptionHandler exceptionHandler in body.ExceptionHandlers) { clonedBody2.ExceptionHandlers.Add(new CilExceptionHandler { HandlerType = exceptionHandler.HandlerType, TryStart = ToClonedLabel(exceptionHandler.TryStart), TryEnd = ToClonedLabel(exceptionHandler.TryEnd), HandlerStart = ToClonedLabel(exceptionHandler.HandlerStart), HandlerEnd = ToClonedLabel(exceptionHandler.HandlerEnd), FilterStart = ToClonedLabel(exceptionHandler.FilterStart), ExceptionType = ((exceptionHandler.ExceptionType == null) ? null : context.Importer.ImportType(exceptionHandler.ExceptionType)) }); } ICilLabel? ToClonedLabel(ICilLabel? label) { if (label == null) { return null; } return clonedBody2.Instructions.GetLabel(label.Offset); } } private void DeepCopyProperties(MemberCloneContext context) { foreach (PropertyDefinition item in _propertiesToClone) { PropertyDefinition propertyDefinition = DeepCopyProperty(context, item); if (item.DeclaringType != null && context.ClonedMembers.TryGetValue(item.DeclaringType, out IMemberDescriptor value) && value is TypeDefinition typeDefinition) { typeDefinition.Properties.Add(propertyDefinition); } PropertyDefinition cloned = propertyDefinition; _clonerListener.OnClonedMember(item, cloned); _clonerListener.OnClonedProperty(item, cloned); } } private PropertyDefinition DeepCopyProperty(MemberCloneContext context, PropertyDefinition property) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (property.Name == null) { throw new ArgumentException("Property " + property.SafeToString() + " has no name."); } if (property.Signature == null) { throw new ArgumentException("Property " + property.SafeToString() + " has no signature."); } PropertyDefinition propertyDefinition = new PropertyDefinition(property.Name, property.Attributes, context.Importer.ImportPropertySignature(property.Signature)); CloneSemantics(context, property, propertyDefinition); CloneCustomAttributes(context, property, propertyDefinition); property.Constant = CloneConstant(property.Constant); return propertyDefinition; } private void DeepCopyEvents(MemberCloneContext context) { foreach (EventDefinition item in _eventsToClone) { EventDefinition eventDefinition = DeepCopyEvent(context, item); if (item.DeclaringType != null && context.ClonedMembers.TryGetValue(item.DeclaringType, out IMemberDescriptor value) && value is TypeDefinition typeDefinition) { typeDefinition.Events.Add(eventDefinition); } EventDefinition cloned = eventDefinition; _clonerListener.OnClonedMember(item, cloned); _clonerListener.OnClonedEvent(item, cloned); } } private static EventDefinition DeepCopyEvent(MemberCloneContext context, EventDefinition @event) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (@event.Name == null) { throw new ArgumentException("Event " + @event.SafeToString() + " has no name."); } if (@event.EventType == null) { throw new ArgumentException("Event " + @event.SafeToString() + " has no event-type."); } EventDefinition eventDefinition = new EventDefinition(@event.Name, @event.Attributes, context.Importer.ImportType(@event.EventType)); CloneSemantics(context, @event, eventDefinition); CloneCustomAttributes(context, @event, eventDefinition); return eventDefinition; } private static void CloneSemantics(MemberCloneContext context, IHasSemantics semanticsProvider, IHasSemantics clonedProvider) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) foreach (MethodSemantics semantic in semanticsProvider.Semantics) { clonedProvider.Semantics.Add(new MethodSemantics((MethodDefinition)context.ClonedMembers[semantic.Method], semantic.Attributes)); } } } public class MemberCloneResult { private readonly IDictionary _clonedMembers; public ICollection ClonedMembers => _clonedMembers.Values; public ICollection OriginalMembers => _clonedMembers.Keys; public ICollection ClonedTopLevelTypes { get; } public MemberCloneResult(IDictionary clonedMembers) { _clonedMembers = clonedMembers ?? throw new ArgumentNullException("clonedMembers"); ClonedTopLevelTypes = (from type in clonedMembers.Values.OfType() where !type.IsNested select type).ToList().AsReadOnly(); } public bool ContainsClonedMember(IMemberDescriptor originalMember) { return _clonedMembers.ContainsKey(originalMember); } public T GetClonedMember(T originalMember) where T : IMemberDescriptor { if (!_clonedMembers.ContainsKey(originalMember)) { throw new ArgumentOutOfRangeException("originalMember"); } return (T)_clonedMembers[originalMember]; } } public abstract class MemberClonerListener : IMemberClonerListener { public virtual void OnClonedMember(IMemberDefinition original, IMemberDefinition cloned) { } public virtual void OnClonedEvent(EventDefinition original, EventDefinition cloned) { } public virtual void OnClonedField(FieldDefinition original, FieldDefinition cloned) { } public virtual void OnClonedMethod(MethodDefinition original, MethodDefinition cloned) { } public virtual void OnClonedProperty(PropertyDefinition original, PropertyDefinition cloned) { } public virtual void OnClonedType(TypeDefinition original, TypeDefinition cloned) { } } } namespace AsmResolver.DotNet.Bundles { public class BundleFile : IOwnedCollectionElement { private readonly LazyVariable _contents; public BundleManifest? ParentManifest { get; private set; } BundleManifest? IOwnedCollectionElement.Owner { get { return ParentManifest; } set { ParentManifest = value; } } public string RelativePath { get; set; } public BundleFileType Type { get; set; } public bool IsCompressed { get; set; } public ISegment Contents { get { return _contents.Value; } set { _contents.Value = value; } } public bool CanRead => Contents is IReadableSegment; public BundleFile(string relativePath) { RelativePath = relativePath; _contents = new LazyVariable((Func)GetContents); } public BundleFile(string relativePath, BundleFileType type, byte[] contents) : this(relativePath, type, (ISegment)new DataSegment(contents)) { }//IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown public BundleFile(string relativePath, BundleFileType type, ISegment contents) { RelativePath = relativePath; Type = type; _contents = new LazyVariable(contents); } protected virtual ISegment? GetContents() { return null; } public bool TryGetReader(out BinaryStreamReader reader) { //IL_001e: 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_0016: Unknown result type (might be due to invalid IL or missing references) ISegment contents = Contents; IReadableSegment val = (IReadableSegment)(object)((contents is IReadableSegment) ? contents : null); if (val != null) { reader = Extensions.CreateReader(val); return true; } reader = default(BinaryStreamReader); return false; } public byte[] GetData() { return GetData(decompressIfRequired: true); } public byte[] GetData(bool decompressIfRequired) { if (TryGetReader(out var reader)) { byte[] array = ((BinaryStreamReader)(ref reader)).ReadToEnd(); if (decompressIfRequired && IsCompressed) { using MemoryStream memoryStream = new MemoryStream(); using MemoryStream stream = new MemoryStream(array); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } array = memoryStream.ToArray(); } return array; } throw new InvalidOperationException("Contents of file is not readable."); } public void Compress() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown if (IsCompressed) { throw new InvalidOperationException("File is already compressed."); } using MemoryStream memoryStream2 = new MemoryStream(GetData()); using MemoryStream memoryStream = new MemoryStream(); using (DeflateStream destination = new DeflateStream(memoryStream, CompressionLevel.Optimal)) { memoryStream2.CopyTo(destination); } Contents = (ISegment)new DataSegment(memoryStream.ToArray()); IsCompressed = true; } public void Decompress() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown if (!IsCompressed) { throw new InvalidOperationException("File is not compressed."); } Contents = (ISegment)new DataSegment(GetData(decompressIfRequired: true)); IsCompressed = false; } public override string ToString() { return RelativePath; } } public enum BundleFileType { Unknown, Assembly, NativeBinary, DepsJson, RuntimeConfigJson, Symbols } public class BundleManifest { private const int DefaultBundleIDLength = 12; private static readonly byte[] BundleSignature = new byte[32] { 139, 18, 2, 185, 106, 97, 32, 56, 114, 123, 147, 2, 20, 215, 160, 50, 19, 245, 185, 230, 239, 174, 51, 24, 238, 59, 45, 206, 36, 179, 106, 174 }; private static readonly byte[] AppBinaryPathPlaceholder = Encoding.UTF8.GetBytes("c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2"); private IList? _files; public uint MajorVersion { get; set; } public uint MinorVersion { get; set; } public string? BundleID { get; set; } public BundleManifestFlags Flags { get; set; } public IList Files { get { if (_files == null) { Interlocked.CompareExchange(ref _files, GetFiles(), null); } return _files; } } protected BundleManifest() { } public BundleManifest(uint majorVersionNumber) { MajorVersion = majorVersionNumber; MinorVersion = 0u; } public BundleManifest(uint majorVersionNumber, string bundleId) { MajorVersion = majorVersionNumber; MinorVersion = 0u; BundleID = bundleId; } public static BundleManifest FromFile(string filePath) { return FromBytes(File.ReadAllBytes(filePath)); } public static BundleManifest FromBytes(byte[] data) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown return FromDataSource((IDataSource)new ByteArrayDataSource(data)); } public static BundleManifest FromBytes(byte[] data, ulong offset) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown return FromDataSource((IDataSource)new ByteArrayDataSource(data), offset); } public static BundleManifest FromDataSource(IDataSource source) { long num = FindBundleManifestAddress(source); if (num == -1) { throw new BadImageFormatException("File does not contain an AppHost bundle signature."); } return FromDataSource(source, (ulong)num); } public static BundleManifest FromDataSource(IDataSource source, ulong offset) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) BinaryStreamReader reader = default(BinaryStreamReader); ((BinaryStreamReader)(ref reader))..ctor(source, 0uL, 0u, (uint)source.Length); ((BinaryStreamReader)(ref reader)).Offset = offset; return FromReader(reader); } public static BundleManifest FromReader(BinaryStreamReader reader) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return new SerializedBundleManifest(reader); } private static long FindInFile(IDataSource source, byte[] data) { byte[] array = new byte[4096]; int num2; for (ulong num = 0uL; num < source.Length; num += (ulong)num2) { num2 = source.ReadBytes(num, array, 0, array.Length); for (int i = 8; i < num2 - data.Length; i++) { bool flag = true; int num3 = 0; while (flag && num3 < data.Length) { if (array[i + num3] != data[num3]) { flag = false; } num3++; } if (flag) { return (long)num + (long)i; } } } return -1L; } private static long ReadBundleManifestAddress(IDataSource source, long signatureAddress) { BinaryStreamReader val = default(BinaryStreamReader); ((BinaryStreamReader)(ref val))..ctor(source, (ulong)(signatureAddress - 8), 0u, 8u); ulong num = ((BinaryStreamReader)(ref val)).ReadUInt64(); if (!source.IsValidAddress(num)) { return -1L; } return (long)num; } public static long FindBundleManifestAddress(IDataSource source) { long num = FindInFile(source, BundleSignature); if (num == -1) { return -1L; } return ReadBundleManifestAddress(source, num); } public static bool IsBundledAssembly(IDataSource source) { return FindBundleManifestAddress(source) != -1; } protected virtual IList GetFiles() { return (IList)new OwnedCollection(this); } public string GenerateDeterministicBundleID() { using SHA256 sHA2 = SHA256.Create(); for (int i = 0; i < Files.Count; i++) { BundleFile bundleFile = Files[i]; using SHA256 sHA = SHA256.Create(); byte[] array = sHA.ComputeHash(bundleFile.GetData()); sHA2.TransformBlock(array, 0, array.Length, array, 0); } sHA2.TransformFinalBlock(Array.Empty(), 0, 0); return Convert.ToBase64String(sHA2.Hash).Substring(12).Replace('/', '_'); } public void WriteUsingTemplate(string outputPath, in BundlerParameters parameters) { using FileStream outputStream = File.Create(outputPath); WriteUsingTemplate(outputStream, in parameters); } public void WriteUsingTemplate(Stream outputStream, in BundlerParameters parameters) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown WriteUsingTemplate((IBinaryStreamWriter)new BinaryStreamWriter(outputStream), parameters); } public void WriteUsingTemplate(IBinaryStreamWriter writer, BundlerParameters parameters) { //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_00a4: Expected O, but got Unknown //IL_00bf: Expected O, but got Unknown if (Files.FirstOrDefault((BundleFile f) => f.RelativePath == parameters.ApplicationBinaryPath) == null) { throw new ArgumentException("Application " + parameters.ApplicationBinaryPath + " does not exist within the bundle."); } byte[] bytes = Encoding.UTF8.GetBytes(parameters.ApplicationBinaryPath); if (bytes.Length > 1024) { throw new ArgumentException("Application binary path cannot exceed 1024 bytes."); } if (!parameters.IsArm64Linux) { EnsureAppHostPEHeadersAreUpToDate(ref parameters); } ByteArrayDataSource val = new ByteArrayDataSource(parameters.ApplicationHostTemplate); long num = FindInFile((IDataSource)val, BundleSignature); if (num == -1) { throw new ArgumentException("AppHost template does not contain the bundle signature."); } long num2 = FindInFile((IDataSource)val, AppBinaryPathPlaceholder); if (num2 == -1) { throw new ArgumentException("AppHost template does not contain the application binary path placeholder."); } IOExtensions.WriteBytes(writer, parameters.ApplicationHostTemplate); writer.Offset = writer.Length; ulong num3 = WriteManifest(writer, parameters.IsArm64Linux); writer.Offset = (ulong)(num - 8); writer.WriteUInt64(num3); writer.Offset = (ulong)num2; IOExtensions.WriteBytes(writer, bytes); if (AppBinaryPathPlaceholder.Length > bytes.Length) { IOExtensions.WriteZeroes(writer, AppBinaryPathPlaceholder.Length - bytes.Length); } } private static void EnsureAppHostPEHeadersAreUpToDate(ref BundlerParameters parameters) { //IL_001c: 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_0030: 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_004f: Expected O, but got Unknown //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_00eb: Unknown result type (might be due to invalid IL or missing references) PEFile val; try { val = PEFile.FromBytes(parameters.ApplicationHostTemplate); } catch (BadImageFormatException) { return; } bool flag = false; if (val.OptionalHeader.SubSystem != parameters.SubSystem) { val.OptionalHeader.SubSystem = parameters.SubSystem; flag = true; } IResourceDirectory resources = parameters.Resources; if (resources != null) { ResourceDirectoryBuffer val2 = new ResourceDirectoryBuffer(); val2.AddDirectory(resources); PESection val3 = new PESection(".rsrc", (SectionFlags)1073741888); val3.Contents = (ISegment)(object)val2; int index = val.Sections.Count - 1; for (int num = val.Sections.Count - 1; num >= 0; num--) { if (val.Sections[num].Name == ".reloc") { index = num; break; } } val.Sections.Insert(index, val3); val.AlignSections(); val.OptionalHeader.DataDirectories[2] = new DataDirectory(val2.Rva, val2.GetPhysicalSize()); flag = true; } if (flag) { using (MemoryStream memoryStream = new MemoryStream()) { val.Write((Stream)memoryStream); parameters.ApplicationHostTemplate = memoryStream.ToArray(); } } } public ulong WriteManifest(IBinaryStreamWriter writer, bool isArm64Linux) { WriteFileContents(writer, isArm64Linux ? 4096u : 16u); ulong offset = writer.Offset; WriteManifestHeader(writer); return offset; } private void WriteFileContents(IBinaryStreamWriter writer, uint alignment) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < Files.Count; i++) { BundleFile bundleFile = Files[i]; if (bundleFile.Type == BundleFileType.Assembly) { IOExtensions.Align(writer, alignment); } ISegment contents = bundleFile.Contents; RelocationParameters val = new RelocationParameters(writer.Offset, (uint)writer.Offset); contents.UpdateOffsets(ref val); ((IWritable)bundleFile.Contents).Write(writer); } } private void WriteManifestHeader(IBinaryStreamWriter writer) { writer.WriteUInt32(MajorVersion); writer.WriteUInt32(MinorVersion); writer.WriteInt32(Files.Count); if (BundleID == null) { string text2 = (BundleID = GenerateDeterministicBundleID()); } IOExtensions.WriteBinaryFormatterString(writer, BundleID); if (MajorVersion >= 2) { WriteFileOffsetSizePair(writer, Files.FirstOrDefault((BundleFile f) => f.Type == BundleFileType.DepsJson)); WriteFileOffsetSizePair(writer, Files.FirstOrDefault((BundleFile f) => f.Type == BundleFileType.RuntimeConfigJson)); writer.WriteUInt64((ulong)Flags); } WriteFileHeaders(writer); } private void WriteFileHeaders(IBinaryStreamWriter writer) { for (int i = 0; i < Files.Count; i++) { BundleFile bundleFile = Files[i]; WriteFileOffsetSizePair(writer, bundleFile); if (MajorVersion >= 6) { writer.WriteUInt64((ulong)(bundleFile.IsCompressed ? ((IWritable)bundleFile.Contents).GetPhysicalSize() : 0u)); } writer.WriteByte((byte)bundleFile.Type); IOExtensions.WriteBinaryFormatterString(writer, bundleFile.RelativePath); } } private static void WriteFileOffsetSizePair(IBinaryStreamWriter writer, BundleFile? file) { if (file != null) { writer.WriteUInt64(((IOffsetProvider)file.Contents).Offset); writer.WriteUInt64((ulong)file.GetData().Length); } else { writer.WriteUInt64(0uL); writer.WriteUInt64(0uL); } } } [Flags] public enum BundleManifestFlags : ulong { None = 0uL, NetCoreApp3CompatibilityMode = 1uL } public struct BundlerParameters { public byte[] ApplicationHostTemplate { get; set; } public string ApplicationBinaryPath { get; set; } public bool IsArm64Linux { get; set; } public IResourceDirectory? Resources { get; set; } public SubSystem SubSystem { get; set; } public BundlerParameters(string appHostTemplatePath, string appBinaryPath) : this(File.ReadAllBytes(appHostTemplatePath), appBinaryPath) { } public BundlerParameters(byte[] appHostTemplate, string appBinaryPath) { ApplicationHostTemplate = appHostTemplate; ApplicationBinaryPath = appBinaryPath; IsArm64Linux = false; Resources = null; SubSystem = (SubSystem)3; } public BundlerParameters(string appHostTemplatePath, string appBinaryPath, string? imagePathToCopyHeadersFrom) : this(File.ReadAllBytes(appHostTemplatePath), appBinaryPath, (!string.IsNullOrEmpty(imagePathToCopyHeadersFrom)) ? PEImage.FromFile(imagePathToCopyHeadersFrom) : null) { } public BundlerParameters(byte[] appHostTemplate, string appBinaryPath, byte[]? imageToCopyHeadersFrom) : this(appHostTemplate, appBinaryPath, (imageToCopyHeadersFrom != null) ? PEImage.FromBytes(imageToCopyHeadersFrom) : null) { } public BundlerParameters(byte[] appHostTemplate, string appBinaryPath, IDataSource? imageToCopyHeadersFrom) : this(appHostTemplate, appBinaryPath, (imageToCopyHeadersFrom != null) ? PEImage.FromDataSource(imageToCopyHeadersFrom, (PEMappingMode)0) : null) { } public unsafe BundlerParameters(byte[] appHostTemplate, string appBinaryPath, IPEImage? imageToCopyHeadersFrom) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f->IL000f: Incompatible stack types: Ref vs I4 //IL_0009->IL000f: Incompatible stack types: I4 vs Ref //IL_0009->IL000f: Incompatible stack types: Ref vs I4 ref BundlerParameters reference = ref this; object obj = appHostTemplate; obj = appBinaryPath; int num; if (imageToCopyHeadersFrom != null) { reference = ref *(BundlerParameters*)imageToCopyHeadersFrom.SubSystem; num = (int)(ref reference); } else { num = 3; reference = ref *(BundlerParameters*)num; num = (int)(ref reference); } Unsafe.Write((void*)num, new BundlerParameters((byte[])obj, (string)obj, (SubSystem)(ref reference), (imageToCopyHeadersFrom != null) ? imageToCopyHeadersFrom.Resources : null)); } public BundlerParameters(byte[] appHostTemplate, string appBinaryPath, SubSystem subSystem, IResourceDirectory? resources) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) ApplicationHostTemplate = appHostTemplate; ApplicationBinaryPath = appBinaryPath; IsArm64Linux = false; SubSystem = subSystem; Resources = resources; } } public class SerializedBundleFile : BundleFile { private readonly BinaryStreamReader _contentsReader; public SerializedBundleFile(ref BinaryStreamReader reader, uint bundleVersionFormat) : base(string.Empty) { //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) ulong num = ((BinaryStreamReader)(ref reader)).ReadUInt64(); ulong num2 = ((BinaryStreamReader)(ref reader)).ReadUInt64(); if (bundleVersionFormat >= 6) { ulong num3 = ((BinaryStreamReader)(ref reader)).ReadUInt64(); if (num3 != 0L) { num2 = num3; base.IsCompressed = true; } } base.Type = (BundleFileType)((BinaryStreamReader)(ref reader)).ReadByte(); base.RelativePath = ((BinaryStreamReader)(ref reader)).ReadBinaryFormatterString(); _contentsReader = ((BinaryStreamReader)(ref reader)).ForkAbsolute(num, (uint)num2); } protected override ISegment GetContents() { //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) BinaryStreamReader contentsReader = _contentsReader; return (ISegment)(object)((BinaryStreamReader)(ref contentsReader)).ReadSegment(((BinaryStreamReader)(ref _contentsReader)).Length); } } public class SerializedBundleManifest : BundleManifest { private readonly uint _originalMajorVersion; private readonly BinaryStreamReader _fileEntriesReader; private readonly int _originalFileCount; public SerializedBundleManifest(BinaryStreamReader reader) { //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) base.MajorVersion = (_originalMajorVersion = ((BinaryStreamReader)(ref reader)).ReadUInt32()); base.MinorVersion = ((BinaryStreamReader)(ref reader)).ReadUInt32(); _originalFileCount = ((BinaryStreamReader)(ref reader)).ReadInt32(); base.BundleID = ((BinaryStreamReader)(ref reader)).ReadBinaryFormatterString(); if (base.MajorVersion >= 2) { ((BinaryStreamReader)(ref reader)).Offset = ((BinaryStreamReader)(ref reader)).Offset + 32; base.Flags = (BundleManifestFlags)((BinaryStreamReader)(ref reader)).ReadUInt64(); } _fileEntriesReader = reader; } protected override IList GetFiles() { //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) BinaryStreamReader reader = _fileEntriesReader; OwnedCollection val = new OwnedCollection((BundleManifest)this); for (int i = 0; i < _originalFileCount; i++) { ((LazyList)(object)val).Add((BundleFile)new SerializedBundleFile(ref reader, _originalMajorVersion)); } return (IList)val; } } } namespace AsmResolver.DotNet.Builder { public class DotNetDirectoryBuffer : ITypeCodedIndexProvider, IMetadataTokenProvider { private readonly TokenMapping _tokenMapping = new TokenMapping(); public ModuleDefinition Module { get; } public IMethodBodySerializer MethodBodySerializer { get; } public INativeSymbolsProvider SymbolsProvider { get; } public IMetadataBuffer Metadata { get; } public IErrorListener ErrorListener { get; } public DotNetResourcesDirectoryBuffer Resources { get; } public int StrongNameSize { get; set; } public VTableFixupsBuffer VTableFixups { get; } private void AddCustomAttributes(MetadataToken ownerToken, IHasCustomAttribute provider) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < provider.CustomAttributes.Count; i++) { AddCustomAttribute(ownerToken, provider.CustomAttributes[i]); } } private void AddCustomAttribute(MetadataToken ownerToken, CustomAttribute attribute) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)12); if (attribute.Constructor != null && attribute.Signature != null) { attribute.Signature.IsCompatibleWith(attribute.Constructor, ErrorListener); } IndexEncoder indexEncoder = Metadata.TablesStream.GetIndexEncoder((CodedIndex)58); CustomAttributeRow row = default(CustomAttributeRow); ((CustomAttributeRow)(ref row))..ctor(indexEncoder.EncodeToken(ownerToken), AddCustomAttributeType(attribute.Constructor), Metadata.BlobStream.GetBlobIndex(this, attribute.Signature, ErrorListener)); sortedTable.Add(attribute, in row); } private uint AddResolutionScope(IResolutionScope? scope, bool allowDuplicates, bool preserveRid) { //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_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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Invalid comparison between Unknown and I4 //IL_001e: 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) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Invalid comparison between Unknown and I4 //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) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 //IL_0078: 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_008c: 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_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) if (!AssertIsImported(scope)) { return 0u; } MetadataToken metadataToken = scope.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; MetadataToken val; if ((int)table <= 1) { if ((int)table != 0) { if ((int)table != 1) { goto IL_006d; } val = AddTypeReference(scope as TypeReference, allowDuplicates, preserveRid); } else { val = MetadataToken.op_Implicit(0); } } else if ((int)table != 26) { if ((int)table != 35) { goto IL_006d; } val = AddAssemblyReference(scope as AssemblyReference, allowDuplicates, preserveRid); } else { val = AddModuleReference(scope as ModuleReference, allowDuplicates, preserveRid); } MetadataToken val2 = val; return Metadata.TablesStream.GetIndexEncoder((CodedIndex)67).EncodeToken(val2); IL_006d: throw new ArgumentOutOfRangeException("scope"); } public uint GetTypeDefOrRefIndex(ITypeDefOrRef? type) { //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_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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 //IL_003f: 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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //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_0075: 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_0035: 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: Invalid comparison between Unknown and I4 //IL_004e: 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) if (!AssertIsImported(type)) { return 0u; } MetadataToken metadataToken = type.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; MetadataToken val; if ((int)table != 1) { if ((int)table != 2) { if ((int)table != 27) { throw new ArgumentOutOfRangeException("type"); } val = GetTypeSpecificationToken(type as TypeSpecification); } else { val = GetTypeDefinitionToken(type as TypeDefinition); } } else { val = GetTypeReferenceToken(type as TypeReference); } MetadataToken val2 = val; return Metadata.TablesStream.GetIndexEncoder((CodedIndex)56).EncodeToken(val2); } private uint AddMemberRefParent(IMemberRefParent? parent) { //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_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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Invalid comparison between Unknown and I4 //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_006c: 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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Invalid comparison between Unknown and I4 //IL_004e: 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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Invalid comparison between Unknown and I4 //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_00a2: 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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Invalid comparison between Unknown and I4 //IL_003f: 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_005d: 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) if (!AssertIsImported(parent)) { return 0u; } MetadataToken metadataToken = parent.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; MetadataToken val; if ((int)table <= 2) { if ((int)table != 1) { if ((int)table != 2) { goto IL_0083; } val = GetTypeDefinitionToken(parent as TypeDefinition); } else { val = GetTypeReferenceToken(parent as TypeReference); } } else if ((int)table != 6) { if ((int)table != 26) { if ((int)table != 27) { goto IL_0083; } val = GetTypeSpecificationToken(parent as TypeSpecification); } else { val = GetModuleReferenceToken(parent as ModuleReference); } } else { val = GetMethodDefinitionToken(parent as MethodDefinition); } MetadataToken val2 = val; return Metadata.TablesStream.GetIndexEncoder((CodedIndex)61).EncodeToken(val2); IL_0083: throw new ArgumentOutOfRangeException("parent"); } private uint AddMethodDefOrRef(IMethodDefOrRef? method) { //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_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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 //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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_004e: 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_0062: 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) if (!AssertIsImported(method)) { return 0u; } MetadataToken metadataToken = method.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; MetadataToken val; if ((int)table != 6) { if ((int)table != 10) { throw new ArgumentOutOfRangeException("method"); } val = GetMemberReferenceToken(method as MemberReference); } else { val = GetMethodDefinitionToken(method as MethodDefinition); } MetadataToken val2 = val; return Metadata.TablesStream.GetIndexEncoder((CodedIndex)63).EncodeToken(val2); } private uint AddCustomAttributeType(ICustomAttributeType? constructor) { //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_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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 //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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_004e: 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_0062: 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) if (!AssertIsImported(constructor)) { return 0u; } MetadataToken metadataToken = constructor.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; MetadataToken val; if ((int)table != 6) { if ((int)table != 10) { throw new ArgumentOutOfRangeException("constructor"); } val = GetMemberReferenceToken(constructor as MemberReference); } else { val = GetMethodDefinitionToken(constructor as MethodDefinition); } MetadataToken val2 = val; return Metadata.TablesStream.GetIndexEncoder((CodedIndex)66).EncodeToken(val2); } private void AddConstant(MetadataToken ownerToken, Constant? constant) { //IL_002c: 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) if (constant != null) { ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)11); IndexEncoder indexEncoder = Metadata.TablesStream.GetIndexEncoder((CodedIndex)57); ConstantRow row = default(ConstantRow); ((ConstantRow)(ref row))..ctor(constant.Type, indexEncoder.EncodeToken(ownerToken), Metadata.BlobStream.GetBlobIndex(this, constant.Value, ErrorListener)); sortedTable.Add(constant, in row); } } private void AddImplementationMap(MetadataToken ownerToken, ImplementationMap? implementationMap) { //IL_002c: 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_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) if (implementationMap != null) { ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)28); IndexEncoder indexEncoder = Metadata.TablesStream.GetIndexEncoder((CodedIndex)64); ImplementationMapAttributes attributes = implementationMap.Attributes; uint num = indexEncoder.EncodeToken(ownerToken); uint stringIndex = Metadata.StringsStream.GetStringIndex(implementationMap.Name); MetadataToken moduleReferenceToken = GetModuleReferenceToken(implementationMap.Scope); ImplementationMapRow row = default(ImplementationMapRow); ((ImplementationMapRow)(ref row))..ctor(attributes, num, stringIndex, ((MetadataToken)(ref moduleReferenceToken)).Rid); sortedTable.Add(implementationMap, in row); } } private uint AddImplementation(IImplementation? implementation) { //IL_0027: 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_0051: 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_0066: 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_0037: 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) if (implementation == null) { return 0u; } MetadataToken val; if (!(implementation is AssemblyReference assembly)) { if (!(implementation is ExportedType exportedType)) { if (!(implementation is FileReference fileReference)) { throw new ArgumentOutOfRangeException("implementation"); } val = AddFileReference(fileReference); } else { val = AddExportedType(exportedType); } } else { val = GetAssemblyReferenceToken(assembly); } MetadataToken val2 = val; return Metadata.TablesStream.GetIndexEncoder((CodedIndex)65).EncodeToken(val2); } private void AddSecurityDeclarations(MetadataToken ownerToken, IHasSecurityDeclaration provider) { //IL_003a: 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) ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)14); IndexEncoder indexEncoder = Metadata.TablesStream.GetIndexEncoder((CodedIndex)60); SecurityDeclarationRow row = default(SecurityDeclarationRow); for (int i = 0; i < provider.SecurityDeclarations.Count; i++) { SecurityDeclaration securityDeclaration = provider.SecurityDeclarations[i]; ((SecurityDeclarationRow)(ref row))..ctor(securityDeclaration.Action, indexEncoder.EncodeToken(ownerToken), Metadata.BlobStream.GetBlobIndex(this, securityDeclaration.PermissionSet, ErrorListener)); sortedTable.Add(securityDeclaration, in row); } } private void AddFieldMarshal(MetadataToken ownerToken, IHasFieldMarshal owner) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (owner.MarshalDescriptor != null) { ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)13); IndexEncoder indexEncoder = Metadata.TablesStream.GetIndexEncoder((CodedIndex)59); FieldMarshalRow row = default(FieldMarshalRow); ((FieldMarshalRow)(ref row))..ctor(indexEncoder.EncodeToken(ownerToken), Metadata.BlobStream.GetBlobIndex(this, owner.MarshalDescriptor, ErrorListener)); sortedTable.Add(owner, in row); } } public DotNetDirectoryBuffer(ModuleDefinition module, IMethodBodySerializer methodBodySerializer, INativeSymbolsProvider symbolsProvider, IMetadataBuffer metadata, IErrorListener errorListener) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) Module = module ?? throw new ArgumentNullException("module"); MethodBodySerializer = methodBodySerializer ?? throw new ArgumentNullException("methodBodySerializer"); SymbolsProvider = symbolsProvider ?? throw new ArgumentNullException("symbolsProvider"); Metadata = metadata ?? throw new ArgumentNullException("metadata"); ErrorListener = errorListener ?? throw new ArgumentNullException("errorListener"); Resources = new DotNetResourcesDirectoryBuffer(); VTableFixups = new VTableFixupsBuffer(Platform.Get(module.MachineType), symbolsProvider); } private bool AssertIsImported([NotNullWhen(true)] IModuleProvider? member) { if (member == null) { return false; } if (member.Module != Module) { ErrorListener.RegisterException((Exception)new MemberNotImportedException((IMetadataMember)member)); return false; } return true; } public DotNetDirectoryBuildResult CreateDirectory() { //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_0022: 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_0050: 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_0061: 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_0083: Expected O, but got Unknown FinalizeInterfaces(); FinalizeGenericParameters(); ? val = new DotNetDirectory { Metadata = Metadata.CreateMetadata(), DotNetResources = ((Resources.Size != 0) ? Resources.CreateDirectory() : null), EntryPoint = GetEntryPoint(), Flags = Module.Attributes }; ? val2 = val; object obj; if (StrongNameSize <= 0) { obj = null; val = obj; obj = (object)val; } else { val = new DataSegment(new byte[StrongNameSize]); obj = (object)val; } ((DotNetDirectory)val2).StrongName = (IReadableSegment)val; ((DotNetDirectory)obj).VTableFixups = ((((Collection)(object)VTableFixups.Directory).Count > 0) ? VTableFixups.Directory : null); return new DotNetDirectoryBuildResult((IDotNetDirectory)obj, _tokenMapping); } private uint GetEntryPoint() { //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_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_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_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 //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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Invalid comparison between Unknown and I4 //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) if (Module.ManagedEntryPoint == null) { return 0u; } MetadataToken val = MetadataToken.Zero; MetadataToken metadataToken = Module.ManagedEntryPoint.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; if ((int)table != 6) { if ((int)table == 38) { val = AddFileReference((FileReference)Module.ManagedEntryPoint); } else { ErrorListener.MetadataBuilder("Invalid managed entry point " + Module.ManagedEntryPoint.SafeToString() + "."); } } else { val = GetMethodDefinitionToken(Module.ManagedEntryPointMethod); } return ((MetadataToken)(ref val)).ToUInt32(); } private void AddMethodSemantics(MetadataToken ownerToken, IHasSemantics provider) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < provider.Semantics.Count; i++) { AddMethodSemantics(ownerToken, provider.Semantics[i]); } } private void AddMethodSemantics(MetadataToken ownerToken, MethodSemantics semantics) { //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_0042: Unknown result type (might be due to invalid IL or missing references) ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)24); IndexEncoder indexEncoder = Metadata.TablesStream.GetIndexEncoder((CodedIndex)62); MethodSemanticsAttributes attributes = semantics.Attributes; MetadataToken methodDefinitionToken = GetMethodDefinitionToken(semantics.Method); MethodSemanticsRow row = default(MethodSemanticsRow); ((MethodSemanticsRow)(ref row))..ctor(attributes, ((MetadataToken)(ref methodDefinitionToken)).Rid, indexEncoder.EncodeToken(ownerToken)); sortedTable.Add(semantics, in row); } private void DefineInterfaces(MetadataToken ownerToken, IList interfaces) { ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)9); InterfaceImplementationRow row = default(InterfaceImplementationRow); for (int i = 0; i < interfaces.Count; i++) { InterfaceImplementation interfaceImplementation = interfaces[i]; ((InterfaceImplementationRow)(ref row))..ctor(((MetadataToken)(ref ownerToken)).Rid, GetTypeDefOrRefIndex(interfaceImplementation.Interface)); sortedTable.Add(interfaceImplementation, in row); } } private void FinalizeInterfaces() { //IL_0030: 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_003d: 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) ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)9); sortedTable.Sort(); foreach (InterfaceImplementation member in sortedTable.GetMembers()) { MetadataToken newToken = sortedTable.GetNewToken(member); _tokenMapping.Register(member, newToken); AddCustomAttributes(newToken, member); } } private void DefineGenericParameters(MetadataToken ownerToken, IHasGenericParameters provider) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < provider.GenericParameters.Count; i++) { DefineGenericParameter(ownerToken, provider.GenericParameters[i]); } } private void DefineGenericParameter(MetadataToken ownerToken, GenericParameter parameter) { //IL_0038: 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) if (AssertIsImported(parameter)) { ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)42); IndexEncoder indexEncoder = Metadata.TablesStream.GetIndexEncoder((CodedIndex)68); GenericParameterRow row = default(GenericParameterRow); ((GenericParameterRow)(ref row))..ctor(parameter.Number, parameter.Attributes, indexEncoder.EncodeToken(ownerToken), Metadata.StringsStream.GetStringIndex(parameter.Name)); sortedTable.Add(parameter, in row); } } private void FinalizeGenericParameters() { //IL_0030: 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_003d: 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_0064: Unknown result type (might be due to invalid IL or missing references) ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)42); sortedTable.Sort(); foreach (GenericParameter member in sortedTable.GetMembers()) { MetadataToken newToken = sortedTable.GetNewToken(member); _tokenMapping.Register(member, newToken); AddCustomAttributes(newToken, member); foreach (GenericParameterConstraint constraint in member.Constraints) { AddGenericParameterConstraint(newToken, constraint); } } } private void AddGenericParameterConstraint(MetadataToken ownerToken, GenericParameterConstraint? constraint) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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) if (constraint != null) { IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)44); GenericParameterConstraintRow row = default(GenericParameterConstraintRow); ((GenericParameterConstraintRow)(ref row))..ctor(((MetadataToken)(ref ownerToken)).Rid, GetTypeDefOrRefIndex(constraint.Constraint)); MetadataToken val = table.Add(in row); _tokenMapping.Register(constraint, val); AddCustomAttributes(val, constraint); } } private void AddClassLayout(MetadataToken ownerToken, ClassLayout? layout) { if (layout != null) { ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)15); ClassLayoutRow row = default(ClassLayoutRow); ((ClassLayoutRow)(ref row))..ctor(layout.PackingSize, layout.ClassSize, ((MetadataToken)(ref ownerToken)).Rid); sortedTable.Add(layout, in row); } } public void DefineAssembly(AssemblyDefinition assembly) { //IL_0015: 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_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) //IL_00a6: 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_00b5: Unknown result type (might be due to invalid IL or missing references) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)32); AssemblyDefinitionRow row = default(AssemblyDefinitionRow); ((AssemblyDefinitionRow)(ref row))..ctor(assembly.HashAlgorithm, (ushort)assembly.Version.Major, (ushort)assembly.Version.Minor, (ushort)assembly.Version.Build, (ushort)assembly.Version.Revision, assembly.Attributes, Metadata.BlobStream.GetBlobIndex(assembly.PublicKey), Metadata.StringsStream.GetStringIndex(assembly.Name), Metadata.StringsStream.GetStringIndex(assembly.Culture)); MetadataToken val = table.Add(in row); _tokenMapping.Register(assembly, val); AddCustomAttributes(val, assembly); AddSecurityDeclarations(val, assembly); } public void DefineModule(ModuleDefinition module) { //IL_0068: 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_0075: Unknown result type (might be due to invalid IL or missing references) StringsStreamBuffer stringsStream = Metadata.StringsStream; GuidStreamBuffer guidStream = Metadata.GuidStream; IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)0); ModuleDefinitionRow row = default(ModuleDefinitionRow); ((ModuleDefinitionRow)(ref row))..ctor(module.Generation, stringsStream.GetStringIndex(module.Name), guidStream.GetGuidIndex(module.Mvid), guidStream.GetGuidIndex(module.EncId), guidStream.GetGuidIndex(module.EncBaseId)); MetadataToken newToken = table.Add(in row); _tokenMapping.Register(module, newToken); } public void FinalizeModule(ModuleDefinition module) { //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_003f: 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) MetadataToken ownerToken = _tokenMapping[module]; if (module.CorLibTypeFactory.CorLibScope is AssemblyReference assembly) { GetAssemblyReferenceToken(assembly); } AddFileReferencesInModule(module); AddExportedTypesInModule(module); AddResourcesInModule(module); AddCustomAttributes(ownerToken, module); } private void AddResourcesInModule(ModuleDefinition module) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < module.Resources.Count; i++) { AddManifestResource(module.Resources[i]); } } public MetadataToken AddManifestResource(ManifestResource resource) { //IL_0086: 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_00c1: 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_00cf: 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_002d: Expected O, but got Unknown uint num = resource.Offset; if (resource.IsEmbedded) { ISegment embeddedDataSegment = resource.EmbeddedDataSegment; if (embeddedDataSegment != null) { using MemoryStream memoryStream = new MemoryStream(); ((IWritable)embeddedDataSegment).Write((IBinaryStreamWriter)new BinaryStreamWriter((Stream)memoryStream)); num = Resources.GetResourceDataOffset(memoryStream.ToArray()); } else { ErrorListener.MetadataBuilder("Embedded resource " + resource.SafeToString() + " does not have any contents."); num = 0u; } } IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)40); ManifestResourceRow row = default(ManifestResourceRow); ((ManifestResourceRow)(ref row))..ctor(num, resource.Attributes, Metadata.StringsStream.GetStringIndex(resource.Name), AddImplementation(resource.Implementation)); MetadataToken val = table.Add(in row); _tokenMapping.Register(resource, val); AddCustomAttributes(val, resource); return val; } public void DefineTypes(IEnumerable types) { //IL_005a: 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_009d: 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_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)2); ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)41); if (types is ICollection collection) { table.EnsureCapacity(table.Count + collection.Count); } TypeDefinitionRow row = default(TypeDefinitionRow); NestedClassRow row2 = default(NestedClassRow); foreach (TypeDefinition type in types) { ((TypeDefinitionRow)(ref row))..ctor(type.Attributes, Metadata.StringsStream.GetStringIndex(type.Name), Metadata.StringsStream.GetStringIndex(type.Namespace), 0u, 0u, 0u); MetadataToken newToken = table.Add(in row); _tokenMapping.Register(type, newToken); if (type.IsNested) { MetadataToken typeDefinitionToken = GetTypeDefinitionToken(type.DeclaringType); if (((MetadataToken)(ref typeDefinitionToken)).Rid == 0) { ErrorListener.MetadataBuilder($"Nested type {type.SafeToString()} is added before its enclosing class {type.DeclaringType.SafeToString()}."); } ((NestedClassRow)(ref row2))..ctor(((MetadataToken)(ref newToken)).Rid, ((MetadataToken)(ref typeDefinitionToken)).Rid); sortedTable.Add(type, in row2); } } } public void DefineFields(IEnumerable fields) { //IL_0042: 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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)4); if (fields is ICollection collection) { table.EnsureCapacity(table.Count + collection.Count); } FieldDefinitionRow row = default(FieldDefinitionRow); foreach (FieldDefinition field in fields) { ((FieldDefinitionRow)(ref row))..ctor(field.Attributes, Metadata.StringsStream.GetStringIndex(field.Name), Metadata.BlobStream.GetBlobIndex(this, field.Signature, ErrorListener)); MetadataToken newToken = table.Add(in row); _tokenMapping.Register(field, newToken); } } public void DefineMethods(IEnumerable methods) { //IL_004a: 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_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_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)6); if (methods is ICollection collection) { table.EnsureCapacity(table.Count + collection.Count); } MethodDefinitionRow row = default(MethodDefinitionRow); foreach (MethodDefinition method in methods) { ((MethodDefinitionRow)(ref row))..ctor(SegmentReference.Null, method.ImplAttributes, method.Attributes, Metadata.StringsStream.GetStringIndex(method.Name), Metadata.BlobStream.GetBlobIndex(this, method.Signature, ErrorListener), 0u); MetadataToken val = table.Add(in row); _tokenMapping.Register(method, val); if (method.ExportInfo.HasValue) { VTableFixups.MapTokenToExport(method.ExportInfo.Value, val); } } } public void DefineParameters(IEnumerable parameters) { //IL_0042: 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_0070: 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) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)8); if (parameters is ICollection collection) { table.EnsureCapacity(table.Count + collection.Count); } ParameterDefinitionRow row = default(ParameterDefinitionRow); foreach (ParameterDefinition parameter in parameters) { ((ParameterDefinitionRow)(ref row))..ctor(parameter.Attributes, parameter.Sequence, Metadata.StringsStream.GetStringIndex(parameter.Name)); MetadataToken newToken = table.Add(in row); _tokenMapping.Register(parameter, newToken); } } public void DefineProperties(IEnumerable properties) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: 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) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)23); if (properties is ICollection collection) { table.EnsureCapacity(table.Count + collection.Count); } PropertyDefinitionRow row = default(PropertyDefinitionRow); foreach (PropertyDefinition property in properties) { ((PropertyDefinitionRow)(ref row))..ctor(property.Attributes, Metadata.StringsStream.GetStringIndex(property.Name), Metadata.BlobStream.GetBlobIndex(this, property.Signature, ErrorListener)); MetadataToken newToken = table.Add(in row); _tokenMapping.Register(property, newToken); } } public void DefineEvents(IEnumerable events) { //IL_0043: 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_0077: 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) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)20); if (events is ICollection collection) { table.EnsureCapacity(table.Count + collection.Count); } EventDefinitionRow row = default(EventDefinitionRow); foreach (EventDefinition @event in events) { ((EventDefinitionRow)(ref row))..ctor(@event.Attributes, Metadata.StringsStream.GetStringIndex(@event.Name), GetTypeDefOrRefIndex(@event.EventType)); MetadataToken newToken = table.Add(in row); _tokenMapping.Register(@event, newToken); } } public void FinalizeTypes() { //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_015b: 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_0179: 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) TablesStreamBuffer tablesStream = Metadata.TablesStream; IMetadataTableBuffer table = tablesStream.GetTable((TableIndex)2); bool fieldPtrRequired = false; bool methodPtrRequired = false; bool paramPtrRequired = false; bool propertyPtrRequired = false; bool eventPtrRequired = false; uint num = 1u; uint num2 = 1u; uint propertyList = 1u; uint eventList = 1u; tablesStream.GetTable((TableIndex)3).EnsureCapacity(tablesStream.GetTable((TableIndex)4).Count); tablesStream.GetTable((TableIndex)5).EnsureCapacity(tablesStream.GetTable((TableIndex)6).Count); tablesStream.GetTable((TableIndex)7).EnsureCapacity(tablesStream.GetTable((TableIndex)8).Count); tablesStream.GetTable((TableIndex)22).EnsureCapacity(tablesStream.GetTable((TableIndex)23).Count); tablesStream.GetTable((TableIndex)19).EnsureCapacity(tablesStream.GetTable((TableIndex)20).Count); MetadataToken val = default(MetadataToken); for (uint num3 = 1u; num3 <= table.Count; num3++) { ((MetadataToken)(ref val))..ctor((TableIndex)2, num3); TypeDefinition typeByToken = _tokenMapping.GetTypeByToken(val); ref TypeDefinitionRow rowRef = ref table.GetRowRef(num3); ((TypeDefinitionRow)(ref rowRef)).Extends = GetTypeDefOrRefIndex(typeByToken.BaseType); ((TypeDefinitionRow)(ref rowRef)).FieldList = num; ((TypeDefinitionRow)(ref rowRef)).MethodList = num2; FinalizeFieldsInType(typeByToken, ref fieldPtrRequired); AddMethodPointers(typeByToken, ref methodPtrRequired); FinalizePropertiesInType(typeByToken, num3, ref propertyList, ref propertyPtrRequired); FinalizeEventsInType(typeByToken, num3, ref eventList, ref eventPtrRequired); num += (uint)typeByToken.Fields.Count; num2 += (uint)typeByToken.Methods.Count; AddCustomAttributes(val, typeByToken); AddSecurityDeclarations(val, typeByToken); DefineInterfaces(val, typeByToken.Interfaces); AddMethodImplementations(val, typeByToken.MethodImplementations); DefineGenericParameters(val, typeByToken); AddClassLayout(val, typeByToken.ClassLayout); } FinalizeMethods(ref paramPtrRequired); if (!fieldPtrRequired) { tablesStream.GetTable((TableIndex)3).Clear(); } if (!methodPtrRequired) { tablesStream.GetTable((TableIndex)5).Clear(); } if (!paramPtrRequired) { tablesStream.GetTable((TableIndex)7).Clear(); } if (!propertyPtrRequired) { tablesStream.GetTable((TableIndex)22).Clear(); } if (!eventPtrRequired) { tablesStream.GetTable((TableIndex)19).Clear(); } } private void FinalizeFieldsInType(TypeDefinition type, ref bool fieldPtrRequired) { //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_002e: 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_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: 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_0089: 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_009e: 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_00b3: 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) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)3); for (int i = 0; i < type.Fields.Count; i++) { FieldDefinition fieldDefinition = type.Fields[i]; MetadataToken fieldDefinitionToken = GetFieldDefinitionToken(fieldDefinition); if (fieldDefinitionToken == MetadataToken.Zero) { ErrorListener.MetadataBuilder("An attempt was made to finalize field " + fieldDefinition.SafeToString() + ", which was not added to the .NET directory buffer yet."); } if (((MetadataToken)(ref fieldDefinitionToken)).Rid != table.Count + 1) { fieldPtrRequired = true; } FieldPointerRow row = new FieldPointerRow(((MetadataToken)(ref fieldDefinitionToken)).Rid); table.Add(in row); AddCustomAttributes(fieldDefinitionToken, fieldDefinition); AddConstant(fieldDefinitionToken, fieldDefinition.Constant); AddImplementationMap(fieldDefinitionToken, fieldDefinition.ImplementationMap); AddFieldRva(fieldDefinitionToken, fieldDefinition); AddFieldLayout(fieldDefinitionToken, fieldDefinition); AddFieldMarshal(fieldDefinitionToken, fieldDefinition); } } private void AddMethodPointers(TypeDefinition type, ref bool methodPtrRequired) { //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_002b: 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_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_007f: Unknown result type (might be due to invalid IL or missing references) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)5); for (int i = 0; i < type.Methods.Count; i++) { MethodDefinition methodDefinition = type.Methods[i]; MetadataToken methodDefinitionToken = GetMethodDefinitionToken(methodDefinition); if (methodDefinitionToken == MetadataToken.Zero) { ErrorListener.MetadataBuilder("An attempt was made to finalize method " + methodDefinition.SafeToString() + ", which was not added to the .NET directory buffer yet."); } if (((MetadataToken)(ref methodDefinitionToken)).Rid != table.Count + 1) { methodPtrRequired = true; } MethodPointerRow row = new MethodPointerRow(((MetadataToken)(ref methodDefinitionToken)).Rid); table.Add(in row); } } private void FinalizeMethods(ref bool paramPtrRequired) { //IL_003a: 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_007a: 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_0093: Unknown result type (might be due to invalid IL or missing references) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)6); MethodBodySerializationContext context = new MethodBodySerializationContext(this, SymbolsProvider, ErrorListener); uint paramList = 1u; MetadataToken val = default(MetadataToken); for (uint num = 1u; num <= table.Count; num++) { ((MetadataToken)(ref val))..ctor((TableIndex)6, num); MethodDefinition methodByToken = _tokenMapping.GetMethodByToken(val); ref MethodDefinitionRow rowRef = ref table.GetRowRef(num); ((MethodDefinitionRow)(ref rowRef)).Body = MethodBodySerializer.SerializeMethodBody(context, methodByToken); ((MethodDefinitionRow)(ref rowRef)).ParameterList = paramList; FinalizeParametersInMethod(methodByToken, ref paramList, ref paramPtrRequired); AddCustomAttributes(val, methodByToken); AddSecurityDeclarations(val, methodByToken); AddImplementationMap(val, methodByToken.ImplementationMap); DefineGenericParameters(val, methodByToken); } } private void FinalizeParametersInMethod(MethodDefinition method, ref uint paramList, ref bool paramPtrRequired) { //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_002e: 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_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) //IL_00bc: 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_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)7); for (int i = 0; i < method.ParameterDefinitions.Count; i++) { ParameterDefinition parameterDefinition = method.ParameterDefinitions[i]; MetadataToken parameterDefinitionToken = GetParameterDefinitionToken(parameterDefinition); if (parameterDefinitionToken == MetadataToken.Zero) { ErrorListener.MetadataBuilder($"An attempt was made to finalize parameter {parameterDefinition.SafeToString()} in {method.SafeToString()}, which was not added to the .NET directory buffer yet."); } if (((MetadataToken)(ref parameterDefinitionToken)).Rid != table.Count + 1) { paramPtrRequired = true; } ParameterPointerRow row = new ParameterPointerRow(((MetadataToken)(ref parameterDefinitionToken)).Rid); table.Add(in row); AddCustomAttributes(parameterDefinitionToken, parameterDefinition); AddConstant(parameterDefinitionToken, parameterDefinition.Constant); AddFieldMarshal(parameterDefinitionToken, parameterDefinition); } paramList += (uint)method.ParameterDefinitions.Count; } private void FinalizePropertiesInType(TypeDefinition type, uint typeRid, ref uint propertyList, ref bool propertyPtrRequired) { //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_0053: 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_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_00aa: 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_00bb: 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) if (type.Properties.Count == 0) { return; } ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)21); IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)22); for (int i = 0; i < type.Properties.Count; i++) { PropertyDefinition propertyDefinition = type.Properties[i]; MetadataToken propertyDefinitionToken = GetPropertyDefinitionToken(propertyDefinition); if (propertyDefinitionToken == MetadataToken.Zero) { ErrorListener.MetadataBuilder("An attempt was made to finalize property " + propertyDefinition.SafeToString() + ", which was not added to the .NET directory buffer yet."); } if (((MetadataToken)(ref propertyDefinitionToken)).Rid != table.Count + 1) { propertyPtrRequired = true; } PropertyPointerRow row = new PropertyPointerRow(((MetadataToken)(ref propertyDefinitionToken)).Rid); table.Add(in row); AddCustomAttributes(propertyDefinitionToken, propertyDefinition); AddMethodSemantics(propertyDefinitionToken, propertyDefinition); AddConstant(propertyDefinitionToken, propertyDefinition.Constant); } PropertyMapRow row2 = default(PropertyMapRow); ((PropertyMapRow)(ref row2))..ctor(typeRid, propertyList); sortedTable.Add(type, in row2); propertyList += (uint)type.Properties.Count; } private void FinalizeEventsInType(TypeDefinition type, uint typeRid, ref uint eventList, ref bool eventPtrRequired) { //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_0053: 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_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_00aa: 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_00bb: Unknown result type (might be due to invalid IL or missing references) if (type.Events.Count == 0) { return; } ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)18); IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)19); for (int i = 0; i < type.Events.Count; i++) { EventDefinition eventDefinition = type.Events[i]; MetadataToken eventDefinitionToken = GetEventDefinitionToken(eventDefinition); if (eventDefinitionToken == MetadataToken.Zero) { ErrorListener.MetadataBuilder("An attempt was made to finalize event " + eventDefinition.SafeToString() + ", which was not added to the .NET directory buffer yet."); } if (((MetadataToken)(ref eventDefinitionToken)).Rid != table.Count + 1) { eventPtrRequired = true; } EventPointerRow row = new EventPointerRow(((MetadataToken)(ref eventDefinitionToken)).Rid); table.Add(in row); AddCustomAttributes(eventDefinitionToken, eventDefinition); AddMethodSemantics(eventDefinitionToken, eventDefinition); } EventMapRow row2 = default(EventMapRow); ((EventMapRow)(ref row2))..ctor(typeRid, eventList); sortedTable.Add(type, in row2); eventList += (uint)type.Events.Count; } private void AddMethodImplementations(MetadataToken typeToken, IList implementations) { ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)25); MethodImplementationRow row = default(MethodImplementationRow); for (int i = 0; i < implementations.Count; i++) { MethodImplementation originalMember = implementations[i]; ((MethodImplementationRow)(ref row))..ctor(((MetadataToken)(ref typeToken)).Rid, AddMethodDefOrRef(originalMember.Body), AddMethodDefOrRef(originalMember.Declaration)); sortedTable.Add(originalMember, in row); } } private void AddFieldRva(MetadataToken ownerToken, FieldDefinition field) { if (field.FieldRva != null) { ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)29); FieldRvaRow row = default(FieldRvaRow); ((FieldRvaRow)(ref row))..ctor(Extensions.ToReference(field.FieldRva), ((MetadataToken)(ref ownerToken)).Rid); sortedTable.Add(field, in row); } } private void AddFieldLayout(MetadataToken ownerToken, FieldDefinition field) { if (field.FieldOffset.HasValue) { ISortedMetadataTableBuffer sortedTable = Metadata.TablesStream.GetSortedTable((TableIndex)16); FieldLayoutRow row = default(FieldLayoutRow); ((FieldLayoutRow)(ref row))..ctor((uint)field.FieldOffset.Value, ((MetadataToken)(ref ownerToken)).Rid); sortedTable.Add(field, in row); } } private void AddExportedTypesInModule(ModuleDefinition module) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < module.ExportedTypes.Count; i++) { AddExportedType(module.ExportedTypes[i]); } } private MetadataToken AddExportedType(ExportedType exportedType) { //IL_0015: 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_0064: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)39); ExportedTypeRow row = default(ExportedTypeRow); ((ExportedTypeRow)(ref row))..ctor(exportedType.Attributes, exportedType.TypeDefId, Metadata.StringsStream.GetStringIndex(exportedType.Name), Metadata.StringsStream.GetStringIndex(exportedType.Namespace), AddImplementation(exportedType.Implementation)); MetadataToken val = table.Add(in row); _tokenMapping.Register(exportedType, val); AddCustomAttributes(val, exportedType); return val; } private void AddFileReferencesInModule(ModuleDefinition module) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < module.FileReferences.Count; i++) { AddFileReference(module.FileReferences[i]); } } private MetadataToken AddFileReference(FileReference fileReference) { //IL_0015: 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) //IL_005a: 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_0068: Unknown result type (might be due to invalid IL or missing references) IMetadataTableBuffer table = Metadata.TablesStream.GetTable((TableIndex)38); FileReferenceRow row = default(FileReferenceRow); ((FileReferenceRow)(ref row))..ctor(fileReference.Attributes, Metadata.StringsStream.GetStringIndex(fileReference.Name), Metadata.BlobStream.GetBlobIndex(fileReference.HashValue)); MetadataToken val = table.Add(in row); _tokenMapping.Register(fileReference, val); AddCustomAttributes(val, fileReference); return val; } public uint GetUserStringIndex(string value) { return Metadata.UserStringsStream.GetStringIndex(value); } public MetadataToken GetTypeReferenceToken(TypeReference? type) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) return AddTypeReference(type, allowDuplicates: false, preserveRid: false); } public MetadataToken AddTypeReference(TypeReference? type, bool allowDuplicates, bool preserveRid) { //IL_0009: 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_0077: 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_0069: 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_008f: 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_009d: Unknown result type (might be due to invalid IL or missing references) if (!AssertIsImported(type)) { return MetadataToken.Zero; } DistinctMetadataTableBuffer distinctTable = Metadata.TablesStream.GetDistinctTable((TableIndex)1); TypeReferenceRow row = default(TypeReferenceRow); ((TypeReferenceRow)(ref row))..ctor(AddResolutionScope(type.Scope, allowDuplicates, preserveRid), Metadata.StringsStream.GetStringIndex(type.Name), Metadata.StringsStream.GetStringIndex(type.Namespace)); MetadataToken val; if (!preserveRid) { val = distinctTable.Add(in row, allowDuplicates); } else { MetadataToken metadataToken = type.MetadataToken; val = distinctTable.Insert(((MetadataToken)(ref metadataToken)).Rid, in row, allowDuplicates); } MetadataToken val2 = val; _tokenMapping.Register(type, val2); AddCustomAttributes(val2, type); return val2; } public MetadataToken GetTypeDefinitionToken(TypeDefinition? type) { //IL_0016: 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 (!AssertIsImported(type)) { return MetadataToken.Zero; } return _tokenMapping[type]; } public MetadataToken GetFieldDefinitionToken(FieldDefinition? field) { //IL_0016: 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 (!AssertIsImported(field)) { return MetadataToken.Zero; } return _tokenMapping[field]; } public MetadataToken GetMethodDefinitionToken(MethodDefinition? method) { //IL_0016: 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 (!AssertIsImported(method)) { return MetadataToken.Zero; } return _tokenMapping[method]; } public MetadataToken GetParameterDefinitionToken(ParameterDefinition? parameter) { //IL_0016: 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 (!AssertIsImported(parameter)) { return MetadataToken.Zero; } return _tokenMapping[parameter]; } public MetadataToken GetPropertyDefinitionToken(PropertyDefinition? property) { //IL_0016: 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 (!AssertIsImported(property)) { return MetadataToken.Zero; } return _tokenMapping[property]; } public MetadataToken GetEventDefinitionToken(EventDefinition? @event) { //IL_0016: 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 (!AssertIsImported(@event)) { return MetadataToken.Zero; } return _tokenMapping[@event]; } public MetadataToken GetMemberReferenceToken(MemberReference? member) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return AddMemberReference(member, allowDuplicates: false); } public MetadataToken AddMemberReference(MemberReference? member, bool allowDuplicates) { //IL_006a: 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_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0085: 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 (!AssertIsImported(member)) { return MetadataToken.Zero; } DistinctMetadataTableBuffer distinctTable = Metadata.TablesStream.GetDistinctTable((TableIndex)10); MemberReferenceRow row = default(MemberReferenceRow); ((MemberReferenceRow)(ref row))..ctor(AddMemberRefParent(member.Parent), Metadata.StringsStream.GetStringIndex(member.Name), Metadata.BlobStream.GetBlobIndex(this, member.Signature, ErrorListener)); MetadataToken val = distinctTable.Add(in row, allowDuplicates); _tokenMapping.Register(member, val); AddCustomAttributes(val, member); return val; } public MetadataToken GetStandAloneSignatureToken(StandAloneSignature? signature) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return AddStandAloneSignature(signature, allowDuplicates: false); } public MetadataToken AddStandAloneSignature(StandAloneSignature? signature, bool allowDuplicates) { //IL_0042: 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_004f: 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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) if (signature == null) { return MetadataToken.Zero; } DistinctMetadataTableBuffer distinctTable = Metadata.TablesStream.GetDistinctTable((TableIndex)17); StandAloneSignatureRow row = default(StandAloneSignatureRow); ((StandAloneSignatureRow)(ref row))..ctor(Metadata.BlobStream.GetBlobIndex(this, signature.Signature, ErrorListener)); MetadataToken val = distinctTable.Add(in row, allowDuplicates); _tokenMapping.Register(signature, val); AddCustomAttributes(val, signature); return val; } public MetadataToken GetAssemblyReferenceToken(AssemblyReference? assembly) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) return AddAssemblyReference(assembly, allowDuplicates: false, preserveRid: false); } public MetadataToken AddAssemblyReference(AssemblyReference? assembly, bool allowDuplicates, bool preserveRid) { //IL_000c: 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_00ca: 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_00da: 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_00df: 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_00e8: Unknown result type (might be due to invalid IL or missing references) if (assembly == null || !AssertIsImported(assembly)) { return MetadataToken.Zero; } DistinctMetadataTableBuffer distinctTable = Metadata.TablesStream.GetDistinctTable((TableIndex)35); AssemblyReferenceRow row = default(AssemblyReferenceRow); ((AssemblyReferenceRow)(ref row))..ctor((ushort)assembly.Version.Major, (ushort)assembly.Version.Minor, (ushort)assembly.Version.Build, (ushort)assembly.Version.Revision, assembly.Attributes, Metadata.BlobStream.GetBlobIndex(assembly.PublicKeyOrToken), Metadata.StringsStream.GetStringIndex(assembly.Name), Metadata.StringsStream.GetStringIndex(assembly.Culture), Metadata.BlobStream.GetBlobIndex(assembly.HashValue)); MetadataToken val; if (!preserveRid) { val = distinctTable.Add(in row, allowDuplicates); } else { MetadataToken metadataToken = assembly.MetadataToken; val = distinctTable.Insert(((MetadataToken)(ref metadataToken)).Rid, in row, allowDuplicates); } MetadataToken val2 = val; AddCustomAttributes(val2, assembly); return val2; } public MetadataToken GetModuleReferenceToken(ModuleReference? reference) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) return AddModuleReference(reference, allowDuplicates: false, preserveRid: false); } public MetadataToken AddModuleReference(ModuleReference? reference, bool allowDuplicates, bool preserveRid) { //IL_0009: 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_0054: 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_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0066: 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) if (!AssertIsImported(reference)) { return MetadataToken.Zero; } DistinctMetadataTableBuffer distinctTable = Metadata.TablesStream.GetDistinctTable((TableIndex)26); ModuleReferenceRow row = default(ModuleReferenceRow); ((ModuleReferenceRow)(ref row))..ctor(Metadata.StringsStream.GetStringIndex(reference.Name)); MetadataToken val; if (!preserveRid) { val = distinctTable.Add(in row, allowDuplicates); } else { MetadataToken metadataToken = reference.MetadataToken; val = distinctTable.Insert(((MetadataToken)(ref metadataToken)).Rid, in row, allowDuplicates); } MetadataToken val2 = val; AddCustomAttributes(val2, reference); return val2; } public MetadataToken GetTypeSpecificationToken(TypeSpecification? type) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return AddTypeSpecification(type, allowDuplicates: false); } public MetadataToken AddTypeSpecification(TypeSpecification? type, bool allowDuplicates) { //IL_0048: 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_0055: 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_0063: 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 (!AssertIsImported(type)) { return MetadataToken.Zero; } DistinctMetadataTableBuffer distinctTable = Metadata.TablesStream.GetDistinctTable((TableIndex)27); TypeSpecificationRow row = default(TypeSpecificationRow); ((TypeSpecificationRow)(ref row))..ctor(Metadata.BlobStream.GetBlobIndex(this, type.Signature, ErrorListener)); MetadataToken val = distinctTable.Add(in row, allowDuplicates); _tokenMapping.Register(type, val); AddCustomAttributes(val, type); return val; } public MetadataToken GetMethodSpecificationToken(MethodSpecification? method) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return AddMethodSpecification(method, allowDuplicates: false); } public MetadataToken AddMethodSpecification(MethodSpecification? method, bool allowDuplicates) { //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_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006f: 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 (!AssertIsImported(method)) { return MetadataToken.Zero; } DistinctMetadataTableBuffer distinctTable = Metadata.TablesStream.GetDistinctTable((TableIndex)43); MethodSpecificationRow row = default(MethodSpecificationRow); ((MethodSpecificationRow)(ref row))..ctor(AddMethodDefOrRef(method.Method), Metadata.BlobStream.GetBlobIndex(this, method.Signature, ErrorListener)); MetadataToken val = distinctTable.Add(in row, allowDuplicates); _tokenMapping.Register(method, val); AddCustomAttributes(val, method); return val; } } public class DotNetDirectoryBuildResult { public IDotNetDirectory Directory { get; } public ITokenMapping TokenMapping { get; } public DotNetDirectoryBuildResult(IDotNetDirectory directory, ITokenMapping mapping) { Directory = directory ?? throw new ArgumentNullException("directory"); TokenMapping = mapping ?? throw new ArgumentNullException("mapping"); } } public class DotNetDirectoryFactory : IDotNetDirectoryFactory { public MetadataBuilderFlags MetadataBuilderFlags { get; set; } public IMethodBodySerializer MethodBodySerializer { get; set; } public StrongNamePrivateKey? StrongNamePrivateKey { get; set; } public DotNetDirectoryFactory() : this(MetadataBuilderFlags.None) { } public DotNetDirectoryFactory(MetadataBuilderFlags metadataBuilderFlags) { MetadataBuilderFlags = metadataBuilderFlags; MethodBodySerializer = new MultiMethodBodySerializer(new CilMethodBodySerializer(), new NativeMethodBodySerializer()); } public virtual DotNetDirectoryBuildResult CreateDotNetDirectory(ModuleDefinition module, INativeSymbolsProvider symbolsProvider, DiagnosticBag diagnosticBag) { //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) MemberDiscoveryResult memberDiscoveryResult = DiscoverMemberDefinitionsInModule(module); DotNetDirectoryBuffer dotNetDirectoryBuffer = CreateDotNetDirectoryBuffer(module, symbolsProvider, diagnosticBag); dotNetDirectoryBuffer.DefineModule(module); ImportBasicTablesIfSpecified(module, dotNetDirectoryBuffer); dotNetDirectoryBuffer.DefineTypes(memberDiscoveryResult.Types); ImportTypeSpecsAndMemberRefsIfSpecified(module, dotNetDirectoryBuffer); dotNetDirectoryBuffer.DefineFields(memberDiscoveryResult.Fields); dotNetDirectoryBuffer.DefineMethods(memberDiscoveryResult.Methods); dotNetDirectoryBuffer.DefineProperties(memberDiscoveryResult.Properties); dotNetDirectoryBuffer.DefineEvents(memberDiscoveryResult.Events); dotNetDirectoryBuffer.DefineParameters(memberDiscoveryResult.Parameters); ImportRemainingTablesIfSpecified(module, dotNetDirectoryBuffer); dotNetDirectoryBuffer.FinalizeTypes(); if (module.Assembly?.ManifestModule == module) { dotNetDirectoryBuffer.DefineAssembly(module.Assembly); } dotNetDirectoryBuffer.FinalizeModule(module); if (StrongNamePrivateKey != null) { dotNetDirectoryBuffer.StrongNameSize = ((StrongNamePublicKey)StrongNamePrivateKey).Modulus.Length; } else { byte[] array = module.Assembly?.PublicKey; if (array != null) { dotNetDirectoryBuffer.StrongNameSize = array.Length - 32; } else if ((module.Attributes & 8) != 0) { dotNetDirectoryBuffer.StrongNameSize = 128; } } DotNetDirectoryBuildResult dotNetDirectoryBuildResult = dotNetDirectoryBuffer.CreateDirectory(); if (module is SerializedModuleDefinition serializedModule && (MetadataBuilderFlags & (MetadataBuilderFlags.PreserveUnknownStreams | MetadataBuilderFlags.PreserveStreamOrder)) != 0) { ReorderMetadataStreams(serializedModule, dotNetDirectoryBuildResult.Directory.Metadata); } return dotNetDirectoryBuildResult; } private MemberDiscoveryResult DiscoverMemberDefinitionsInModule(ModuleDefinition module) { MemberDiscoveryFlags memberDiscoveryFlags = MemberDiscoveryFlags.None; if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveTypeDefinitionIndices) != 0) { memberDiscoveryFlags |= MemberDiscoveryFlags.PreserveTypeOrder; } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveFieldDefinitionIndices) != 0) { memberDiscoveryFlags |= MemberDiscoveryFlags.PreserveFieldOrder; } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveMethodDefinitionIndices) != 0) { memberDiscoveryFlags |= MemberDiscoveryFlags.PreserveMethodOrder; } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveParameterDefinitionIndices) != 0) { memberDiscoveryFlags |= MemberDiscoveryFlags.PreserveParameterOrder; } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreservePropertyDefinitionIndices) != 0) { memberDiscoveryFlags |= MemberDiscoveryFlags.PreservePropertyOrder; } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveEventDefinitionIndices) != 0) { memberDiscoveryFlags |= MemberDiscoveryFlags.PreserveEventOrder; } return MemberDiscoverer.DiscoverMembersInModule(module, memberDiscoveryFlags); } private DotNetDirectoryBuffer CreateDotNetDirectoryBuffer(ModuleDefinition module, INativeSymbolsProvider symbolsProvider, DiagnosticBag diagnosticBag) { IMetadataBuffer metadata = CreateMetadataBuffer(module); return new DotNetDirectoryBuffer(module, MethodBodySerializer, symbolsProvider, metadata, (IErrorListener)(object)diagnosticBag); } private IMetadataBuffer CreateMetadataBuffer(ModuleDefinition module) { MetadataBuffer metadataBuffer = new MetadataBuffer(module.RuntimeVersion) { OptimizeStringIndices = ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveUnknownStreams) == 0) }; IDotNetDirectory? dotNetDirectory = module.DotNetDirectory; IMetadata val = ((dotNetDirectory != null) ? dotNetDirectory.Metadata : null); if (val == null) { return metadataBuffer; } BlobStream stream = default(BlobStream); if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveBlobIndices) != 0 && val.TryGetStream(ref stream)) { metadataBuffer.BlobStream.ImportStream(stream); } GuidStream stream2 = default(GuidStream); if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveGuidIndices) != 0 && val.TryGetStream(ref stream2)) { metadataBuffer.GuidStream.ImportStream(stream2); } StringsStream stream3 = default(StringsStream); if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveStringIndices) != 0 && val.TryGetStream(ref stream3)) { metadataBuffer.StringsStream.ImportStream(stream3); } UserStringsStream stream4 = default(UserStringsStream); if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveUserStringIndices) != 0 && val.TryGetStream(ref stream4)) { metadataBuffer.UserStringsStream.ImportStream(stream4); } return metadataBuffer; } private void ImportBasicTablesIfSpecified(ModuleDefinition module, DotNetDirectoryBuffer buffer) { DotNetDirectoryBuffer buffer2 = buffer; if (module.DotNetDirectory == null) { return; } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveAssemblyReferenceIndices) != 0) { ImportTables(module, (TableIndex)35, (AssemblyReference r) => buffer2.AddAssemblyReference(r, allowDuplicates: true, preserveRid: true)); } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveModuleReferenceIndices) != 0) { ImportTables(module, (TableIndex)26, (ModuleReference r) => buffer2.AddModuleReference(r, allowDuplicates: true, preserveRid: true)); } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveTypeReferenceIndices) != 0) { ImportTables(module, (TableIndex)1, (TypeReference r) => buffer2.AddTypeReference(r, allowDuplicates: true, preserveRid: true)); } } private void ImportTypeSpecsAndMemberRefsIfSpecified(ModuleDefinition module, DotNetDirectoryBuffer buffer) { DotNetDirectoryBuffer buffer2 = buffer; if (module.DotNetDirectory == null) { return; } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveTypeSpecificationIndices) != 0) { ImportTables(module, (TableIndex)27, (TypeSpecification s) => buffer2.AddTypeSpecification(s, allowDuplicates: true)); } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveMemberReferenceIndices) != 0) { ImportTables(module, (TableIndex)10, (MemberReference r) => buffer2.AddMemberReference(r, allowDuplicates: true)); } } private void ImportRemainingTablesIfSpecified(ModuleDefinition module, DotNetDirectoryBuffer buffer) { DotNetDirectoryBuffer buffer2 = buffer; if (module.DotNetDirectory == null) { return; } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveStandAloneSignatureIndices) != 0) { ImportTables(module, (TableIndex)17, (StandAloneSignature s) => buffer2.AddStandAloneSignature(s, allowDuplicates: true)); } if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveMethodSpecificationIndices) != 0) { ImportTables(module, (TableIndex)43, (MethodSpecification s) => buffer2.AddMethodSpecification(s, allowDuplicates: true)); } } private static void ImportTables(ModuleDefinition module, TableIndex tableIndex, Func importAction) { //IL_0010: 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_0024: 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_0049: 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) int count = ((ICollection)module.DotNetDirectory.Metadata.GetStream().GetTable(tableIndex)).Count; for (uint num = 1u; num <= count; num++) { importAction((TMember)module.LookupMember(new MetadataToken(tableIndex, num))); } foreach (IMetadataMember assignee in module.TokenAllocator.GetAssignees(tableIndex)) { importAction((TMember)assignee); } } private void ReorderMetadataStreams(SerializedModuleDefinition serializedModule, IMetadata newMetadata) { IMetadata newMetadata2 = newMetadata; ModuleReaderContext readerContext = serializedModule.ReaderContext; (int, IMetadataStream)[] array = new(int, IMetadataStream)[5] { (readerContext.TablesStreamIndex, GetStreamOrNull()), (readerContext.BlobStreamIndex, GetStreamOrNull()), (readerContext.GuidStreamIndex, GetStreamOrNull()), (readerContext.StringsStreamIndex, GetStreamOrNull()), (readerContext.UserStringsStreamIndex, GetStreamOrNull()) }; if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveUnknownStreams) != 0) { IList streams = serializedModule.DotNetDirectory.Metadata.Streams; if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveStreamOrder) != 0) { newMetadata2.Streams.Clear(); int j; for (j = 0; j < streams.Count; j++) { (int, IMetadataStream) tuple = array.FirstOrDefault(((int Index, IMetadataStream Stream) x) => x.Index == j); newMetadata2.Streams.Insert(j, tuple.Item2 ?? streams[j]); } return; } int i; for (i = 0; i < streams.Count; i++) { if (array.All(((int Index, IMetadataStream Stream) x) => x.Index != i)) { newMetadata2.Streams.Add(streams[i]); } } } else { if ((MetadataBuilderFlags & MetadataBuilderFlags.PreserveStreamOrder) == 0) { return; } Array.Sort(array, ((int Index, IMetadataStream Stream) a, (int Index, IMetadataStream Stream) b) => a.Index.CompareTo(b.Index)); newMetadata2.Streams.Clear(); for (int k = 0; k < array.Length; k++) { IMetadataStream item = array[k].Item2; if (item != null) { newMetadata2.Streams.Add(item); } } } IMetadataStream? GetStreamOrNull() where TStream : class?, IMetadataStream { TStream val = default(TStream); return (IMetadataStream?)(object)(newMetadata2.TryGetStream(ref val) ? val : null); } } } public interface IDotNetDirectoryFactory { DotNetDirectoryBuildResult CreateDotNetDirectory(ModuleDefinition module, INativeSymbolsProvider symbolsProvider, DiagnosticBag diagnosticBag); } public interface IPEImageBuilder { PEImageBuildResult CreateImage(ModuleDefinition module); } public interface ITokenMapping { MetadataToken this[IMetadataMember member] { get; } bool TryGetNewToken(IMetadataMember member, out MetadataToken token); } public class ManagedPEImageBuilder : IPEImageBuilder { public IDotNetDirectoryFactory DotNetDirectoryFactory { get; set; } public ManagedPEImageBuilder() : this(new DotNetDirectoryFactory()) { } public ManagedPEImageBuilder(MetadataBuilderFlags metadataBuilderFlags) : this(new DotNetDirectoryFactory(metadataBuilderFlags)) { } public ManagedPEImageBuilder(IDotNetDirectoryFactory factory) { DotNetDirectoryFactory = factory ?? throw new ArgumentNullException("factory"); } public PEImageBuildResult CreateImage(ModuleDefinition module) { //IL_000a: 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_0011: 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_001d: 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_0029: 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_0035: 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_0041: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown //IL_0104: 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) //IL_0116: Expected O, but got Unknown //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) PEImageBuildContext pEImageBuildContext = new PEImageBuildContext(); PEImage val = null; ITokenMapping tokenMapping = null; try { val = new PEImage { MachineType = module.MachineType, PEKind = module.PEKind, Characteristics = module.FileCharacteristics, SubSystem = module.SubSystem, DllCharacteristics = module.DllCharacteristics, Resources = module.NativeResourceDirectory, TimeDateStamp = module.TimeDateStamp }; NativeSymbolsProvider nativeSymbolsProvider = new NativeSymbolsProvider(); DotNetDirectoryBuildResult dotNetDirectoryBuildResult = DotNetDirectoryFactory.CreateDotNetDirectory(module, nativeSymbolsProvider, pEImageBuildContext.DiagnosticBag); val.DotNetDirectory = dotNetDirectoryBuildResult.Directory; tokenMapping = dotNetDirectoryBuildResult.TokenMapping; foreach (IImportedModule importedModule in nativeSymbolsProvider.GetImportedModules()) { val.Imports.Add(importedModule); } uint baseOrdinal; ExportedSymbol[] array = nativeSymbolsProvider.GetExportedSymbols(out baseOrdinal).ToArray(); if (array.Length != 0) { val.Exports = (IExportDirectory)new ExportDirectory((!Utf8String.IsNullOrEmpty(module.Name)) ? Utf8String.op_Implicit(module.Name) : string.Empty) { BaseOrdinal = baseOrdinal }; ExportedSymbol[] array2 = array; foreach (ExportedSymbol item in array2) { val.Exports.Entries.Add(item); } } foreach (BaseRelocation baseRelocation in nativeSymbolsProvider.GetBaseRelocations()) { val.Relocations.Add(baseRelocation); } for (int j = 0; j < module.DebugData.Count; j++) { val.DebugData.Add(module.DebugData[j]); } } catch (Exception ex) { pEImageBuildContext.DiagnosticBag.RegisterException(ex); pEImageBuildContext.DiagnosticBag.MarkAsFatal(); } if (tokenMapping == null) { tokenMapping = new TokenMapping(); } return new PEImageBuildResult((IPEImage?)(object)val, pEImageBuildContext.DiagnosticBag, tokenMapping); } } [Serializable] public class MetadataBuilderException : Exception { public MetadataBuilderException() : base("An error occurred during the assembly of a .NET data directory.") { } public MetadataBuilderException(string message) : base(message) { } public MetadataBuilderException(string message, Exception inner) : base(message, inner) { } protected MetadataBuilderException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Flags] public enum MetadataBuilderFlags { None = 0, PreserveBlobIndices = 1, PreserveGuidIndices = 2, PreserveStringIndices = 4, PreserveUserStringIndices = 8, PreserveTypeReferenceIndices = 0x10, PreserveTypeDefinitionIndices = 0x20, PreserveFieldDefinitionIndices = 0x40, PreserveMethodDefinitionIndices = 0x80, PreserveParameterDefinitionIndices = 0x100, PreserveMemberReferenceIndices = 0x200, PreserveStandAloneSignatureIndices = 0x400, PreserveEventDefinitionIndices = 0x800, PreservePropertyDefinitionIndices = 0x1000, PreserveModuleReferenceIndices = 0x2000, PreserveTypeSpecificationIndices = 0x4000, PreserveAssemblyReferenceIndices = 0x8000, PreserveMethodSpecificationIndices = 0x10000, PreserveTableIndices = 0x1FFF0, PreserveUnknownStreams = 0x20000, PreserveStreamOrder = 0x40000, PreserveAll = 0x7FFFF, NoStringsStreamOptimization = 0x20000 } public class PEImageBuildContext { public DiagnosticBag DiagnosticBag { get; } public PEImageBuildContext() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown DiagnosticBag = new DiagnosticBag(); } public PEImageBuildContext(DiagnosticBag diagnosticBag) { DiagnosticBag = diagnosticBag ?? throw new ArgumentNullException("diagnosticBag"); } } public class PEImageBuildResult { public IPEImage? ConstructedImage { get; } [MemberNotNullWhen(false, "ConstructedImage")] public bool HasFailed { [MemberNotNullWhen(false, "ConstructedImage")] get { return DiagnosticBag.IsFatal; } } public DiagnosticBag DiagnosticBag { get; } public ITokenMapping TokenMapping { get; } public PEImageBuildResult(IPEImage? image, DiagnosticBag diagnosticBag, ITokenMapping tokenMapping) { ConstructedImage = image; DiagnosticBag = diagnosticBag ?? throw new ArgumentNullException("diagnosticBag"); TokenMapping = tokenMapping ?? throw new ArgumentNullException("tokenMapping"); } } public class TokenMapping : ITokenMapping { private readonly OneToOneRelation _typeDefTokens = new OneToOneRelation(); private readonly Dictionary _fieldTokens = new Dictionary(); private readonly OneToOneRelation _methodTokens = new OneToOneRelation(); private readonly Dictionary _parameterTokens = new Dictionary(); private readonly Dictionary _propertyTokens = new Dictionary(); private readonly Dictionary _eventTokens = new Dictionary(); private readonly Dictionary _remainingTokens = new Dictionary(); public MetadataToken this[IMetadataMember member] { get { //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_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_000f: 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_0033: Expected I4, but got Unknown //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_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_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0073: 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_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_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: 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_003b: Invalid comparison between Unknown and I4 //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) MetadataToken metadataToken = member.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; switch (table - 2) { default: if ((int)table != 20) { if ((int)table != 23) { break; } return _propertyTokens[(PropertyDefinition)member]; } return _eventTokens[(EventDefinition)member]; case 0: return _typeDefTokens.GetValue((TypeDefinition)member); case 2: return _fieldTokens[(FieldDefinition)member]; case 4: return _methodTokens.GetValue((MethodDefinition)member); case 6: return _parameterTokens[(ParameterDefinition)member]; case 1: case 3: case 5: break; } return _remainingTokens[member]; } } public bool TryGetNewToken(IMetadataMember member, out MetadataToken token) { //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_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_000f: 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_0033: Expected I4, but got Unknown //IL_0052: 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_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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_0036: Invalid comparison between Unknown and I4 //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Invalid comparison between Unknown and I4 MetadataToken metadataToken = member.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; switch (table - 2) { default: if ((int)table != 20) { if ((int)table != 23) { break; } return _propertyTokens.TryGetValue((PropertyDefinition)member, out token); } return _eventTokens.TryGetValue((EventDefinition)member, out token); case 0: token = _typeDefTokens.GetValue((TypeDefinition)member); return ((MetadataToken)(ref token)).Rid != 0; case 2: return _fieldTokens.TryGetValue((FieldDefinition)member, out token); case 4: token = _methodTokens.GetValue((MethodDefinition)member); return ((MetadataToken)(ref token)).Rid != 0; case 6: return _parameterTokens.TryGetValue((ParameterDefinition)member, out token); case 1: case 3: case 5: break; } return _remainingTokens.TryGetValue(member, out token); } public void Register(IMetadataMember member, MetadataToken newToken) { //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_0009: 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_0031: 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_0052: 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_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: 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_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected I4, but got Unknown //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0132: 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_00e2: Invalid comparison between Unknown and I4 //IL_0145: 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) //IL_00e7: Invalid comparison between Unknown and I4 //IL_0158: Unknown result type (might be due to invalid IL or missing references) MetadataToken metadataToken = member.MetadataToken; if (((MetadataToken)(ref metadataToken)).Table != ((MetadataToken)(ref newToken)).Table) { DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(38, 2); defaultInterpolatedStringHandler.AppendLiteral("Cannot assign a "); defaultInterpolatedStringHandler.AppendFormatted(((MetadataToken)(ref newToken)).Table); defaultInterpolatedStringHandler.AppendLiteral(" metadata token to a "); metadataToken = member.MetadataToken; defaultInterpolatedStringHandler.AppendFormatted(((MetadataToken)(ref metadataToken)).Table); defaultInterpolatedStringHandler.AppendLiteral("."); throw new ArgumentException(defaultInterpolatedStringHandler.ToStringAndClear()); } if (TryGetNewToken(member, out var token)) { if (((MetadataToken)(ref token)).Rid != ((MetadataToken)(ref newToken)).Rid) { throw new ArgumentException("Member " + member.SafeToString() + " was already assigned a metadata token."); } return; } metadataToken = member.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; switch (table - 2) { default: if ((int)table != 20) { if ((int)table != 23) { break; } _propertyTokens.Add((PropertyDefinition)member, newToken); return; } _eventTokens.Add((EventDefinition)member, newToken); return; case 0: _typeDefTokens.Add((TypeDefinition)member, newToken); return; case 2: _fieldTokens.Add((FieldDefinition)member, newToken); return; case 4: _methodTokens.Add((MethodDefinition)member, newToken); return; case 6: _parameterTokens.Add((ParameterDefinition)member, newToken); return; case 1: case 3: case 5: break; } _remainingTokens.Add(member, newToken); } public TypeDefinition? GetTypeByToken(MetadataToken newToken) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _typeDefTokens.GetKey(newToken); } public MethodDefinition? GetMethodByToken(MetadataToken newToken) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _methodTokens.GetKey(newToken); } } } namespace AsmResolver.DotNet.Builder.VTableFixups { public class VTableFixupsBuffer { private readonly Platform _targetPlatform; private readonly INativeSymbolsProvider _symbolsProvider; public VTableFixupsDirectory Directory { get; } = new VTableFixupsDirectory(); public VTableFixupsBuffer(Platform targetPlatform, INativeSymbolsProvider symbolsProvider) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown _targetPlatform = targetPlatform; _symbolsProvider = symbolsProvider; } private VTableFixup GetFixup(VTableType type) { //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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown VTableFixup val = ((IEnumerable)Directory).FirstOrDefault((Func)((VTableFixup f) => f.Tokens.Type == type)); if (val == null) { val = new VTableFixup(type); ((Collection)(object)Directory).Add(val); } return val; } public void MapTokenToExport(UnmanagedExportInfo exportInfo, MetadataToken token) { //IL_0003: 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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_003f: 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_006b: 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_0072: Expected O, but got Unknown //IL_009a: Unknown result type (might be due to invalid IL or missing references) VTableFixup fixup = GetFixup(exportInfo.VTableType); ((Collection)(object)fixup.Tokens).Add(token); Symbol val = new Symbol(fixup.Tokens.GetReferenceToIndex(((Collection)(object)fixup.Tokens).Count - 1)); RelocatableSegment val2 = _targetPlatform.CreateThunkStub((ISymbol)(object)val); ISegmentReference val3 = Extensions.ToReference(((RelocatableSegment)(ref val2)).Segment); ExportedSymbol symbol = (exportInfo.IsByName ? new ExportedSymbol(val3, exportInfo.Name) : new ExportedSymbol(val3)); _symbolsProvider.RegisterExportedSymbol(symbol, exportInfo.Ordinal); for (int i = 0; i < ((RelocatableSegment)(ref val2)).Relocations.Count; i++) { _symbolsProvider.RegisterBaseRelocation(((RelocatableSegment)(ref val2)).Relocations[i]); } } } } namespace AsmResolver.DotNet.Builder.Resources { public class DotNetResourcesDirectoryBuffer { private readonly MemoryStream _rawStream = new MemoryStream(); private readonly BinaryStreamWriter _writer; private readonly Dictionary _dataOffsets = new Dictionary((IEqualityComparer?)ByteArrayEqualityComparer.Instance); public uint Size => (uint)_rawStream.Length; public DotNetResourcesDirectoryBuffer() { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown _writer = new BinaryStreamWriter((Stream)_rawStream); } public uint AppendRawData(byte[] data) { int result = (int)_rawStream.Length; _writer.WriteBytes(data, 0, data.Length); return (uint)result; } public uint GetResourceDataOffset(byte[]? data) { if (data == null || data.Length == 0) { return 0u; } if (!_dataOffsets.TryGetValue(data, out var value)) { value = (uint)_rawStream.Length; _writer.WriteUInt32((uint)data.Length); AppendRawData(data); _dataOffsets.Add(data, value); } return value; } public DotNetResourcesDirectory CreateDirectory() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown return (DotNetResourcesDirectory)new SerializedDotNetResourcesDirectory((IReadableSegment)new DataSegment(_rawStream.ToArray())); } } } namespace AsmResolver.DotNet.Builder.Metadata { public interface IMetadataBuffer { BlobStreamBuffer BlobStream { get; } StringsStreamBuffer StringsStream { get; } UserStringsStreamBuffer UserStringsStream { get; } GuidStreamBuffer GuidStream { get; } TablesStreamBuffer TablesStream { get; } IMetadata CreateMetadata(); } public interface IMetadataStreamBuffer { string Name { get; } bool IsEmpty { get; } IMetadataStream CreateStream(); } public class MemberNotImportedException : Exception { public IMetadataMember Member { get; } public MemberNotImportedException(IMetadataMember member) : base("Member " + member.SafeToString() + " was not imported into the module.") { Member = member; } } public class MetadataBuffer : IMetadataBuffer { private readonly string _versionString; public BlobStreamBuffer BlobStream { get; } = new BlobStreamBuffer(); public StringsStreamBuffer StringsStream { get; } = new StringsStreamBuffer(); public UserStringsStreamBuffer UserStringsStream { get; } = new UserStringsStreamBuffer(); public GuidStreamBuffer GuidStream { get; } = new GuidStreamBuffer(); public TablesStreamBuffer TablesStream { get; } = new TablesStreamBuffer(); public bool OptimizeStringIndices { get; set; } = true; public MetadataBuffer() : this("v4.0.30319") { } public MetadataBuffer(string versionString) { _versionString = versionString ?? throw new ArgumentNullException("versionString"); } public IMetadata CreateMetadata() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0011: 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_002e: Expected O, but got Unknown //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown //IL_007a: 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_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got I4 ? val = new Metadata { VersionString = _versionString, IsEncMetadata = TablesStream.IsEncMetadata }; TablesStream val2 = Add((IMetadata)val, (IMetadataStreamBuffer)TablesStream); if (OptimizeStringIndices) { OptimizeIndices(val2); } StringsStream val3 = AddIfNotEmpty((IMetadata)val, (IMetadataStreamBuffer)StringsStream); AddIfNotEmpty((IMetadata)val, (IMetadataStreamBuffer)UserStringsStream); GuidStream val4 = AddIfNotEmpty((IMetadata)val, (IMetadataStreamBuffer)GuidStream); BlobStream val5 = AddIfNotEmpty((IMetadata)val, (IMetadataStreamBuffer)BlobStream); int num; if (val3 == null) { num = 2; val = num; num = (int)val; } else { val = ((MetadataHeap)val3).IndexSize; num = (int)val; } val2.StringIndexSize = (IndexSize)val; num = ((val4 == null) ? 2 : ((int)((MetadataHeap)val4).IndexSize)); val2.GuidIndexSize = (IndexSize)num; num = ((val5 == null) ? 2 : ((int)((MetadataHeap)val5).IndexSize)); val2.BlobIndexSize = (IndexSize)num; return (IMetadata)(object)num; } private static TStream? AddIfNotEmpty(IMetadata metadata, IMetadataStreamBuffer streamBuffer) where TStream : class, IMetadataStream { if (streamBuffer.IsEmpty) { return null; } return Add(metadata, streamBuffer); } private static TStream Add(IMetadata metadata, IMetadataStreamBuffer streamBuffer) where TStream : class, IMetadataStream { IMetadataStream val = streamBuffer.CreateStream(); metadata.Streams.Add(val); return (TStream)(object)val; } private void OptimizeIndices(TablesStream tablesStream) { IDictionary translationTable = StringsStream.Optimize(); OptimizeAssemblyTable(translationTable, tablesStream); OptimizeAssemblyReferenceTable(translationTable, tablesStream); OptimizeEventDefinitionTable(translationTable, tablesStream); OptimizeExportedTypeTable(translationTable, tablesStream); OptimizeFieldDefinitionTable(translationTable, tablesStream); OptimizeFileReferenceTable(translationTable, tablesStream); OptimizeGenericParameterTable(translationTable, tablesStream); OptimizeImplementationMapTable(translationTable, tablesStream); OptimizeManifestResourceTable(translationTable, tablesStream); OptimizeMemberReferenceTable(translationTable, tablesStream); OptimizeMethodDefinitionTable(translationTable, tablesStream); OptimizeModuleDefinitionTable(translationTable, tablesStream); OptimizeModuleReferenceTable(translationTable, tablesStream); OptimizeParameterDefinitionTable(translationTable, tablesStream); OptimizePropertyDefinitionTable(translationTable, tablesStream); OptimizeTypeDefinitionTable(translationTable, tablesStream); OptimizeTypeReferenceTable(translationTable, tablesStream); } private static void OptimizeAssemblyTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)32); for (uint num = 1u; num <= table.Count; num++) { ref AssemblyDefinitionRow rowRef = ref table.GetRowRef(num); ((AssemblyDefinitionRow)(ref rowRef)).Name = translationTable[((AssemblyDefinitionRow)(ref rowRef)).Name]; ((AssemblyDefinitionRow)(ref rowRef)).Culture = translationTable[((AssemblyDefinitionRow)(ref rowRef)).Culture]; } } private static void OptimizeAssemblyReferenceTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)35); for (uint num = 1u; num <= table.Count; num++) { ref AssemblyReferenceRow rowRef = ref table.GetRowRef(num); ((AssemblyReferenceRow)(ref rowRef)).Name = translationTable[((AssemblyReferenceRow)(ref rowRef)).Name]; ((AssemblyReferenceRow)(ref rowRef)).Culture = translationTable[((AssemblyReferenceRow)(ref rowRef)).Culture]; } } private static void OptimizeEventDefinitionTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)20); for (uint num = 1u; num <= table.Count; num++) { ref EventDefinitionRow rowRef = ref table.GetRowRef(num); ((EventDefinitionRow)(ref rowRef)).Name = translationTable[((EventDefinitionRow)(ref rowRef)).Name]; } } private static void OptimizeExportedTypeTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)39); for (uint num = 1u; num <= table.Count; num++) { ref ExportedTypeRow rowRef = ref table.GetRowRef(num); ((ExportedTypeRow)(ref rowRef)).Name = translationTable[((ExportedTypeRow)(ref rowRef)).Name]; ((ExportedTypeRow)(ref rowRef)).Namespace = translationTable[((ExportedTypeRow)(ref rowRef)).Namespace]; } } private static void OptimizeFieldDefinitionTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)4); for (uint num = 1u; num <= table.Count; num++) { ref FieldDefinitionRow rowRef = ref table.GetRowRef(num); ((FieldDefinitionRow)(ref rowRef)).Name = translationTable[((FieldDefinitionRow)(ref rowRef)).Name]; } } private static void OptimizeFileReferenceTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)38); for (uint num = 1u; num <= table.Count; num++) { ref FileReferenceRow rowRef = ref table.GetRowRef(num); ((FileReferenceRow)(ref rowRef)).Name = translationTable[((FileReferenceRow)(ref rowRef)).Name]; } } private static void OptimizeGenericParameterTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)42); for (uint num = 1u; num <= table.Count; num++) { ref GenericParameterRow rowRef = ref table.GetRowRef(num); ((GenericParameterRow)(ref rowRef)).Name = translationTable[((GenericParameterRow)(ref rowRef)).Name]; } } private static void OptimizeImplementationMapTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)28); for (uint num = 1u; num <= table.Count; num++) { ref ImplementationMapRow rowRef = ref table.GetRowRef(num); ((ImplementationMapRow)(ref rowRef)).ImportName = translationTable[((ImplementationMapRow)(ref rowRef)).ImportName]; } } private static void OptimizeManifestResourceTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)40); for (uint num = 1u; num <= table.Count; num++) { ref ManifestResourceRow rowRef = ref table.GetRowRef(num); ((ManifestResourceRow)(ref rowRef)).Name = translationTable[((ManifestResourceRow)(ref rowRef)).Name]; } } private static void OptimizeMemberReferenceTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)10); for (uint num = 1u; num <= table.Count; num++) { ref MemberReferenceRow rowRef = ref table.GetRowRef(num); ((MemberReferenceRow)(ref rowRef)).Name = translationTable[((MemberReferenceRow)(ref rowRef)).Name]; } } private static void OptimizeMethodDefinitionTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)6); for (uint num = 1u; num <= table.Count; num++) { ref MethodDefinitionRow rowRef = ref table.GetRowRef(num); ((MethodDefinitionRow)(ref rowRef)).Name = translationTable[((MethodDefinitionRow)(ref rowRef)).Name]; } } private static void OptimizeModuleDefinitionTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)0); for (uint num = 1u; num <= table.Count; num++) { ref ModuleDefinitionRow rowRef = ref table.GetRowRef(num); ((ModuleDefinitionRow)(ref rowRef)).Name = translationTable[((ModuleDefinitionRow)(ref rowRef)).Name]; } } private static void OptimizeModuleReferenceTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)26); for (uint num = 1u; num <= table.Count; num++) { ref ModuleReferenceRow rowRef = ref table.GetRowRef(num); ((ModuleReferenceRow)(ref rowRef)).Name = translationTable[((ModuleReferenceRow)(ref rowRef)).Name]; } } private static void OptimizeParameterDefinitionTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)8); for (uint num = 1u; num <= table.Count; num++) { ref ParameterDefinitionRow rowRef = ref table.GetRowRef(num); ((ParameterDefinitionRow)(ref rowRef)).Name = translationTable[((ParameterDefinitionRow)(ref rowRef)).Name]; } } private static void OptimizePropertyDefinitionTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)23); for (uint num = 1u; num <= table.Count; num++) { ref PropertyDefinitionRow rowRef = ref table.GetRowRef(num); ((PropertyDefinitionRow)(ref rowRef)).Name = translationTable[((PropertyDefinitionRow)(ref rowRef)).Name]; } } private static void OptimizeTypeDefinitionTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)2); for (uint num = 1u; num <= table.Count; num++) { ref TypeDefinitionRow rowRef = ref table.GetRowRef(num); ((TypeDefinitionRow)(ref rowRef)).Name = translationTable[((TypeDefinitionRow)(ref rowRef)).Name]; ((TypeDefinitionRow)(ref rowRef)).Namespace = translationTable[((TypeDefinitionRow)(ref rowRef)).Namespace]; } } private static void OptimizeTypeReferenceTable(IDictionary translationTable, TablesStream tablesStream) { MetadataTable table = tablesStream.GetTable((TableIndex)1); for (uint num = 1u; num <= table.Count; num++) { ref TypeReferenceRow rowRef = ref table.GetRowRef(num); ((TypeReferenceRow)(ref rowRef)).Name = translationTable[((TypeReferenceRow)(ref rowRef)).Name]; ((TypeReferenceRow)(ref rowRef)).Namespace = translationTable[((TypeReferenceRow)(ref rowRef)).Namespace]; } } } internal static class MetadataStreamBufferHelper { public delegate void IndexBlobAction(uint originalIndex, uint newIndex); public static void CloneBlobHeap(IMetadataStream stream, IBinaryStreamWriter writer, IndexBlobAction indexAction) { //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) if (!stream.CanRead) { throw new ArgumentException("Stream to clone must be readable."); } BinaryStreamReader val = stream.CreateReader(); byte b = ((BinaryStreamReader)(ref val)).ReadByte(); if (writer.Length != 1) { writer.WriteByte(b); } uint num2 = default(uint); int num4; for (uint num = 1u; num < ((IWritable)stream).GetPhysicalSize(); num += (uint)num4) { ulong offset = ((BinaryStreamReader)(ref val)).Offset; if (((BinaryStreamReader)(ref val)).TryReadCompressedUInt32(ref num2)) { uint num3 = (uint)(((BinaryStreamReader)(ref val)).Offset - offset); ((BinaryStreamReader)(ref val)).Offset = ((BinaryStreamReader)(ref val)).Offset - num3; if (num2 != 0) { indexAction(num, writer.Length); } byte[] array = new byte[num3 + num2]; num4 = ((BinaryStreamReader)(ref val)).ReadBytes(array, 0, array.Length); writer.WriteBytes(array, 0, num4); continue; } break; } } } } namespace AsmResolver.DotNet.Builder.Metadata.UserStrings { public class UserStringsStreamBuffer : IMetadataStreamBuffer { private readonly MemoryStream _rawStream = new MemoryStream(); private readonly BinaryStreamWriter _writer; private readonly Dictionary _strings = new Dictionary(); public string Name { get; } public bool IsEmpty => _rawStream.Length <= 1; public UserStringsStreamBuffer() : this("#US") { } public UserStringsStreamBuffer(string name) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown Name = name ?? throw new ArgumentNullException("name"); _writer = new BinaryStreamWriter((Stream)_rawStream); _writer.WriteByte((byte)0); } public void ImportStream(UserStringsStream stream) { UserStringsStream stream2 = stream; MetadataStreamBufferHelper.CloneBlobHeap((IMetadataStream)(object)stream2, (IBinaryStreamWriter)(object)_writer, delegate(uint index, uint newIndex) { string stringByIndex = stream2.GetStringByIndex(index); if (stringByIndex != null) { _strings[stringByIndex] = newIndex; } }); } public uint AppendRawData(byte[] data) { int result = (int)_rawStream.Length; _writer.WriteBytes(data, 0, data.Length); return (uint)result; } private uint AppendString(string? value) { uint result = (uint)_rawStream.Length; if (value == null) { _writer.WriteByte((byte)0); return result; } int num = Encoding.Unicode.GetByteCount(value) + 1; IOExtensions.WriteCompressedUInt32((IBinaryStreamWriter)(object)_writer, (uint)num); byte[] array = new byte[num]; Encoding.Unicode.GetBytes(value, 0, value.Length, array, 0); array[num - 1] = GetTerminatorByte(value); AppendRawData(array); return result; } public uint GetStringIndex(string? value) { if (value == null) { return 0u; } if (!_strings.TryGetValue(value, out var value2)) { value2 = AppendString(value); _strings.Add(value, value2); } return value2; } private static byte GetTerminatorByte(string data) { foreach (char c in data) { if ((c >= '\u0001' && c <= '\b') || (c >= '\u000e' && c <= '\u001f') || c == '\'' || c == '-' || c == '\u007f' || c >= 'Ā') { return 1; } } return 0; } public UserStringsStream CreateStream() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown IOExtensions.Align((IBinaryStreamWriter)(object)_writer, 4u); return (UserStringsStream)new SerializedUserStringsStream(Name, _rawStream.ToArray()); } IMetadataStream IMetadataStreamBuffer.CreateStream() { return (IMetadataStream)(object)CreateStream(); } } } namespace AsmResolver.DotNet.Builder.Metadata.Tables { public class DistinctMetadataTableBuffer : IMetadataTableBuffer, IMetadataTableBuffer where TRow : struct, IMetadataRow { private readonly Dictionary _entries = new Dictionary(); private readonly IMetadataTableBuffer _underlyingBuffer; public int Count => _underlyingBuffer.Count; public TRow this[uint rid] { get { return _underlyingBuffer[rid]; } set { //IL_0054: Unknown result type (might be due to invalid IL or missing references) if (_entries.TryGetValue(value, out var value2) && ((MetadataToken)(ref value2)).Rid != rid) { throw new ArgumentException("Row is already present in the table."); } TRow key = _underlyingBuffer[rid]; _underlyingBuffer[rid] = value; _entries.Remove(key); _entries.Add(value, MetadataToken.op_Implicit(rid)); } } public DistinctMetadataTableBuffer(IMetadataTableBuffer underlyingBuffer) { _underlyingBuffer = underlyingBuffer ?? throw new ArgumentNullException("underlyingBuffer"); } public void EnsureCapacity(int capacity) { _underlyingBuffer.EnsureCapacity(capacity); } public ref TRow GetRowRef(uint rid) { return ref _underlyingBuffer.GetRowRef(rid); } public MetadataToken Add(in TRow row) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return Add(in row, allowDuplicates: false); } public MetadataToken Insert(uint rid, in TRow row) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) return Insert(rid, in row, allowDuplicates: false); } public MetadataToken Insert(uint rid, in TRow row, bool allowDuplicates) { //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_002f: 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_0042: 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) if (!_entries.TryGetValue(row, out var value)) { value = _underlyingBuffer.Insert(rid, in row); _entries.Add(row, value); } else if (allowDuplicates) { value = _underlyingBuffer.Insert(rid, in row); } return value; } public MetadataToken Add(in TRow row, bool allowDuplicates) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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_0040: 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) if (!_entries.TryGetValue(row, out var value)) { value = _underlyingBuffer.Add(in row); _entries.Add(row, value); } else if (allowDuplicates) { value = _underlyingBuffer.Add(in row); } return value; } public void FlushToTable() { _underlyingBuffer.FlushToTable(); } public void Clear() { _underlyingBuffer.Clear(); _entries.Clear(); } MetadataToken IMetadataTableBuffer.Add(in TRow row) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return Add(in row); } MetadataToken IMetadataTableBuffer.Insert(uint rid, in TRow row) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return Insert(rid, in row); } } public interface IMetadataTableBuffer { int Count { get; } void FlushToTable(); void Clear(); } public interface IMetadataTableBuffer : IMetadataTableBuffer where TRow : struct, IMetadataRow { TRow this[uint rid] { get; set; } void EnsureCapacity(int capacity); ref TRow GetRowRef(uint rid); MetadataToken Add(in TRow row); MetadataToken Insert(uint rid, in TRow row); } public interface ISortedMetadataTableBuffer : IMetadataTableBuffer where TRow : struct, IMetadataRow { void Add(TKey originalMember, in TRow row); IEnumerable GetMembers(); MetadataToken GetNewToken(TKey member); void Sort(); } public class SortedMetadataTableBuffer : ISortedMetadataTableBuffer, IMetadataTableBuffer where TKey : notnull where TRow : struct, IMetadataRow { private sealed class EntryComparer : IComparer<(TKey Key, TRow Row, int InputIndex)> { private readonly int _primaryColumn; private readonly int _secondaryColumn; public EntryComparer(int primaryColumn, int secondaryColumn) { _primaryColumn = primaryColumn; _secondaryColumn = secondaryColumn; } public int Compare((TKey Key, TRow Row, int InputIndex) x, (TKey Key, TRow Row, int InputIndex) y) { int num = ((IReadOnlyList)x.Row)[_primaryColumn].CompareTo(((IReadOnlyList)y.Row)[_primaryColumn]); if (num == 0) { num = ((IReadOnlyList)x.Row)[_secondaryColumn].CompareTo(((IReadOnlyList)y.Row)[_secondaryColumn]); } if (num == 0) { num = x.InputIndex.CompareTo(y.InputIndex); } return num; } } private readonly List<(TKey Key, TRow Row, int InputIndex)> _entries = new List<(TKey, TRow, int)>(); private readonly Dictionary _newTokens = new Dictionary(); private readonly MetadataTable _table; private readonly EntryComparer _comparer; public int Count => _entries.Count; public SortedMetadataTableBuffer(MetadataTable table, int primaryColumn) : this(table, primaryColumn, primaryColumn) { } public SortedMetadataTableBuffer(MetadataTable table, int primaryColumn, int secondaryColumn) { _table = table ?? throw new ArgumentNullException("table"); _comparer = new EntryComparer(primaryColumn, secondaryColumn); } public void Add(TKey originalKey, in TRow row) { _entries.Add((originalKey, row, _entries.Count)); } public IEnumerable GetMembers() { return _entries.Select(((TKey Key, TRow Row, int InputIndex) entry) => entry.Key); } public void Sort() { //IL_0036: 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) _entries.Sort(_comparer); for (uint num = 1u; num <= _entries.Count; num++) { TKey item = _entries[(int)(num - 1)].Key; _newTokens[item] = new MetadataToken(((MetadataTable)(object)_table).TableIndex, num); } } public MetadataToken GetNewToken(TKey member) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return _newTokens[member]; } public void FlushToTable() { Sort(); ((MetadataTable)(object)_table).Clear(); foreach (var entry in _entries) { ((MetadataTable)(object)_table).Add(entry.Row); } } public void Clear() { _entries.Clear(); ((MetadataTable)(object)_table).Clear(); } void ISortedMetadataTableBuffer.Add(TKey originalMember, in TRow row) { Add(originalMember, in row); } } public class TablesStreamBuffer : IMetadataStreamBuffer { private static readonly TableIndex[] EncTables; private readonly TablesStream _tablesStream = new TablesStream(); private readonly IMetadataTableBuffer[] _tableBuffers; public string Name { get { if (!IsEncMetadata) { return "#~"; } return "#-"; } } public bool IsEmpty { get { for (int i = 0; i < _tableBuffers.Length; i++) { if (_tableBuffers[i].Count > 0) { return false; } } return true; } } public bool IsEncMetadata { get { for (int i = 0; i < EncTables.Length; i++) { if (_tableBuffers[(int)EncTables[i]].Count > 0) { return true; } } return false; } } public TablesStreamBuffer() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown _tableBuffers = new IMetadataTableBuffer[45] { Unsorted((TableIndex)0), Distinct((TableIndex)1), Unsorted((TableIndex)2), Unsorted((TableIndex)3), Unsorted((TableIndex)4), Unsorted((TableIndex)5), Unsorted((TableIndex)6), Unsorted((TableIndex)7), Unsorted((TableIndex)8), Sorted((TableIndex)9, 0), Distinct((TableIndex)10), Sorted((TableIndex)11, 2), Sorted((TableIndex)12, 0), Sorted((TableIndex)13, 0), Sorted((TableIndex)14, 1), Sorted((TableIndex)15, 2), Sorted((TableIndex)16, 1), Distinct((TableIndex)17), Sorted((TableIndex)18, 0, 1), Unsorted((TableIndex)19), Unsorted((TableIndex)20), Sorted((TableIndex)21, 0, 1), Unsorted((TableIndex)22), Unsorted((TableIndex)23), Sorted((TableIndex)24, 2), Sorted((TableIndex)25, 0), Distinct((TableIndex)26), Distinct((TableIndex)27), Sorted((TableIndex)28, 1), Sorted((TableIndex)29, 1), Unsorted((TableIndex)30), Unsorted((TableIndex)31), Unsorted((TableIndex)32), Unsorted((TableIndex)33), Unsorted((TableIndex)34), Distinct((TableIndex)35), Unsorted((TableIndex)36), Unsorted((TableIndex)37), Distinct((TableIndex)38), Distinct((TableIndex)39), Distinct((TableIndex)40), Sorted((TableIndex)41, 0), Sorted((TableIndex)42, 2, 0), Distinct((TableIndex)43), Distinct((TableIndex)44) }; } public IMetadataTableBuffer GetTable(TableIndex table) where TRow : struct, IMetadataRow { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return (IMetadataTableBuffer)_tableBuffers[table]; } public DistinctMetadataTableBuffer GetDistinctTable(TableIndex table) where TRow : struct, IMetadataRow { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return (DistinctMetadataTableBuffer)_tableBuffers[table]; } public ISortedMetadataTableBuffer GetSortedTable(TableIndex table) where TRow : struct, IMetadataRow { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return (ISortedMetadataTableBuffer)_tableBuffers[table]; } public IndexEncoder GetIndexEncoder(CodedIndex codedIndex) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _tablesStream.GetIndexEncoder(codedIndex); } public TablesStream CreateStream() { IMetadataTableBuffer[] tableBuffers = _tableBuffers; for (int i = 0; i < tableBuffers.Length; i++) { tableBuffers[i].FlushToTable(); } _tablesStream.Name = Name; return _tablesStream; } IMetadataStream IMetadataStreamBuffer.CreateStream() { return (IMetadataStream)(object)CreateStream(); } private IMetadataTableBuffer Unsorted(TableIndex table) where TRow : struct, IMetadataRow { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return new UnsortedMetadataTableBuffer((MetadataTable)(object)_tablesStream.GetTable(table)); } private IMetadataTableBuffer Distinct(TableIndex table) where TRow : struct, IMetadataRow { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return new DistinctMetadataTableBuffer(Unsorted(table)); } private ISortedMetadataTableBuffer Sorted(TableIndex table, int primaryColumn) where TKey : notnull where TRow : struct, IMetadataRow { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return new SortedMetadataTableBuffer((MetadataTable)(object)_tablesStream.GetTable(table), primaryColumn); } private ISortedMetadataTableBuffer Sorted(TableIndex table, int primaryColumn, int secondaryColumn) where TKey : notnull where TRow : struct, IMetadataRow { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return new SortedMetadataTableBuffer((MetadataTable)(object)_tablesStream.GetTable(table), primaryColumn, secondaryColumn); } static TablesStreamBuffer() { TableIndex[] array = new TableIndex[7]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); EncTables = (TableIndex[])(object)array; } } public class UnsortedMetadataTableBuffer : IMetadataTableBuffer, IMetadataTableBuffer where TRow : struct, IMetadataRow { private readonly RefList _entries = new RefList(); private readonly BitList _available = new BitList(); private readonly MetadataTable _table; private uint _currentRid; public int Count => _entries.Count; public virtual TRow this[uint rid] { get { return _entries[(int)(rid - 1)]; } set { _entries[(int)(rid - 1)] = value; _available[(int)(rid - 1)] = false; } } public UnsortedMetadataTableBuffer(MetadataTable table) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown _table = table ?? throw new ArgumentNullException("table"); } public void EnsureCapacity(int capacity) { if (_entries.Capacity < capacity) { _entries.Capacity = capacity; } } public ref TRow GetRowRef(uint rid) { return ref _entries.GetElementRef((int)(rid - 1)); } public virtual MetadataToken Add(in TRow row) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) while (_currentRid < _available.Count && !_available[(int)_currentRid]) { _currentRid++; } if (_currentRid == _entries.Count) { _currentRid++; } return Insert(_currentRid++, in row); } public MetadataToken Insert(uint rid, in TRow row) { //IL_000f: 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_004a: Unknown result type (might be due to invalid IL or missing references) EnsureRowsAllocated(rid); MetadataToken result = default(MetadataToken); ((MetadataToken)(ref result))..ctor(_table.TableIndex, rid); if (!_available[(int)(rid - 1)]) { if (EqualityComparer.Default.Equals(row, _entries[(int)(rid - 1)])) { return result; } throw new InvalidOperationException("Token 0x" + ((object)(MetadataToken)(ref result)).ToString() + " is already in use."); } this[rid] = row; return result; } private void EnsureRowsAllocated(uint rid) { while (_entries.Count < rid) { RefList entries = _entries; TRow val = default(TRow); entries.Add(ref val); _available.Add(true); } } public void FlushToTable() { //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) if (_table.Capacity < _entries.Count) { _table.Capacity = _entries.Count; } Enumerator enumerator = _entries.GetEnumerator(); try { while (enumerator.MoveNext()) { TRow current = enumerator.Current; _table.Add(current); } } finally { ((IDisposable)enumerator).Dispose(); } } public void Clear() { _entries.Clear(); } MetadataToken IMetadataTableBuffer.Insert(uint rid, in TRow row) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return Insert(rid, in row); } } } namespace AsmResolver.DotNet.Builder.Metadata.Strings { internal readonly struct StringIndex { public int BlobIndex { get; } public uint Offset { get; } public StringIndex(int blobIndex, uint offset) { BlobIndex = blobIndex; Offset = offset; } } internal readonly struct StringsStreamBlob : IWritable { public Utf8String Blob { get; } public StringsStreamBlobFlags Flags { get; } public bool IsZeroTerminated => (Flags & StringsStreamBlobFlags.ZeroTerminated) != 0; public bool IsFixed => (Flags & StringsStreamBlobFlags.Fixed) != 0; public StringsStreamBlob(Utf8String blob, bool isFixed) { Blob = blob; Flags = ((!isFixed) ? StringsStreamBlobFlags.ZeroTerminated : (StringsStreamBlobFlags.ZeroTerminated | StringsStreamBlobFlags.Fixed)); } public StringsStreamBlob(Utf8String blob, StringsStreamBlobFlags flags) { Blob = blob; Flags = flags; } public uint GetPhysicalSize() { return (uint)(Blob.ByteCount + (IsZeroTerminated ? 1 : 0)); } public void Write(IBinaryStreamWriter writer) { IOExtensions.WriteBytes(writer, Blob.GetBytesUnsafe()); if (IsZeroTerminated) { writer.WriteByte((byte)0); } } } [Flags] internal enum StringsStreamBlobFlags : byte { ZeroTerminated = 1, Fixed = 2 } internal sealed class StringsStreamBlobSuffixComparer : IComparer, IComparer, IComparer> { public static StringsStreamBlobSuffixComparer Instance { get; } = new StringsStreamBlobSuffixComparer(); public int Compare(StringsStreamBlob x, StringsStreamBlob y) { return Compare(x.Blob.GetBytesUnsafe(), y.Blob.GetBytesUnsafe()); } public int Compare(KeyValuePair x, KeyValuePair y) { return Compare(x.Key.GetBytesUnsafe(), y.Key.GetBytesUnsafe()); } public int Compare(byte[]? x, byte[]? y) { if (x == y) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } int num = x.Length - 1; int num2 = y.Length - 1; while (num >= 0 && num2 >= 0) { int num3 = x[num].CompareTo(y[num2]); if (num3 != 0) { return num3; } num--; num2--; } return y.Length.CompareTo(x.Length); } } public class StringsStreamBuffer : IMetadataStreamBuffer { private Dictionary _index = new Dictionary(); private List _blobs = new List(); private uint _currentOffset = 1u; private int _fixedBlobCount; public string Name { get; } public bool IsEmpty => _blobs.Count == 0; public StringsStreamBuffer() : this("#Strings") { } public StringsStreamBuffer(string name) { Name = name ?? throw new ArgumentNullException("name"); } public void ImportStream(StringsStream stream) { if (!IsEmpty) { throw new InvalidOperationException("Cannot import a stream if the buffer is not empty."); } uint num = 1u; uint physicalSize = ((SegmentBase)stream).GetPhysicalSize(); while (num < physicalSize) { Utf8String stringByIndex = stream.GetStringByIndex(num); uint offset = AppendString(stringByIndex, isFixed: true); _index[stringByIndex] = new StringIndex(_blobs.Count - 1, offset); num += (uint)(stringByIndex.ByteCount + 1); _fixedBlobCount++; } } private uint AppendString(Utf8String value, bool isFixed) { uint currentOffset = _currentOffset; _blobs.Add(new StringsStreamBlob(value, isFixed)); _currentOffset += (uint)(value.ByteCount + 1); return currentOffset; } public uint GetStringIndex(Utf8String? value) { if (Utf8String.IsNullOrEmpty(value)) { return 0u; } if (Array.IndexOf(value.GetBytesUnsafe(), (byte)0) >= 0) { throw new ArgumentException("String contains a zero byte."); } if (!_index.TryGetValue(value, out var value2)) { uint offset = AppendString(value, isFixed: false); value2 = new StringIndex(_blobs.Count - 1, offset); _index.Add(value, value2); } return value2.Offset; } public IDictionary Optimize() { uint finalOffset = 1u; Dictionary newIndex = new Dictionary(); List newBlobs = new List(_fixedBlobCount); Dictionary translationTable = new Dictionary { [0u] = 0u }; for (int i = 0; i < _fixedBlobCount; i++) { StringsStreamBlob blob2 = _blobs[i]; AppendBlob(in blob2); } List> sortedEntries = _index.ToList(); sortedEntries.Sort(StringsStreamBlobSuffixComparer.Instance); for (int j = 0; j < sortedEntries.Count; j++) { KeyValuePair currentEntry2 = sortedEntries[j]; StringsStreamBlob blob3 = _blobs[currentEntry2.Value.BlobIndex]; if (blob3.IsFixed) { continue; } if (j == 0) { AppendBlob(in blob3); continue; } int num = j; while (num > 0 && BytesEndsWith(sortedEntries[num - 1].Key.GetBytesUnsafe(), currentEntry2.Key.GetBytesUnsafe())) { num--; } if (num != j) { ReuseBlob(in currentEntry2, num); } else { AppendBlob(in blob3); } } _blobs = newBlobs; _index = newIndex; _currentOffset = finalOffset; return translationTable; void AppendBlob(in StringsStreamBlob blob) { newBlobs.Add(blob); StringIndex stringIndex = _index[blob.Blob]; translationTable[stringIndex.Offset] = finalOffset; newIndex[blob.Blob] = new StringIndex(newBlobs.Count - 1, finalOffset); finalOffset += blob.GetPhysicalSize(); } void ReuseBlob(in KeyValuePair currentEntry, int reusedIndex) { KeyValuePair keyValuePair = sortedEntries[reusedIndex]; uint num2 = translationTable[keyValuePair.Value.Offset]; int num3 = keyValuePair.Key.ByteCount - currentEntry.Key.ByteCount; uint num4 = (uint)(num2 + num3); translationTable[currentEntry.Value.Offset] = num4; newIndex[currentEntry.Key] = new StringIndex(keyValuePair.Value.BlobIndex, num4); } } private static bool BytesEndsWith(byte[] x, byte[] y) { if (x.Length < y.Length) { return false; } int num = x.Length - 1; int num2 = y.Length - 1; while (num >= 0 && num2 >= 0) { if (x[num] != y[num2]) { return false; } num--; num2--; } return true; } public StringsStream CreateStream() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown using MemoryStream memoryStream = new MemoryStream(); BinaryStreamWriter val = new BinaryStreamWriter((Stream)memoryStream); val.WriteByte((byte)0); foreach (StringsStreamBlob blob in _blobs) { blob.Write((IBinaryStreamWriter)(object)val); } IOExtensions.Align((IBinaryStreamWriter)(object)val, 4u); return (StringsStream)new SerializedStringsStream(Name, memoryStream.ToArray()); } IMetadataStream IMetadataStreamBuffer.CreateStream() { return (IMetadataStream)(object)CreateStream(); } } } namespace AsmResolver.DotNet.Builder.Metadata.Guid { public class GuidStreamBuffer : IMetadataStreamBuffer { private readonly MemoryStream _rawStream = new MemoryStream(); private readonly BinaryStreamWriter _writer; private readonly Dictionary _guids = new Dictionary(); public string Name { get; } public bool IsEmpty => _rawStream.Length <= 0; public GuidStreamBuffer() : this("#GUID") { } public GuidStreamBuffer(string name) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown Name = name ?? throw new ArgumentNullException("name"); _writer = new BinaryStreamWriter((Stream)_rawStream); } public void ImportStream(GuidStream stream) { for (uint num = 1u; num < ((SegmentBase)stream).GetPhysicalSize() / 16 + 1; num++) { System.Guid guidByIndex = stream.GetGuidByIndex(num); uint value = AppendGuid(guidByIndex); _guids[guidByIndex] = value; } } private uint AppendRawData(byte[] data) { int result = (int)_rawStream.Length; _writer.WriteBytes(data, 0, data.Length); return (uint)result; } private uint AppendGuid(System.Guid guid) { uint result = (uint)_rawStream.Length / 16 + 1; AppendRawData(guid.ToByteArray()); return result; } public uint GetGuidIndex(System.Guid guid) { if (guid == System.Guid.Empty) { return 0u; } if (!_guids.TryGetValue(guid, out var value)) { value = AppendGuid(guid); _guids.Add(guid, value); } return value; } public GuidStream CreateStream() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown return (GuidStream)new SerializedGuidStream(Name, _rawStream.ToArray()); } IMetadataStream IMetadataStreamBuffer.CreateStream() { return (IMetadataStream)(object)CreateStream(); } } } namespace AsmResolver.DotNet.Builder.Metadata.Blob { public class BlobStreamBuffer : IMetadataStreamBuffer { private readonly MemoryStream _rawStream = new MemoryStream(); private readonly BinaryStreamWriter _writer; private readonly Dictionary _blobs = new Dictionary((IEqualityComparer?)ByteArrayEqualityComparer.Instance); private readonly MemoryStreamWriterPool _blobWriterPool = new MemoryStreamWriterPool(); public string Name { get; } public bool IsEmpty => _rawStream.Length <= 1; public BlobStreamBuffer() : this("#Blob") { } public BlobStreamBuffer(string name) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown Name = name ?? throw new ArgumentNullException("name"); _writer = new BinaryStreamWriter((Stream)_rawStream); _writer.WriteByte((byte)0); } public void ImportStream(BlobStream stream) { BlobStream stream2 = stream; MetadataStreamBufferHelper.CloneBlobHeap((IMetadataStream)(object)stream2, (IBinaryStreamWriter)(object)_writer, delegate(uint index, uint newIndex) { byte[] blobByIndex = stream2.GetBlobByIndex(index); if (blobByIndex != null) { _blobs[blobByIndex] = newIndex; } }); } public uint AppendRawData(byte[] data) { int result = (int)_rawStream.Length; _writer.WriteBytes(data, 0, data.Length); return (uint)result; } private uint AppendBlob(byte[] blob) { int result = (int)_rawStream.Length; IOExtensions.WriteCompressedUInt32((IBinaryStreamWriter)(object)_writer, (uint)blob.Length); AppendRawData(blob); return (uint)result; } public uint GetBlobIndex(byte[]? blob) { if (blob == null || blob.Length == 0) { return 0u; } if (!_blobs.TryGetValue(blob, out var value)) { value = AppendBlob(blob); _blobs.Add(blob, value); } return value; } public uint GetBlobIndex(ITypeCodedIndexProvider provider, BlobSignature? signature, IErrorListener errorListener) { //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) if (signature == null) { return 0u; } RentedWriter val = _blobWriterPool.Rent(); try { BlobSerializationContext context = new BlobSerializationContext((IBinaryStreamWriter)(object)((RentedWriter)(ref val)).Writer, provider, errorListener); signature.Write(in context); return GetBlobIndex(((RentedWriter)(ref val)).GetData()); } finally { ((RentedWriter)(ref val)).Dispose(); } } public BlobStream CreateStream() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown IOExtensions.Align((IBinaryStreamWriter)(object)_writer, 4u); return (BlobStream)new SerializedBlobStream(Name, _rawStream.ToArray()); } IMetadataStream IMetadataStreamBuffer.CreateStream() { return (IMetadataStream)(object)CreateStream(); } } } namespace AsmResolver.DotNet.Builder.Discovery { public sealed class MemberDiscoverer { private sealed class PlaceHolderTypeDefinition : TypeDefinition { public PlaceHolderTypeDefinition(ModuleDefinition module, string ns, MetadataToken token) : base(token) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) base.Namespace = Utf8String.op_Implicit(ns); base.Name = Utf8String.op_Implicit("PlaceHolderTypeDef_" + ((MetadataToken)(ref token)).Rid); base.Attributes = (TypeAttributes)128; base.BaseType = module.CorLibTypeFactory.Object.Type; ((IOwnedCollectionElement)(object)this).Owner = module; } } private const MethodAttributes MethodPlaceHolderAttributes = 1478; private const FieldAttributes FieldPlaceHolderAttributes = 6; private readonly ModuleDefinition _module; private readonly MemberDiscoveryFlags _flags; private readonly MemberDiscoveryResult _result = new MemberDiscoveryResult(); private readonly List _allPlaceHolderMethods = new List(); private int _placeHolderParameterCounter; private readonly TypeReference _eventHandlerTypeRef; private readonly TypeSignature _eventHandlerTypeSig; private readonly Dictionary> _freeRids = new Dictionary> { [(TableIndex)2] = new List(), [(TableIndex)4] = new List(), [(TableIndex)6] = new List(), [(TableIndex)8] = new List(), [(TableIndex)23] = new List(), [(TableIndex)20] = new List() }; private readonly Dictionary> _floatingMembers = new Dictionary> { [(TableIndex)2] = new List(), [(TableIndex)4] = new List(), [(TableIndex)6] = new List(), [(TableIndex)8] = new List(), [(TableIndex)23] = new List(), [(TableIndex)20] = new List() }; private MemberDiscoverer(ModuleDefinition module, MemberDiscoveryFlags flags) { _module = module ?? throw new ArgumentNullException("module"); _flags = flags; _eventHandlerTypeRef = new TypeReference(module, module.CorLibTypeFactory.CorLibScope, Utf8String.op_Implicit("System"), Utf8String.op_Implicit("EventHandler")); _eventHandlerTypeSig = new TypeDefOrRefSignature(_eventHandlerTypeRef, isValueType: false); } public static MemberDiscoveryResult DiscoverMembersInModule(ModuleDefinition module, MemberDiscoveryFlags flags) { MemberDiscoverer memberDiscoverer = new MemberDiscoverer(module, flags); if (flags != 0) { memberDiscoverer.CollectExistingMembers(); } memberDiscoverer.CollectNewlyAddedFixedMembers(); memberDiscoverer.AddFloatingMembers(); if (flags != 0) { memberDiscoverer.StuffFreeMemberSlots(); } return memberDiscoverer._result; } private IList GetResultList(TableIndex tableIndex) where TMember : IMetadataMember { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected I4, but got Unknown //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Invalid comparison between Unknown and I4 //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Invalid comparison between Unknown and I4 switch (tableIndex - 2) { default: if ((int)tableIndex != 20) { if ((int)tableIndex != 23) { break; } return (IList)_result.Properties; } return (IList)_result.Events; case 0: return (IList)_result.Types; case 2: return (IList)_result.Fields; case 4: return (IList)_result.Methods; case 6: return (IList)_result.Parameters; case 1: case 3: case 5: break; } throw new ArgumentOutOfRangeException("tableIndex"); } private void CollectExistingMembers() { IDotNetDirectory? dotNetDirectory = _module.DotNetDirectory; if (((dotNetDirectory != null) ? dotNetDirectory.Metadata : null) != null) { if ((_flags & MemberDiscoveryFlags.PreserveTypeOrder) != 0) { CollectMembersFromTable((TableIndex)2); } if ((_flags & MemberDiscoveryFlags.PreserveFieldOrder) != 0) { CollectMembersFromTable((TableIndex)4); } if ((_flags & MemberDiscoveryFlags.PreserveMethodOrder) != 0) { CollectMembersFromTable((TableIndex)6); } if ((_flags & MemberDiscoveryFlags.PreserveParameterOrder) != 0) { CollectMembersFromTable((TableIndex)8); } if ((_flags & MemberDiscoveryFlags.PreservePropertyOrder) != 0) { CollectMembersFromTable((TableIndex)23); } if ((_flags & MemberDiscoveryFlags.PreserveEventOrder) != 0) { CollectMembersFromTable((TableIndex)20); } } } private void CollectMembersFromTable(TableIndex tableIndex) where TMember : IMetadataMember, IModuleProvider { //IL_0015: 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_002f: 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_006e: Unknown result type (might be due to invalid IL or missing references) int count = ((ICollection)_module.DotNetDirectory.Metadata.GetStream().GetTable(tableIndex)).Count; IList resultList = GetResultList(tableIndex); MetadataToken token = default(MetadataToken); for (uint num = 1u; num <= count; num++) { ((MetadataToken)(ref token))..ctor(tableIndex, num); TMember item = (TMember)_module.LookupMember(token); if (item.Module == _module) { resultList.Add(item); continue; } _freeRids[tableIndex].Add(num); resultList.Add(default(TMember)); } } private void CollectNewlyAddedFixedMembers() { foreach (TypeDefinition allType in _module.GetAllTypes()) { InsertOrAppendIfNew(allType, queueIfNoSlotsAvailable: true); for (int i = 0; i < allType.Fields.Count; i++) { InsertOrAppendIfNew(allType.Fields[i], queueIfNoSlotsAvailable: true); } for (int j = 0; j < allType.Methods.Count; j++) { MethodDefinition methodDefinition = allType.Methods[j]; InsertOrAppendIfNew(methodDefinition, queueIfNoSlotsAvailable: true); for (int k = 0; k < methodDefinition.ParameterDefinitions.Count; k++) { InsertOrAppendIfNew(methodDefinition.ParameterDefinitions[k], queueIfNoSlotsAvailable: true); } } for (int l = 0; l < allType.Properties.Count; l++) { InsertOrAppendIfNew(allType.Properties[l], queueIfNoSlotsAvailable: true); } for (int m = 0; m < allType.Events.Count; m++) { InsertOrAppendIfNew(allType.Events[m], queueIfNoSlotsAvailable: true); } } } private void AddFloatingMembers() { foreach (IMetadataMember item in _floatingMembers[(TableIndex)2]) { InsertOrAppendIfNew((TypeDefinition)item, queueIfNoSlotsAvailable: false); } foreach (IMetadataMember item2 in _floatingMembers[(TableIndex)4]) { InsertOrAppendIfNew((FieldDefinition)item2, queueIfNoSlotsAvailable: false); } foreach (IMetadataMember item3 in _floatingMembers[(TableIndex)6]) { InsertOrAppendIfNew((MethodDefinition)item3, queueIfNoSlotsAvailable: false); } foreach (IMetadataMember item4 in _floatingMembers[(TableIndex)8]) { InsertOrAppendIfNew((ParameterDefinition)item4, queueIfNoSlotsAvailable: false); } foreach (IMetadataMember item5 in _floatingMembers[(TableIndex)23]) { InsertOrAppendIfNew((PropertyDefinition)item5, queueIfNoSlotsAvailable: false); } foreach (IMetadataMember item6 in _floatingMembers[(TableIndex)20]) { InsertOrAppendIfNew((EventDefinition)item6, queueIfNoSlotsAvailable: false); } } private void InsertOrAppendIfNew(TMember member, bool queueIfNoSlotsAvailable) where TMember : class, IMetadataMember { //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_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_0016: 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_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_0043: 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_004a: 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_006f: Expected I4, but got Unknown //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Invalid comparison between Unknown and I4 //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_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Invalid comparison between Unknown and I4 //IL_0217: 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_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0115: 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_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) MetadataToken metadataToken = member.MetadataToken; TableIndex table = ((MetadataToken)(ref metadataToken)).Table; IList resultList = GetResultList(table); if (!IsNewMember(resultList, member)) { return; } IList list = _freeRids[table]; metadataToken = member.MetadataToken; TableIndex table2 = ((MetadataToken)(ref metadataToken)).Table; MemberDiscoveryFlags memberDiscoveryFlags; switch (table2 - 2) { default: if ((int)table2 != 20) { if ((int)table2 != 23) { goto case 1; } memberDiscoveryFlags = MemberDiscoveryFlags.PreservePropertyOrder; break; } memberDiscoveryFlags = MemberDiscoveryFlags.PreserveEventOrder; break; case 0: memberDiscoveryFlags = MemberDiscoveryFlags.PreserveTypeOrder; break; case 2: memberDiscoveryFlags = MemberDiscoveryFlags.PreserveFieldOrder; break; case 4: memberDiscoveryFlags = MemberDiscoveryFlags.PreserveMethodOrder; break; case 6: memberDiscoveryFlags = MemberDiscoveryFlags.PreserveParameterOrder; break; case 1: case 3: case 5: throw new ArgumentOutOfRangeException("member"); } MemberDiscoveryFlags memberDiscoveryFlags2 = memberDiscoveryFlags; metadataToken = member.MetadataToken; if (((MetadataToken)(ref metadataToken)).Rid != 0 && (_flags & memberDiscoveryFlags2) == memberDiscoveryFlags2) { while (true) { long num = resultList.Count; metadataToken = member.MetadataToken; if (num >= ((MetadataToken)(ref metadataToken)).Rid) { break; } resultList.Add(null); list.Add((uint)resultList.Count); } metadataToken = member.MetadataToken; TMember val = resultList[(int)(((MetadataToken)(ref metadataToken)).Rid - 1)]; if (val != null) { DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(33, 3); defaultInterpolatedStringHandler.AppendFormatted(val.SafeToString()); defaultInterpolatedStringHandler.AppendLiteral(" and "); defaultInterpolatedStringHandler.AppendFormatted(member.SafeToString()); defaultInterpolatedStringHandler.AppendLiteral(" are assigned the same RID "); metadataToken = member.MetadataToken; defaultInterpolatedStringHandler.AppendFormatted(((MetadataToken)(ref metadataToken)).Rid); defaultInterpolatedStringHandler.AppendLiteral("."); throw new ArgumentException(defaultInterpolatedStringHandler.ToStringAndClear()); } metadataToken = member.MetadataToken; resultList[(int)(((MetadataToken)(ref metadataToken)).Rid - 1)] = member; metadataToken = member.MetadataToken; list.Remove(((MetadataToken)(ref metadataToken)).Rid); } else if (list.Count > 0) { uint num2 = list[0]; list.RemoveAt(0); resultList[(int)(num2 - 1)] = member; } else if (queueIfNoSlotsAvailable) { _floatingMembers[table].Add(member); } else { resultList.Add(member); } } private static bool IsNewMember(IList existingMembers, TMember member) where TMember : class, IMetadataMember { //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_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_0039: 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) MetadataToken metadataToken = member.MetadataToken; if (((MetadataToken)(ref metadataToken)).Rid != 0) { metadataToken = member.MetadataToken; if (((MetadataToken)(ref metadataToken)).Rid <= existingMembers.Count) { metadataToken = member.MetadataToken; return existingMembers[(int)(((MetadataToken)(ref metadataToken)).Rid - 1)] != member; } } return true; } private void StuffFreeMemberSlots() { //IL_0078: Unknown result type (might be due to invalid IL or missing references) if (_freeRids.Values.All((IList q) => q.Count == 0)) { return; } string placeHolderNamespace = Guid.NewGuid().ToString("B"); TypeDefinition typeDefinition; if (_freeRids[(TableIndex)2].Count == 0) { typeDefinition = new PlaceHolderTypeDefinition(_module, placeHolderNamespace, new MetadataToken((TableIndex)2, 0u)); _result.Types.Add(typeDefinition); } else { uint num = _freeRids[(TableIndex)2][0]; StuffFreeMemberSlots((TypeDefinition?)null, (TableIndex)2, (Func)((TypeDefinition _, MetadataToken token) => new PlaceHolderTypeDefinition(_module, placeHolderNamespace, token))); typeDefinition = _result.Types[(int)(num - 1)]; } StuffFreeMemberSlots(typeDefinition, (TableIndex)4, AddPlaceHolderField); StuffFreeMemberSlots(typeDefinition, (TableIndex)6, AddPlaceHolderMethod); StuffFreeMemberSlots(typeDefinition, (TableIndex)23, AddPlaceHolderProperty); StuffFreeMemberSlots(typeDefinition, (TableIndex)20, AddPlaceHolderEvent); StuffFreeMemberSlots(typeDefinition, (TableIndex)8, AddPlaceHolderParameter); } private void StuffFreeMemberSlots(TypeDefinition? placeHolderType, TableIndex tableIndex, Func createPlaceHolder) where TMember : IMetadataMember { //IL_0006: 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_0028: 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) IList list = _freeRids[tableIndex]; IList resultList = GetResultList(tableIndex); MetadataToken arg = default(MetadataToken); while (list.Count > 0) { uint num = list[0]; list.RemoveAt(0); ((MetadataToken)(ref arg))..ctor(tableIndex, num); resultList[(int)(num - 1)] = createPlaceHolder(placeHolderType, arg); } } private FieldDefinition AddPlaceHolderField(TypeDefinition placeHolderType, MetadataToken token) { FieldDefinition fieldDefinition = new FieldDefinition(Utf8String.op_Implicit("PlaceHolderField_" + ((MetadataToken)(ref token)).Rid), (FieldAttributes)6, _module.CorLibTypeFactory.Object); placeHolderType.Fields.Add(fieldDefinition); return fieldDefinition; } private MethodDefinition AddPlaceHolderMethod(TypeDefinition placeHolderType, MetadataToken token) { MethodDefinition methodDefinition = new MethodDefinition(Utf8String.op_Implicit("PlaceHolderMethod_" + ((MetadataToken)(ref token)).Rid), (MethodAttributes)1478, MethodSignature.CreateInstance(_module.CorLibTypeFactory.Void)); placeHolderType.Methods.Add(methodDefinition); _allPlaceHolderMethods.Add(methodDefinition); return methodDefinition; } private ParameterDefinition AddPlaceHolderParameter(TypeDefinition placeHolderType, MetadataToken token) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (_allPlaceHolderMethods.Count == 0) { InsertOrAppendIfNew(AddPlaceHolderMethod(placeHolderType, token), queueIfNoSlotsAvailable: false); } int index = _placeHolderParameterCounter % _allPlaceHolderMethods.Count; int num = _placeHolderParameterCounter / _allPlaceHolderMethods.Count; MethodDefinition methodDefinition = _allPlaceHolderMethods[index]; if (num > 0) { methodDefinition.Signature.ParameterTypes.Add(_module.CorLibTypeFactory.Object); } ParameterDefinition parameterDefinition = new ParameterDefinition((ushort)num, Utf8String.op_Implicit((string)null), (ParameterAttributes)0); methodDefinition.ParameterDefinitions.Add(parameterDefinition); _placeHolderParameterCounter++; return parameterDefinition; } private PropertyDefinition AddPlaceHolderProperty(TypeDefinition placeHolderType, MetadataToken token) { PropertyDefinition propertyDefinition = new PropertyDefinition(Utf8String.op_Implicit("PlaceHolderProperty_" + ((MetadataToken)(ref token)).Rid), (PropertyAttributes)0, PropertySignature.CreateStatic(_module.CorLibTypeFactory.Object)); MethodDefinition methodDefinition = new MethodDefinition(Utf8String.op_Implicit($"get_{propertyDefinition.Name}"), (MethodAttributes)3526, MethodSignature.CreateStatic(_module.CorLibTypeFactory.Object)); placeHolderType.Methods.Add(methodDefinition); placeHolderType.Properties.Add(propertyDefinition); propertyDefinition.Semantics.Add(new MethodSemantics(methodDefinition, (MethodSemanticsAttributes)2)); InsertOrAppendIfNew(methodDefinition, queueIfNoSlotsAvailable: false); return propertyDefinition; } private EventDefinition AddPlaceHolderEvent(TypeDefinition placeHolderType, MetadataToken token) { EventDefinition eventDefinition = new EventDefinition(Utf8String.op_Implicit("PlaceHolderEvent_" + ((MetadataToken)(ref token)).Rid), (EventAttributes)0, _eventHandlerTypeRef); MethodSignature signature = MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void, _module.CorLibTypeFactory.Object, _eventHandlerTypeSig); MethodDefinition methodDefinition = new MethodDefinition(Utf8String.op_Implicit($"add_{eventDefinition.Name}"), (MethodAttributes)3526, signature); MethodDefinition methodDefinition2 = new MethodDefinition(Utf8String.op_Implicit($"remove_{eventDefinition.Name}"), (MethodAttributes)3526, signature); placeHolderType.Methods.Add(methodDefinition); placeHolderType.Methods.Add(methodDefinition2); placeHolderType.Events.Add(eventDefinition); eventDefinition.Semantics.Add(new MethodSemantics(methodDefinition, (MethodSemanticsAttributes)8)); eventDefinition.Semantics.Add(new MethodSemantics(methodDefinition2, (MethodSemanticsAttributes)16)); InsertOrAppendIfNew(methodDefinition, queueIfNoSlotsAvailable: false); InsertOrAppendIfNew(methodDefinition2, queueIfNoSlotsAvailable: false); return eventDefinition; } } [Flags] public enum MemberDiscoveryFlags { None = 0, PreserveTypeOrder = 1, PreserveFieldOrder = 2, PreserveMethodOrder = 4, PreserveParameterOrder = 8, PreserveEventOrder = 0x10, PreservePropertyOrder = 0x20 } public class MemberDiscoveryResult { public List Types { get; } = new List(); public List Fields { get; } = new List(); public List Methods { get; } = new List(); public List Parameters { get; } = new List(); public List Properties { get; } = new List(); public List Events { get; } = new List(); } }