public PeCoffFile Load() { PeCoffFile file = new PeCoffFile(TestFile, new TheBoxSoftware.FileSystem()); file.Initialise(); return(file); }
/// <summary> /// Initialises the PEFile. /// </summary> private void Initialise(PeCoffFile peCoffFile) { Entries.Add(new Entry("File Header")); // Initialise the display of the PE Header entries Entry peHeader = new Entry("PE Header"); Entries.Add(peHeader); string[] names = Enum.GetNames(typeof(TheBoxSoftware.Reflection.Core.PE.DataDirectories)); foreach (string name in names) { peHeader.Children.Add(Entry.Create(name)); } // Initialise the section entries Entry sections = new Entry("Sections"); Entries.Add(sections); foreach (TheBoxSoftware.Reflection.Core.PE.SectionHeader header in peCoffFile.SectionHeaders) { sections.Children.Add(Entry.Create(header.Name)); } // Initialise the view of the different directories Entry directories = new Entry("Directories"); Entries.Add(directories); foreach (KeyValuePair <DataDirectories, Directory> directory in peCoffFile.Directories) { directories.Children.Add(Entry.Create(directory.Value)); } }
public override void ReadDirectories(PeCoffFile containingFile) { _metadata = new MetadataDirectory( containingFile, containingFile.GetAddressFromRVA(this.Header.MetaData.VirtualAddress) ); }
public void WhenFileIsValid_Initialise_LoadsMetadata() { PeCoffFile coffFile = new PeCoffFile(TestLibrary, new FileSystem()); coffFile.Initialise(); Assert.AreEqual(TestLibrary, coffFile.FileName); Assert.IsTrue(coffFile.IsMetadataLoaded); }
/// <summary> /// Initialises a new instance of the GuidStream class. /// </summary> /// <param name="file">The file which owns the stream.</param> /// <param name="address">The start address of the stream.</param> /// <param name="size">The size of the stream.</param> internal GuidStream(PeCoffFile file, uint address, int size) { // Read and store the underlying data for this stream _streamContents = new byte[size]; for (uint i = address; i < (address + size); i++) { _streamContents[i - address] = file.FileContents[i]; } }
private void LoadAndInitialiseAssembly(string filename) { PeCoffFile coffFile = new PeCoffFile(filename, new FileSystem()); coffFile.Initialise(); _peFile = new Model.PEFile(coffFile); InitialiseForNewPEFile(); }
public StringStreamBenchmark() { PeCoffFile file = new PeCoffFile(TestFile, new TheBoxSoftware.FileSystem()); file.Initialise(); MetadataDirectory directory = file.GetMetadataDirectory(); _stream = directory.Streams[Streams.StringStream] as StringStream; }
public void WhenFilenameIsEmptyString_Initialise_ThrowsArgumentException() { Mock <IFileSystem> fileSystem = new Mock <IFileSystem>(); Assert.Throws <ArgumentException>(delegate() { PeCoffFile coffFile = new PeCoffFile(string.Empty, fileSystem.Object); coffFile.Initialise(); }); }
public void WhenLoaded_GetMetadataDirectory_ReturnsMetadata() { PeCoffFile coffFile = new PeCoffFile(TestLibrary, new FileSystem()); coffFile.Initialise(); MetadataDirectory directory = coffFile.GetMetadataDirectory(); Assert.IsNotNull(directory); }
public SignatureBenchmark() { _file = new PeCoffFile(TestFile, new FileSystem()); _file.Initialise(); _metadata = _file.GetMetadataDirectory(); BlobStream blob = (BlobStream)_metadata.Streams[Streams.BlobStream]; _source = blob.GetRange(0, (uint)blob.GetLength()); // copy full length of stream }
[TestCase(0x0000d000, 0x00001200)] // top of range public void WhenHeaderIsInRange_GetRva_AddressIsCalculated(int rva, int expected) { Mock <IFileSystem> fileSystem = new Mock <IFileSystem>(); PeCoffFile coffFile = new PeCoffFile("doesnt-matter.dll", fileSystem.Object); // section headers need to be set up to be able work out the rva coffFile.SectionHeaders = new List <SectionHeader>(); coffFile.SectionHeaders.Add(CreateSectionHeader(0x0000c000, 0x0000d000, 0x00000200)); uint result = coffFile.GetAddressFromRVA((uint)rva); Assert.AreEqual(expected, result); }
public void WhenHeaderOutOfRange_CanGetRva_IsFalse() { Mock <IFileSystem> fileSystem = new Mock <IFileSystem>(); PeCoffFile coffFile = new PeCoffFile("doesnt-matter.dll", fileSystem.Object); // section headers need to be set up to be able work out the rva coffFile.SectionHeaders = new List <SectionHeader>(); coffFile.SectionHeaders.Add(CreateSectionHeader(0x0000c000, 0x0000d000, 0x00000200)); bool result = coffFile.CanGetAddressFromRva(0x00000001); Assert.AreEqual(false, result); }
/// <include file='code-documentation\reflection.xml' path='docs/assemblydef/member[@name="create2"]/*'/> public static AssemblyDef Create(PeCoffFile peCoffFile) { AssemblyDef created = new AssemblyDefBuilder(peCoffFile).Build(); created._fileName = peCoffFile.FileName; created._metadataDirectory = peCoffFile.GetMetadataDirectory(); created._metadataStream = created._metadataDirectory.GetMetadataStream(); created._blobStream = created._metadataDirectory.Streams[Streams.BlobStream] as BlobStream; created._metadataMap = peCoffFile.Map; created._fileContents = peCoffFile.FileContents; return(created); }
public void WhenNoSectionsRvaCantBeComputed_GetRva_ThrowsException() { Mock <IFileSystem> fileSystem = new Mock <IFileSystem>(); PeCoffFile coffFile = new PeCoffFile("doesnt-matter.dll", fileSystem.Object); // section headers need to be set up to be able work out the rva coffFile.SectionHeaders = new List <SectionHeader>(); Assert.Throws <InvalidOperationException>(delegate() { coffFile.GetAddressFromRVA(0x00000000); }); }
public void WhenHeaderStartIsInRangeButRvaIsOutside_GetRva_ThrowsException() { Mock <IFileSystem> fileSystem = new Mock <IFileSystem>(); PeCoffFile coffFile = new PeCoffFile("doesnt-matter.dll", fileSystem.Object); // section headers need to be set up to be able work out the rva coffFile.SectionHeaders = new List <SectionHeader>(); coffFile.SectionHeaders.Add(CreateSectionHeader(0x0000c000, 0x00000001, 0x0)); Assert.Throws <InvalidOperationException>(delegate() { coffFile.GetAddressFromRVA(0x00000c02); }); }
/// <include file='code-documentation\reflection.xml' path='docs/assemblydef/member[@name="create"]/*'/> public static AssemblyDef Create(string fileName) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullException(fileName); } PeCoffFile peFile = new PeCoffFile(fileName, new FileSystem()); peFile.Initialise(); if (!peFile.Directories.ContainsKey(DataDirectories.CommonLanguageRuntimeHeader)) { throw new NotAManagedLibraryException($"The file '{fileName}' is not a managed library."); } return(Create(peFile)); }
public AssemblyDefBuilder(PeCoffFile peCoffFile) { if (peCoffFile == null) { throw new ArgumentNullException(nameof(peCoffFile)); } if (!peCoffFile.Directories.ContainsKey(DataDirectories.CommonLanguageRuntimeHeader)) { throw new NotAManagedLibraryException($"The file '{peCoffFile.FileName}' is not a managed library."); } _peCoffFile = peCoffFile; _map = _peCoffFile.Map; _references = new BuildReferences(); _references.Map = _map; _references.PeCoffFile = _peCoffFile; _references.Metadata = _peCoffFile.GetMetadataDirectory(); }
/// <summary> /// Initialises a new instance of the MetadataDirectory /// </summary> /// <param name="file">The contents of the file</param> /// <param name="address">The base address of the directory</param> public MetadataDirectory(PeCoffFile file, uint address) { _header = new MetadataHeader(file.FileContents, address); _streams = new Dictionary <Streams, Stream>(); for (int i = 0; i < _header.NumberOfMetaDataStreams; i++) { var streamHeader = _header.Headers[i]; Stream current = Stream.Create( file, streamHeader.Offset + address, (int)streamHeader.Size, streamHeader.Name ); _streams.Add(current.StreamType, current); } }
public static Stream Create(PeCoffFile file, uint address, int size, string name) { Stream created = null; switch (name) { case "#~": created = new MetadataStream(file, address); created.StreamType = Streams.MetadataStream; break; case "#Strings": created = new StringStream(file.FileContents, address, size); created.StreamType = Streams.StringStream; break; case "#GUID": created = new GuidStream(file, address, size); created.StreamType = Streams.GuidStream; break; case "#Blob": created = new BlobStream(file.FileContents, address, size); created.StreamType = Streams.BlobStream; break; case "#US": created = new Stream(); created.StreamType = Streams.USStream; break; } created.Name = name; return(created); }
public AssemblyDef Build() { if (_assembly != null) { return(_assembly); // we have already built it return previous } _assembly = new AssemblyDef(_peCoffFile); _references.Assembly = _assembly; _map.Assembly = _assembly; // Read the metadata from the file and populate the entries _metadata = _peCoffFile.GetMetadataDirectory(); _stream = _metadata.Streams[Streams.MetadataStream] as MetadataStream; _assembly.StringStream = _metadata.Streams[Streams.StringStream] as IStringStream; // needs to be populated first LoadAssemblyMetadata(); LoadAssemblyRefMetadata(); LoadModuleMetadata(); LoadTypeRefMetadata(); LoadTypeDefMetadata(); LoadMemberRefMetadata(); LoadTypeSpecMetadata(); LoadNestedClassMetadata(); LoadInterfaceImplMetadata(); LoadConstantMetadata(); LoadCustomAttributeMetadata(); // assign the built assembly locally and clear up the unused references _peCoffFile = null; _map = null; _metadata = null; _stream = null; return(_assembly); }
internal MetadataStream(PeCoffFile file, uint address) { _owningFile = file; byte[] contents = file.FileContents; Offset offset = (int)address; offset.Shift(4); // reserved1 = BitConverter.ToUInt32(contents, offset.Shift(4)); offset.Shift(1); // majorVersion = contents[offset.Shift(1)]; offset.Shift(1); // minorVersion = contents[offset.Shift(1)]; _heapOffsetSizes = (HeapOffsetSizes)contents.GetValue(offset.Shift(1)); offset.Shift(1); // reserved2 = contents[offset.Shift(1)]; ulong valid = BitConverter.ToUInt64(contents, offset.Shift(8)); offset.Shift(8); // sorted = BitConverter.ToUInt64(contents, offset.Shift(8)); // Now we need to read the number of rows present in the available tables, we have // had to add the unused tables to the MEtadatTables as mscorlib seems to use one. Not // sure which though. Dictionary <MetadataTables, int> rowsInPresentTables = new Dictionary <MetadataTables, int>(); Array values = Enum.GetValues(typeof(MetadataTables)); for (int i = 0; i < values.Length - 1; i++) { MetadataTables current = (MetadataTables)values.GetValue(i); ulong mask = (ulong)1 << (int)current; if ((mask & valid) == mask) { rowsInPresentTables.Add(current, BitConverter.ToInt32(contents, offset.Shift(4))); } } // build index helper classes for metadata row creation ICodedIndexResolver resolver = new CodedIndexResolver(rowsInPresentTables); IIndexDetails indexDetails = new IndexDetails(rowsInPresentTables, SizeOfStringIndexes, SizeOfBlobIndexes, SizeOfGuidIndexes ); // Following the array of row size we get the actual metadata tables _tables = new MetadataTablesDictionary(rowsInPresentTables.Count); for (int i = 0; i < values.Length; i++) { MetadataTables current = (MetadataTables)values.GetValue(i); if (!rowsInPresentTables.ContainsKey(current)) { continue; } int numRows = rowsInPresentTables[current]; MetadataRow[] rows = new MetadataRow[numRows]; switch (current) { case MetadataTables.Module: for (int j = 0; j < numRows; j++) { rows[j] = new ModuleMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.TypeRef: for (int j = 0; j < numRows; j++) { rows[j] = new TypeRefMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.TypeDef: for (int j = 0; j < numRows; j++) { rows[j] = new TypeDefMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.Field: for (int j = 0; j < numRows; j++) { rows[j] = new FieldMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.MethodDef: for (int j = 0; j < numRows; j++) { rows[j] = new MethodMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.Param: for (int j = 0; j < numRows; j++) { rows[j] = new ParamMetadataTableRow(contents, offset, SizeOfStringIndexes); } break; case MetadataTables.InterfaceImpl: for (int j = 0; j < numRows; j++) { rows[j] = new InterfaceImplMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.MemberRef: for (int j = 0; j < numRows; j++) { rows[j] = new MemberRefMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.Constant: for (int j = 0; j < numRows; j++) { rows[j] = new ConstantMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.CustomAttribute: for (int j = 0; j < numRows; j++) { rows[j] = new CustomAttributeMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.FieldMarshal: for (int j = 0; j < numRows; j++) { rows[j] = new FieldMarshalMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.DeclSecurity: for (int j = 0; j < numRows; j++) { rows[j] = new DeclSecurityMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.ClassLayout: for (int j = 0; j < numRows; j++) { rows[j] = new ClassLayoutMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.FieldLayout: for (int j = 0; j < numRows; j++) { rows[j] = new FieldLayoutMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.StandAloneSig: for (int j = 0; j < numRows; j++) { rows[j] = new StandAloneSigMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.EventMap: for (int j = 0; j < numRows; j++) { rows[j] = new EventMapMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.Event: for (int j = 0; j < numRows; j++) { rows[j] = new EventMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.PropertyMap: for (int j = 0; j < numRows; j++) { rows[j] = new PropertyMapMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.Property: for (int j = 0; j < numRows; j++) { rows[j] = new PropertyMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.MethodSemantics: for (int j = 0; j < numRows; j++) { rows[j] = new MethodSemanticsMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.MethodImpl: for (int j = 0; j < numRows; j++) { rows[j] = new MethodImplMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.ModuleRef: for (int j = 0; j < numRows; j++) { rows[j] = new ModuleRefMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.TypeSpec: for (int j = 0; j < numRows; j++) { rows[j] = new TypeSpecMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.ImplMap: for (int j = 0; j < numRows; j++) { rows[j] = new ImplMapMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.FieldRVA: for (int j = 0; j < numRows; j++) { rows[j] = new FieldRVAMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.Assembly: for (int j = 0; j < numRows; j++) { rows[j] = new AssemblyMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.AssemblyProcessor: for (int j = 0; j < numRows; j++) { rows[j] = new AssemblyProcessorMetadataTableRow(contents, offset); } break; case MetadataTables.AssemblyOS: for (int j = 0; j < numRows; j++) { rows[j] = new AssemblyOSMetadataTableRow(contents, offset); } break; case MetadataTables.AssemblyRef: for (int j = 0; j < numRows; j++) { rows[j] = new AssemblyRefMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.AssemblyRefProcessor: for (int j = 0; j < numRows; j++) { rows[j] = new AssemblyRefProcessorMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.AssemblyRefOS: for (int j = 0; j < numRows; j++) { rows[j] = new AssemblyRefOSMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.File: for (int j = 0; j < numRows; j++) { rows[j] = new FileMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.ExportedType: for (int j = 0; j < numRows; j++) { rows[j] = new ExportedTypeMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.ManifestResource: for (int j = 0; j < numRows; j++) { rows[j] = new ManifestResourceMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.NestedClass: for (int j = 0; j < numRows; j++) { rows[j] = new NestedClassMetadataTableRow(contents, offset, indexDetails); } break; case MetadataTables.GenericParam: for (int j = 0; j < numRows; j++) { rows[j] = new GenericParamMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.MethodSpec: for (int j = 0; j < numRows; j++) { rows[j] = new MethodSpecMetadataTableRow(contents, offset, resolver, indexDetails); } break; case MetadataTables.GenericParamConstraint: for (int j = 0; j < numRows; j++) { rows[j] = new GenericParamConstraintMetadataTableRow(contents, offset, resolver, indexDetails); } break; } _tables.SetMetadataTable(current, rows); } }
/// <summary> /// Initialises a new instance of the PEFile wrapper class. /// </summary> /// <param name="peCoffFile">The file instance to parse and wrap.</param> public PEFile(PeCoffFile peCoffFile) { Entries = new List <Entry>(); Initialise(peCoffFile); }
static void Main(string[] args) { // the argument is going to be a library to load PeCoffFile peCoffFile = new PeCoffFile(args[0], new FileSystem()); peCoffFile.Initialise(); BlobStream blobStream = peCoffFile.GetMetadataDirectory().Streams[Streams.BlobStream] as BlobStream; Console.WriteLine("Library Loaded"); string input = Console.ReadLine(); while (input != "q") { int offset = 0; string[] command = input.Split(' '); byte[] contents; switch (command[0]) { case "bytes": // print the bytes for the signiture at offset offset = int.Parse(command[1]); byte[] signiture = blobStream.GetSignitureContents(offset); Console.WriteLine(FieldReader.ToHexString(signiture, 0, signiture.Length)); break; case "tokens": offset = int.Parse(command[1]); try { /* * Signatures type = (Signatures)Enum.Parse(typeof(Signatures), command[2]); * Signiture sig = blobStream.GetSigniture(1, type); * Console.WriteLine(sig.ToString()); */ SignatureBuilder builder1 = new SignatureBuilder(blobStream); Signature sig1 = builder1.Read(offset); Console.WriteLine(sig1.ToString()); } catch (Exception) { Console.WriteLine($"Could not read signiture as a {command[2]}"); } finally { } break; case "length": Console.WriteLine(blobStream.GetLength(int.Parse(command[1]))); break; case "first": offset = int.Parse(command[1]); byte[] a = blobStream.GetSignitureContents(offset); CallingConventions conventions = (CallingConventions)(a[0] & 0x0F); Console.WriteLine(conventions); break; case "all": StringBuilder output = new StringBuilder(); blobStream.GetRange(0, (uint)blobStream.GetLength()); for (int i = 0; i < blobStream.GetLength(); i++) { if (i == 0) { output.Append($"{i.ToString()}: "); } if (i != 0 && i % 16 == 0) { Console.WriteLine(output.ToString()); output.Clear(); output.Append($"{i.ToString()}: "); } output.Append($"{blobStream.GetByte(i).ToString("X2")} "); } break; case "report": offset = int.Parse(command[1]); Console.WriteLine("Original code signiture retrieval: "); contents = blobStream.GetSignitureContents(offset); Console.WriteLine(FieldReader.ToHexString(contents, 0, contents.Length)); Console.WriteLine($" byte at {offset}: 0x{blobStream.GetByte(offset).ToString("X2")}"); SignatureBuilder builder = new SignatureBuilder(blobStream); Console.WriteLine($" length: {builder.GetLength(offset)}"); contents = builder.GetSignitureBytes(offset); Console.WriteLine(" contents:"); Console.WriteLine(FieldReader.ToHexString(contents, 0, contents.Length)); break; } Console.WriteLine(); input = Console.ReadLine(); } }
private void LoadPeCoffFileOnly() { PeCoffFile file = new PeCoffFile(TestFile, new TheBoxSoftware.FileSystem()); file.Initialise(); }
internal AssemblyDef(PeCoffFile peCoffFile) : this() { _peCoffFile = peCoffFile; }