public uint GetHashValueOffset(PEFile peFile) { fixed (FileRow * pThis = &this) { var pHashValue = (byte*)pThis + StreamID.Strings.IndexSize(peFile); return StreamID.Blob.IndexSize(peFile) == 2 ? *(ushort*) pHashValue : *(uint*) pHashValue; } }
public uint GetNameOffset(PEFile peFile) { fixed (FileRow* pThis = &this) { var pName = (byte*) pThis + 4; return StreamID.Strings.IndexSize(peFile) == 2 ? *(ushort*) pName : *(uint*) pName; } }
//# Creates a new assembly, inserting it into the provided project. public Assembly(Project project, string fileName) { try { m_project = project.CheckNotNull("project"); m_peFile = new PEFile(this, fileName); var assemblyRowCount = MetadataTable.Assembly.RowCount(m_peFile); if (assemblyRowCount <= 0) { throw new FileLoadException("Not an assembly", fileName); } if (assemblyRowCount > 1) { throw new FileLoadException("Too many rows in the assembly table."); } m_modules = new ModuleCollection(this, m_peFile); project.Add(this); } catch { Dispose(); throw; } }
internal GenericParameter(GenericParameterRow * pRow, PEFile peFile, IGenericParameterScope parent) : base(TypeKind.GenericParameter) { m_pRow = (GenericParameterRow *)FluentAsserts.CheckNotNull((void*) pRow, "pRow"); m_peFile = peFile.CheckNotNull("peFile"); m_parent = parent.CheckNotNull("parent"); }
private Module(Assembly assembly, ModuleRow* moduleRow, PEFile peFile) { m_lockObject = new object(); m_assembly = assembly.CheckNotNull("assembly"); m_pModuleRow = (ModuleRow *)FluentAsserts.CheckNotNull((void *)moduleRow, "moduleRow"); m_peFile = peFile.CheckNotNull("peFile"); m_containsMetadata = true; }
internal unsafe MethodImplementation(MethodImplRow* pRow, PEFile peFile) { FluentAsserts.CheckNotNull((void *)pRow, "pRow"); peFile.CheckNotNull("peFile"); m_implementedMethod = new MethodReference(pRow->GetImplementedMethod(peFile)); m_implementingMethod = new MethodReference(pRow->GetImplementingMethod(peFile)); }
public OneBasedIndex GetClass(PEFile peFile) { fixed (InterfaceImplRow* pThis = &this) { if (MetadataTable.TypeDef.IndexSize(peFile) == 2) { return new OneBasedIndex(*(ushort*) pThis); } return new OneBasedIndex(*(uint*) pThis); } }
public OneBasedIndex GetParent(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (EventMapRow * pThis = &this) { if (MetadataTable.TypeDef.IndexSize(peFile) == 2) { return new OneBasedIndex(*(ushort*) pThis); } return new OneBasedIndex(*(uint*) pThis); } }
public HasSemantics GetAssosication(PEFile peFile) { fixed (MethodSemanticsRow* pThis = &this) { var pAssociation = (byte*) pThis + 2 + MetadataTable.MethodDef.IndexSize(peFile); if (CodedIndex.HasSemantics.IndexSize(peFile) == 2) { return new HasSemantics(new OneBasedIndex(*(ushort*) pAssociation)); } return new HasSemantics(new OneBasedIndex(*(uint*) pAssociation)); } }
public OneBasedIndex GetMethodIndex(PEFile peFile) { fixed (MethodSemanticsRow* pThis = &this) { var pMethod = (byte*) pThis + 2; if (MetadataTable.MethodDef.IndexSize(peFile) == 2) { return new OneBasedIndex(*(ushort*) pMethod); } return new OneBasedIndex(*(uint*) pMethod); } }
public OneBasedIndex GetOwner(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (GenericParameterConstraintRow* pThis = &this) { if (MetadataTable.GenericParam.IndexSize(peFile) == 2) { return new OneBasedIndex(*(ushort*) pThis); } return new OneBasedIndex(*(uint*) pThis); } }
public uint GetNameOffset(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (FieldRow * pThis = &this) { if (StreamID.Strings.IndexSize(peFile) == 2) { return *(ushort*) pThis; } return *(uint*) pThis; } }
public OneBasedIndex GetEventListIndex(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (EventMapRow* pThis = &this) { var pEventList = (byte*) pThis + MetadataTable.TypeDef.IndexSize(peFile); if (MetadataTable.Event.IndexSize(peFile) == 2) { return new OneBasedIndex(*(ushort*) pEventList); } return new OneBasedIndex(*(uint*)pEventList); } }
public uint GetNativeTypeOffset(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (FieldMarshalRow * pThis = &this) { var pNativeType = (byte*) pThis + CodedIndex.HasFieldMarshal.IndexSize(peFile); if (StreamID.Blob.IndexSize(peFile) == 2) { return *(ushort*) pNativeType; } return *(uint*) pNativeType; } }
public OneBasedIndex GetFieldIndex(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (FieldLayoutRow * pThis = &this) { byte* pField = (byte *)pThis + 4; if (MetadataTable.Field.IndexSize(peFile) == 2) { return new OneBasedIndex(*(ushort *)pField); } return new OneBasedIndex(*(uint*) pField); } }
public MethodDefOrRef GetImplementingMethod(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (MethodImplRow* pThis = &this) { var pImplementingMethod = (byte*) pThis + MetadataTable.TypeDef.IndexSize(peFile); if (CodedIndex.MethodDefOrRef.IndexSize(peFile) == 2) { return new MethodDefOrRef(new OneBasedIndex(*(ushort*) pImplementingMethod)); } return new MethodDefOrRef(new OneBasedIndex(*(uint*) pImplementingMethod)); } }
public uint GetMvidOffset(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (ModuleRow* pThis = &this) { var pMvid = (byte*) pThis + 2 + StreamID.Strings.IndexSize(peFile); if (StreamID.Guid.IndexSize(peFile) == 2) { return *(ushort*) pMvid; } return *(uint*) pMvid; } }
public uint GetEncBaseId(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (ModuleRow* pThis = &this) { var pBaseId = (byte*) pThis + 2 + StreamID.Strings.IndexSize(peFile) + StreamID.Guid.IndexSize(peFile)*2; if (StreamID.Guid.IndexSize(peFile) == 2) { return *(ushort*) pBaseId; } return *(uint*) pBaseId; } }
public uint GetCultureOffset(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (AssemblyRow* pThis = &this) { var pCulture = (byte*) pThis + 16 + StreamID.Blob.IndexSize(peFile) + StreamID.Strings.IndexSize(peFile); if (StreamID.Strings.IndexSize(peFile) == 2) { return *(ushort*) pCulture; } return *(uint*) pCulture; } }
public uint GetTypeSignatureOffset(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (PropertyRow * pThis = & this) { var pType = (byte*) pThis + 2 + StreamID.Strings.IndexSize(peFile); if (StreamID.Blob.IndexSize(peFile) == 2) { return *(ushort*) pType; } return *(uint*) pType; } }
public uint GetNameOffset(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (GenericParameterRow* pThis = &this) { var pOwner = (byte*) pThis + 4 + CodedIndex.TypeOrMethodDef.IndexSize(peFile); if (StreamID.Strings.IndexSize(peFile) == 2) { return *(ushort*) pOwner; } return *(uint*) pOwner; } }
public uint GetSignatureOffset(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (MethodDefRow * pThis = &this) { var pSignature = (byte *)pThis + 8 + StreamID.Strings.IndexSize(peFile); if (StreamID.Blob.IndexSize(peFile) == 2) { return *(ushort *)(pSignature); } return *(uint *)pSignature; } }
public uint GetNameOffset(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (MethodDefRow * pThis = &this) { var pName = (byte *)pThis +8; if (StreamID.Strings.IndexSize(peFile) == 2) { return *(ushort *)pName; } return *(uint *)pName; } }
public OneBasedIndex GetEnclosingClass(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (NestedClassRow* pThis = &this) { var pEnclosingClass = (byte*) pThis + MetadataTable.TypeDef.IndexSize(peFile); if (MetadataTable.TypeDef.IndexSize(peFile) == 2) { return new OneBasedIndex(*(ushort*) pEnclosingClass); } return new OneBasedIndex(*(uint*) pEnclosingClass); } }
public uint GetNameIndex(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed(PropertyRow * pThis = &this) { var pName = (byte*) pThis + 2; if (StreamID.Strings.IndexSize(peFile) == 2) { return *(ushort*) pName; } return *(uint*) pName; } }
public HasCustomAttribute GetParent(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (CustomAttributeRow * pThis = &this) { uint index; if (CodedIndex.HasCustomAttribute.IndexSize(peFile) == 2) { index = *(ushort*) pThis; } else { index = *(uint*) pThis; } return new HasCustomAttribute(new OneBasedIndex(index)); } }
public TypeDefOrRef GetInterface(PEFile peFile) { fixed (InterfaceImplRow* pThis = &this) { var pInterface = (byte*) pThis + MetadataTable.TypeDef.IndexSize(peFile); uint index; if (CodedIndex.TypeDefOrRef.IndexSize(peFile) == 2) { index = *(ushort*) pInterface; } else { index = *(uint*) pInterface; } return new TypeDefOrRef(new OneBasedIndex(index)); } }
public HasFieldMarshal GetParent(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (FieldMarshalRow* pThis = &this) { uint index; if (CodedIndex.HasFieldMarshal.IndexSize(peFile) == 2) { index = *(ushort*) pThis; } else { index = *(uint*) pThis; } return new HasFieldMarshal(new OneBasedIndex(index)); } }
public uint GetValueOffset(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (CustomAttributeRow * pThis = &this) { var pValue = (byte*)pThis + CodedIndex.HasCustomAttribute.IndexSize(peFile) + CodedIndex.CustomAttributeConstructor.IndexSize(peFile); if (StreamID.Blob.IndexSize(peFile) == 2) { return *(ushort*) pValue; } return *(uint*) pValue; } }
public CustomAttributeConstructor GetConstructor(PEFile peFile) { peFile.CheckNotNull("peFile"); fixed (CustomAttributeRow * pThis = &this) { var pConstructor = (byte*) pThis + CodedIndex.HasCustomAttribute.IndexSize(peFile); uint index; if (CodedIndex.CustomAttributeConstructor.IndexSize(peFile) == 2) { index = *(ushort*) pConstructor; } else { index = *(uint*) pConstructor; } return new CustomAttributeConstructor(new OneBasedIndex(index)); } }
public ExportedTypeTableTreeNode(PEFile module) : base(HandleKind.ExportedType, module) { }
// reference: https://github.com/NuGet/NuGet.Jobs/blob/26c23697fee363d3133171f71e129cda9b5a3707/src/Validation.Symbols/SymbolsValidatorService.cs#L186 private bool VerifyPdbChecksums() { // Nothing to verify as the pdb is inside the PE file if (_pdbType == PdbType.Embedded) { return(true); } if (_pdbType == PdbType.Portable) { var checksumRecords = _peReader.ReadDebugDirectory() .Where(entry => entry.Type == DebugDirectoryEntryType.PdbChecksum) .Select(_peReader.ReadPdbChecksumDebugDirectoryData) .ToList(); if (checksumRecords.Count == 0) { return(false); } var hashes = new Dictionary <string, byte[]>(); if (_reader.DebugMetadataHeader == null) { return(false); } var idOffset = _reader.DebugMetadataHeader.IdStartOffset; foreach (var checksumRecord in checksumRecords) { if (!hashes.TryGetValue(checksumRecord.AlgorithmName, out var hash)) { var han = new HashAlgorithmName(checksumRecord.AlgorithmName); using (var hashAlg = IncrementalHash.CreateHash(han)) { hashAlg.AppendData(_pdbBytes !, 0, idOffset); hashAlg.AppendData(new byte[20]); var offset = idOffset + 20; var count = _pdbBytes !.Length - offset; hashAlg.AppendData(_pdbBytes !, offset, count); hash = hashAlg.GetHashAndReset(); } hashes.Add(checksumRecord.AlgorithmName, hash); } if (checksumRecord.Checksum.ToArray().SequenceEqual(hash)) { // found the right checksum return(true); } } // Not found any checksum record that matches the PDB. return(false); } // Deal with Windows PDB's using var pdbBytesStream = new MemoryStream(_pdbBytes !); var pdbFile = new PDBFile(new StreamAddressSpace(pdbBytesStream)); using var peBytesStream = new MemoryStream(_peBytes !); var peFile = new PEFile(new StreamAddressSpace(peBytesStream)); var pdb = peFile.Pdbs.FirstOrDefault(p => p.Signature == pdbFile.Signature && p.Age == pdbFile.Age); if (pdb != null) { return(true); } return(false); }
public EntityReference(string protocol, PEFile module, Handle handle) : this(module, handle) { this.Protocol = protocol ?? "decompile"; }
/// <summary> /// Creates the data directory headers stored in the optional header of the PE file. /// </summary> /// <param name="peFile">The (incomplete) PE file that contains the sections.</param> /// <param name="image">The image to create the data directories for.</param> /// <param name="context">The object containing the intermediate values used during the PE file construction.</param> /// <returns>The data directories.</returns> protected abstract IEnumerable <DataDirectory> CreateDataDirectories(PEFile peFile, IPEImage image, TContext context);
public override bool ShowMember(IEntity member) { PEFile assembly = member.ParentModule.PEFile; return(showAllMembers || !CSharpDecompiler.MemberIsHidden(assembly, member.MetadataToken, new DecompilationOptions().DecompilerSettings)); }
public MethodSemanticsTableTreeNode(PEFile module) : base((HandleKind)0x18, module) { }
public DecompilerTypeSystem GetOrCreateTypeSystem(PEFile module) { return(typeSystemCache.GetOrAdd(module, m => new DecompilerTypeSystem(m, m.GetAssemblyResolver()))); }
public LoadResult(PEFile peFile) { this.PEFile = peFile ?? throw new ArgumentNullException(nameof(peFile)); }
public PEFile?ResolveModule(PEFile mainModule, string moduleName) { return(ResolveModuleAsync(mainModule, moduleName).GetAwaiter().GetResult()); }
public BamlDecompilerTypeSystem(PEFile mainModule, IAssemblyResolver assemblyResolver) { if (mainModule == null) { throw new ArgumentNullException(nameof(mainModule)); } if (assemblyResolver == null) { throw new ArgumentNullException(nameof(assemblyResolver)); } // Load referenced assemblies and type-forwarder references. // This is necessary to make .NET Core/PCL binaries work better. var referencedAssemblies = new List <PEFile>(); var assemblyReferenceQueue = new Queue <(bool IsAssembly, PEFile MainModule, object Reference)>(); var mainMetadata = mainModule.Metadata; foreach (var h in mainMetadata.GetModuleReferences()) { var moduleRef = mainMetadata.GetModuleReference(h); var moduleName = mainMetadata.GetString(moduleRef.Name); foreach (var fileHandle in mainMetadata.AssemblyFiles) { var file = mainMetadata.GetAssemblyFile(fileHandle); if (mainMetadata.StringComparer.Equals(file.Name, moduleName) && file.ContainsMetadata) { assemblyReferenceQueue.Enqueue((false, mainModule, moduleName)); break; } } } foreach (var refs in mainModule.AssemblyReferences) { assemblyReferenceQueue.Enqueue((true, mainModule, refs)); } foreach (var bamlReference in defaultBamlReferences) { assemblyReferenceQueue.Enqueue((true, mainModule, AssemblyNameReference.Parse(bamlReference))); } var comparer = KeyComparer.Create(((bool IsAssembly, PEFile MainModule, object Reference)reference) => reference.IsAssembly ? "A:" + ((IAssemblyReference)reference.Reference).FullName : "M:" + reference.Reference); var processedAssemblyReferences = new HashSet <(bool IsAssembly, PEFile Parent, object Reference)>(comparer); while (assemblyReferenceQueue.Count > 0) { var asmRef = assemblyReferenceQueue.Dequeue(); if (!processedAssemblyReferences.Add(asmRef)) { continue; } PEFile asm; if (asmRef.IsAssembly) { asm = assemblyResolver.Resolve((IAssemblyReference)asmRef.Reference); } else { asm = assemblyResolver.ResolveModule(asmRef.MainModule, (string)asmRef.Reference); } if (asm != null) { referencedAssemblies.Add(asm); var metadata = asm.Metadata; foreach (var h in metadata.ExportedTypes) { var exportedType = metadata.GetExportedType(h); switch (exportedType.Implementation.Kind) { case SRM.HandleKind.AssemblyReference: assemblyReferenceQueue.Enqueue((true, asm, new AssemblyReference(asm, (SRM.AssemblyReferenceHandle)exportedType.Implementation))); break; case SRM.HandleKind.AssemblyFile: var file = metadata.GetAssemblyFile((SRM.AssemblyFileHandle)exportedType.Implementation); assemblyReferenceQueue.Enqueue((false, asm, metadata.GetString(file.Name))); break; } } } } var mainModuleWithOptions = mainModule.WithOptions(TypeSystemOptions.Default); var referencedAssembliesWithOptions = referencedAssemblies.Select(file => file.WithOptions(TypeSystemOptions.Default)); // Primitive types are necessary to avoid assertions in ILReader. // Fallback to MinimalCorlib to provide the primitive types. if (!HasType(KnownTypeCode.Void) || !HasType(KnownTypeCode.Int32)) { Init(mainModule.WithOptions(TypeSystemOptions.Default), referencedAssembliesWithOptions.Concat(new[] { MinimalCorlib.Instance })); } else { Init(mainModuleWithOptions, referencedAssembliesWithOptions); } this.MainModule = (MetadataModule)base.MainModule; bool HasType(KnownTypeCode code) { TopLevelTypeName name = KnownTypeReference.Get(code).TypeName; if (mainModule.GetTypeDefinition(name) != null) { return(true); } foreach (var file in referencedAssemblies) { if (file.GetTypeDefinition(name) != null) { return(true); } } return(false); } }
public AssemblyTableTreeNode(PEFile module) : base(HandleKind.AssemblyDefinition, module) { }
/// <summary> /// Gets the relative virtual address (RVA) to the entrypoint of the PE file. /// </summary> /// <param name="peFile">The (incomplete) PE file containing the entrypoint.</param> /// <param name="image">The image that the PE file was based on.</param> /// <param name="context">The object containing the intermediate values used during the PE file construction.</param> /// <returns>The relative virtual address to the entrypoin.</returns> protected abstract uint GetEntrypointAddress(PEFile peFile, IPEImage image, TContext context);
/// <summary> /// Gets the section alignment for the new PE file. /// </summary> /// <param name="peFile">The (incomplete) PE file to be aligned.</param> /// <param name="image">The image that the PE file was based on.</param> /// <param name="context">The object containing the intermediate values used during the PE file construction.</param> /// <returns> /// The section alignment. Must be greater or equal to the file alignment. Default is the page size for /// the architecture. /// </returns> protected abstract uint GetSectionAlignment(PEFile peFile, IPEImage image, TContext context);
/// <summary> /// Gets the image base for the new PE file. /// </summary> /// <param name="peFile">The (incomplete) PE file to determine the image base for.</param> /// <param name="image">The image that the PE file was based on.</param> /// <param name="context">The object containing the intermediate values used during the PE file construction.</param> /// <returns>The image base.</returns> protected abstract uint GetImageBase(PEFile peFile, IPEImage image, TContext context);
/// <summary> /// Reads a .NET assembly from the provided input file. /// </summary> /// <param name="file">The portable executable file to load.</param> /// <returns>The module.</returns> /// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception> public static AssemblyDefinition FromFile(PEFile file) => FromImage(PEImage.FromFile(file));
/// <summary>Create instance of IAT class</summary> /// <param name="parent">Data directory</param> public Iat(PEFile parent) : base(parent, WinNT.IMAGE_DIRECTORY_ENTRY.IAT) { }
public static bool HasCodeViewDebugDirectoryEntry(PEFile file) { return(file.Reader.ReadDebugDirectory().Any(entry => entry.Type == DebugDirectoryEntryType.CodeView)); }
public PEFile ResolveModule(PEFile mainModule, string moduleName) { return(parent.LookupReferencedModule(mainModule, moduleName)?.GetPEFileOrNull()); }
public override string GetEntityName(PEFile module, EntityHandle handle, bool fullName, bool omitGenerics) { MetadataReader metadata = module.Metadata; switch (handle.Kind) { case HandleKind.TypeDefinition: return(ToCSharpString(metadata, (TypeDefinitionHandle)handle, fullName, omitGenerics)); case HandleKind.FieldDefinition: var fd = metadata.GetFieldDefinition((FieldDefinitionHandle)handle); var declaringType = fd.GetDeclaringType(); if (fullName) { return(ToCSharpString(metadata, declaringType, fullName, omitGenerics) + "." + metadata.GetString(fd.Name)); } return(metadata.GetString(fd.Name)); case HandleKind.MethodDefinition: var md = metadata.GetMethodDefinition((MethodDefinitionHandle)handle); declaringType = md.GetDeclaringType(); string methodName = metadata.GetString(md.Name); switch (methodName) { case ".ctor": case ".cctor": var td = metadata.GetTypeDefinition(declaringType); methodName = ReflectionHelper.SplitTypeParameterCountFromReflectionName(metadata.GetString(td.Name)); break; case "Finalize": const MethodAttributes finalizerAttributes = (MethodAttributes.Virtual | MethodAttributes.Family | MethodAttributes.HideBySig); if ((md.Attributes & finalizerAttributes) != finalizerAttributes) { goto default; } MethodSignature <IType> methodSignature = md.DecodeSignature(MetadataExtensions.MinimalSignatureTypeProvider, default); if (methodSignature.GenericParameterCount != 0 || methodSignature.ParameterTypes.Length != 0) { goto default; } td = metadata.GetTypeDefinition(declaringType); methodName = "~" + ReflectionHelper.SplitTypeParameterCountFromReflectionName(metadata.GetString(td.Name)); break; default: var genericParams = md.GetGenericParameters(); if (!omitGenerics && genericParams.Count > 0) { methodName += "<"; int i = 0; foreach (var h in genericParams) { if (i > 0) { methodName += ","; } var gp = metadata.GetGenericParameter(h); methodName += metadata.GetString(gp.Name); } methodName += ">"; } break; } if (fullName) { return(ToCSharpString(metadata, declaringType, fullName, omitGenerics) + "." + methodName); } return(methodName); case HandleKind.EventDefinition: var ed = metadata.GetEventDefinition((EventDefinitionHandle)handle); declaringType = metadata.GetMethodDefinition(ed.GetAccessors().GetAny()).GetDeclaringType(); if (fullName) { return(ToCSharpString(metadata, declaringType, fullName, omitGenerics) + "." + metadata.GetString(ed.Name)); } return(metadata.GetString(ed.Name)); case HandleKind.PropertyDefinition: var pd = metadata.GetPropertyDefinition((PropertyDefinitionHandle)handle); declaringType = metadata.GetMethodDefinition(pd.GetAccessors().GetAny()).GetDeclaringType(); if (fullName) { return(ToCSharpString(metadata, declaringType, fullName, omitGenerics) + "." + metadata.GetString(pd.Name)); } return(metadata.GetString(pd.Name)); default: return(null); } }
LoadedAssembly LookupReferencedModuleInternal(PEFile mainModule, string moduleName) { string file; LoadedAssembly asm; lock (loadingAssemblies) { foreach (LoadedAssembly loaded in assemblyList.GetAssemblies()) { var reader = loaded.GetPEFileOrNull()?.Metadata; if (reader == null || reader.IsAssembly) { continue; } var moduleDef = reader.GetModuleDefinition(); if (moduleName.Equals(reader.GetString(moduleDef.Name), StringComparison.OrdinalIgnoreCase)) { LoadedAssemblyReferencesInfo.AddMessageOnce(moduleName, MessageKind.Info, "Success - Found in Assembly List"); return(loaded); } } file = Path.Combine(Path.GetDirectoryName(mainModule.FileName), moduleName); if (!File.Exists(file)) { return(null); } foreach (LoadedAssembly loaded in assemblyList.GetAssemblies()) { if (loaded.FileName.Equals(file, StringComparison.OrdinalIgnoreCase)) { return(loaded); } } if (file != null && loadingAssemblies.TryGetValue(file, out asm)) { return(asm); } if (assemblyLoadDisableCount > 0) { return(null); } if (file != null) { LoadedAssemblyReferencesInfo.AddMessage(moduleName, MessageKind.Info, "Success - Loading from: " + file); asm = new LoadedAssembly(assemblyList, file) { IsAutoLoaded = true }; } else { LoadedAssemblyReferencesInfo.AddMessageOnce(moduleName, MessageKind.Error, "Could not find reference: " + moduleName); return(null); } loadingAssemblies.Add(file, asm); } App.Current.Dispatcher.BeginInvoke((Action) delegate() { lock (assemblyList.assemblies) { assemblyList.assemblies.Add(asm); } lock (loadingAssemblies) { loadingAssemblies.Remove(file); } }); return(asm); }
public override CodeMappingInfo GetCodeMappingInfo(PEFile module, EntityHandle member) { return(CSharpDecompiler.GetCodeMappingInfo(module, member)); }
/// <summary> /// Load native symbols and modules (i.e. DAC, DBI). /// </summary> /// <param name="callback">called back for each symbol file loaded</param> /// <param name="parameter">callback parameter</param> /// <param name="config">Target configuration: Windows, Linux or OSX</param> /// <param name="moduleFilePath">module path</param> /// <param name="address">module base address</param> /// <param name="size">module size</param> /// <param name="readMemory">read memory callback delegate</param> private void LoadNativeSymbols( IntPtr self, SymbolFileCallback callback, IntPtr parameter, RuntimeConfiguration config, string moduleFilePath, ulong address, uint size) { if (_symbolService.IsSymbolStoreEnabled) { try { Stream stream = MemoryService.CreateMemoryStream(address, size); KeyGenerator generator = null; if (config == RuntimeConfiguration.UnixCore) { var elfFile = new ELFFile(new StreamAddressSpace(stream), 0, true); generator = new ELFFileKeyGenerator(Tracer.Instance, elfFile, moduleFilePath); } else if (config == RuntimeConfiguration.OSXCore) { var machOFile = new MachOFile(new StreamAddressSpace(stream), 0, true); generator = new MachOFileKeyGenerator(Tracer.Instance, machOFile, moduleFilePath); } else if (config == RuntimeConfiguration.WindowsCore || config == RuntimeConfiguration.WindowsDesktop) { var peFile = new PEFile(new StreamAddressSpace(stream), true); generator = new PEFileKeyGenerator(Tracer.Instance, peFile, moduleFilePath); } else { Trace.TraceError("LoadNativeSymbols: unsupported config {0}", config); } if (generator != null) { IEnumerable <SymbolStoreKey> keys = generator.GetKeys(KeyTypeFlags.SymbolKey | KeyTypeFlags.DacDbiKeys); foreach (SymbolStoreKey key in keys) { string moduleFileName = Path.GetFileName(key.FullPathName); Trace.TraceInformation("{0} {1}", key.FullPathName, key.Index); string downloadFilePath = _symbolService.DownloadFile(key); if (downloadFilePath != null) { Trace.TraceInformation("{0}: {1}", moduleFileName, downloadFilePath); callback(parameter, moduleFileName, downloadFilePath); } } } } catch (Exception ex) when (ex is DiagnosticsException || ex is BadInputFormatException || ex is InvalidVirtualAddressException || ex is ArgumentOutOfRangeException || ex is IndexOutOfRangeException || ex is TaskCanceledException) { Trace.TraceError("{0} address {1:X16}: {2}", moduleFilePath, address, ex.Message); } } }
/// <summary> /// Updates the fields in the optional header of the PE file. /// </summary> /// <param name="peFile">The (incomplete) PE file to update.</param> /// <param name="image">The image that the PE file was based on.</param> /// <param name="context">The object containing the intermediate values used during the PE file construction.</param> protected virtual void ComputeOptionalHeaderFields(PEFile peFile, IPEImage image, TContext context) { var header = peFile.OptionalHeader; header.ImageBase = GetImageBase(peFile, image, context); header.SectionAlignment = GetSectionAlignment(peFile, image, context); header.FileAlignment = GetFileAlignment(peFile, image, context); if (header.SectionAlignment < header.FileAlignment) { throw new ArgumentException("File alignment cannot be larger than the section alignment."); } peFile.UpdateHeaders(); header.Magic = image.PEKind; header.MajorLinkerVersion = 0x30; header.MinorLinkerVersion = 0; header.SizeOfCode = 0; header.SizeOfInitializedData = 0; header.SizeOfUninitializedData = 0; header.SizeOfImage = 0; foreach (var section in peFile.Sections) { uint physicalSize = section.GetPhysicalSize(); if (section.IsContentCode) { header.SizeOfCode += physicalSize; } if (section.IsContentInitializedData) { header.SizeOfInitializedData += physicalSize; } if (section.IsContentUninitializedData) { header.SizeOfUninitializedData += physicalSize; } header.SizeOfImage += section.GetVirtualSize(); } header.AddressOfEntrypoint = GetEntrypointAddress(peFile, image, context); header.BaseOfCode = peFile.Sections.FirstOrDefault(s => s.IsContentCode)?.Rva ?? 0; header.BaseOfData = peFile.Sections.FirstOrDefault(s => s.IsContentInitializedData)?.Rva ?? 0; header.MajorOperatingSystemVersion = 4; header.MinorOperatingSystemVersion = 0; header.MajorImageVersion = 0; header.MinorImageVersion = 0; header.MajorSubsystemVersion = 4; header.MinorSubsystemVersion = 0; header.Win32VersionValue = 0; header.SizeOfImage = header.SizeOfImage.Align(header.SectionAlignment); header.SizeOfHeaders = (peFile.DosHeader.GetPhysicalSize() + peFile.FileHeader.GetPhysicalSize() + peFile.OptionalHeader.GetPhysicalSize() + (uint)peFile.Sections.Count * SectionHeader.SectionHeaderSize) .Align(header.FileAlignment); header.CheckSum = 0; // TODO: actually calculate a checksum. header.SubSystem = image.SubSystem; header.DllCharacteristics = image.DllCharacteristics; // TODO: make more configurable. header.SizeOfStackReserve = 0x00100000; header.SizeOfStackCommit = 0x00001000; header.SizeOfHeapReserve = 0x00100000; header.SizeOfHeapCommit = 0x00001000; header.LoaderFlags = 0; var dataDirectories = CreateDataDirectories(peFile, image, context).ToList(); for (int i = 0; i < OptionalHeader.DefaultNumberOfRvasAndSizes; i++) { header.DataDirectories.Add(i < dataDirectories.Count ? dataDirectories[i] : new DataDirectory(0, 0)); } header.NumberOfRvaAndSizes = OptionalHeader.DefaultNumberOfRvasAndSizes; }
void OnFoundResult(PEFile module) { OnFoundResult(searchRequest.SearchResultFactory.Create(module)); }
public EntityReference(PEFile module, Handle handle) { this.Module = module ?? throw new ArgumentNullException(nameof(module)); this.Handle = handle; }
public OptionalHeaderTreeNode(PEFile module) { this.module = module; }
public static string GetRuntimeDisplayName(PEFile module) { return(module.Metadata.MetadataVersion); }
public override void Search(PEFile module, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (searchTermToken.IsNil) { return; } var typeSystem = module.GetTypeSystemWithDecompilerSettingsOrNull(searchRequest.DecompilerSettings); if (typeSystem == null) { return; } var metadataModule = (MetadataModule)typeSystem.MainModule; int row = module.Metadata.GetRowNumber(searchTermToken); switch (searchTermToken.Kind) { case HandleKind.TypeDefinition: if (row < 1 || row > module.Metadata.TypeDefinitions.Count) { break; } var type = metadataModule.GetDefinition((TypeDefinitionHandle)searchTermToken); if (!CheckVisibility(type) || !IsInNamespaceOrAssembly(type)) { break; } OnFoundResult(type); break; case HandleKind.MethodDefinition: if (row < 1 || row > module.Metadata.MethodDefinitions.Count) { break; } var method = metadataModule.GetDefinition((MethodDefinitionHandle)searchTermToken); if (!CheckVisibility(method) || !IsInNamespaceOrAssembly(method)) { break; } OnFoundResult(method); break; case HandleKind.FieldDefinition: if (row < 1 || row > module.Metadata.FieldDefinitions.Count) { break; } var field = metadataModule.GetDefinition((FieldDefinitionHandle)searchTermToken); if (!CheckVisibility(field) || !IsInNamespaceOrAssembly(field)) { break; } OnFoundResult(field); break; case HandleKind.PropertyDefinition: if (row < 1 || row > module.Metadata.PropertyDefinitions.Count) { break; } var property = metadataModule.GetDefinition((PropertyDefinitionHandle)searchTermToken); if (!CheckVisibility(property) || !IsInNamespaceOrAssembly(property)) { break; } OnFoundResult(property); break; case HandleKind.EventDefinition: if (row < 1 || row > module.Metadata.EventDefinitions.Count) { break; } var @event = metadataModule.GetDefinition((EventDefinitionHandle)searchTermToken); if (!CheckVisibility(@event) || !IsInNamespaceOrAssembly(@event)) { break; } OnFoundResult(@event); break; } }
bool MethodIsLiteralMatch(PEFile module, MethodDefinition methodDefinition) { var blob = module.Reader.GetMethodBody(methodDefinition.RelativeVirtualAddress).GetILReader(); if (searchTermLiteralType == TypeCode.Int64) { long val = (long)searchTermLiteralValue; while (blob.RemainingBytes > 0) { ILOpCode code; switch (code = ILParser.DecodeOpCode(ref blob)) { case ILOpCode.Ldc_i8: if (val == blob.ReadInt64()) { return(true); } break; case ILOpCode.Ldc_i4: if (val == blob.ReadInt32()) { return(true); } break; case ILOpCode.Ldc_i4_s: if (val == blob.ReadSByte()) { return(true); } break; case ILOpCode.Ldc_i4_m1: if (val == -1) { return(true); } break; case ILOpCode.Ldc_i4_0: if (val == 0) { return(true); } break; case ILOpCode.Ldc_i4_1: if (val == 1) { return(true); } break; case ILOpCode.Ldc_i4_2: if (val == 2) { return(true); } break; case ILOpCode.Ldc_i4_3: if (val == 3) { return(true); } break; case ILOpCode.Ldc_i4_4: if (val == 4) { return(true); } break; case ILOpCode.Ldc_i4_5: if (val == 5) { return(true); } break; case ILOpCode.Ldc_i4_6: if (val == 6) { return(true); } break; case ILOpCode.Ldc_i4_7: if (val == 7) { return(true); } break; case ILOpCode.Ldc_i4_8: if (val == 8) { return(true); } break; default: ILParser.SkipOperand(ref blob, code); break; } } } else if (searchTermLiteralType != TypeCode.Empty) { ILOpCode expectedCode; switch (searchTermLiteralType) { case TypeCode.Single: expectedCode = ILOpCode.Ldc_r4; break; case TypeCode.Double: expectedCode = ILOpCode.Ldc_r8; break; case TypeCode.String: expectedCode = ILOpCode.Ldstr; break; default: throw new InvalidOperationException(); } while (blob.RemainingBytes > 0) { var code = ILParser.DecodeOpCode(ref blob); if (code != expectedCode) { ILParser.SkipOperand(ref blob, code); continue; } switch (code) { case ILOpCode.Ldc_r4: if ((float)searchTermLiteralValue == blob.ReadSingle()) { return(true); } break; case ILOpCode.Ldc_r8: if ((double)searchTermLiteralValue == blob.ReadDouble()) { return(true); } break; case ILOpCode.Ldstr: if ((string)searchTermLiteralValue == ILParser.DecodeUserString(ref blob, module.Metadata)) { return(true); } break; } } } else { while (blob.RemainingBytes > 0) { var code = ILParser.DecodeOpCode(ref blob); if (code != ILOpCode.Ldstr) { ILParser.SkipOperand(ref blob, code); continue; } if (IsMatch(ILParser.DecodeUserString(ref blob, module.Metadata))) { return(true); } } } return(false); }
/// <summary> /// Updates the fields in the file header and optional header of the PE file. /// </summary> /// <param name="peFile">The (incomplete) PE file to update.</param> /// <param name="image">The image that the PE file was based on.</param> /// <param name="context">The object containing the intermediate values used during the PE file construction.</param> protected virtual void ComputeHeaderFields(PEFile peFile, IPEImage image, TContext context) { ComputeOptionalHeaderFields(peFile, image, context); ComputeFileHeaderFields(peFile, image, context); peFile.DosHeader.NextHeaderOffset = peFile.DosHeader.GetPhysicalSize(); }