Merge pull request #178 from mnadareski/new-exe-framework

Use new executable framework for protection checks
This commit is contained in:
Matt Nadareski
2022-12-05 11:30:54 -08:00
committed by GitHub
145 changed files with 2054 additions and 8403 deletions

2
.vscode/launch.json vendored
View File

@@ -10,7 +10,7 @@
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Test/bin/Debug/netcoreapp3.1/Test.dll",
"program": "${workspaceFolder}/Test/bin/Debug/net6.0/Test.dll",
"args": [],
"cwd": "${workspaceFolder}/Test",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console

View File

@@ -25,7 +25,7 @@ namespace BurnOutSharp.Builder
public static byte[] ReadBytes(this byte[] content, ref int offset, int count)
{
// If there's an invalid byte count, don't do anything
if (count == 0)
if (count <= 0)
return null;
byte[] buffer = new byte[count];
@@ -163,7 +163,7 @@ namespace BurnOutSharp.Builder
public static byte[] ReadBytes(this Stream stream, int count)
{
// If there's an invalid byte count, don't do anything
if (count == 0)
if (count <= 0)
return null;
byte[] buffer = new byte[count];
@@ -1220,9 +1220,6 @@ namespace BurnOutSharp.Builder
// Create the output table
var stringTable = new Dictionary<int, string>();
// Create the string encoding
Encoding stringEncoding = (entry.Codepage != 0 ? Encoding.GetEncoding((int)entry.Codepage) : Encoding.Unicode);
// Loop through and add
while (offset < entry.Data.Length)
{
@@ -1233,17 +1230,9 @@ namespace BurnOutSharp.Builder
}
else
{
string fullEncodedString = stringEncoding.GetString(entry.Data, offset, entry.Data.Length - offset);
if (stringLength > fullEncodedString.Length)
{
// TODO: Do something better than print to console
Console.WriteLine($"Requested {stringLength} but only have {fullEncodedString.Length} remaining, truncating...");
stringLength = (ushort)fullEncodedString.Length;
}
string stringValue = fullEncodedString.Substring(0, stringLength);
offset += stringEncoding.GetByteCount(stringValue);
stringValue = stringValue.Replace("\n", "\\n").Replace("\r", "\\r");
string stringValue = Encoding.Unicode.GetString(entry.Data, offset, stringLength * 2);
offset += stringLength * 2;
stringValue = stringValue.Replace("\n", "\\n").Replace("\r", newValue: "\\r");
stringTable[stringIndex++] = stringValue;
}
}

View File

@@ -175,6 +175,29 @@ namespace BurnOutSharp.Builder
#endregion
#region Base Relocation Table
// Should also be in a '.reloc' section
if (optionalHeader.BaseRelocationTable != null && optionalHeader.BaseRelocationTable.VirtualAddress.ConvertVirtualAddress(executable.SectionTable) != 0)
{
// If the offset for the base relocation table doesn't exist
int baseRelocationTableAddress = initialOffset
+ (int)optionalHeader.BaseRelocationTable.VirtualAddress.ConvertVirtualAddress(executable.SectionTable);
if (baseRelocationTableAddress >= data.Length)
return executable;
// Try to parse the base relocation table
int endOffset = (int)(baseRelocationTableAddress + optionalHeader.BaseRelocationTable.Size);
var baseRelocationTable = ParseBaseRelocationTable(data, baseRelocationTableAddress, endOffset, executable.SectionTable);
if (baseRelocationTable == null)
return null;
// Set the base relocation table
executable.BaseRelocationTable = baseRelocationTable;
}
#endregion
#region Debug Table
// Should also be in a '.debug' section
@@ -700,20 +723,22 @@ namespace BurnOutSharp.Builder
{
var attributeCertificateTable = new List<AttributeCertificateTableEntry>();
while (offset < endOffset)
while (offset < endOffset && offset != data.Length)
{
var entry = new AttributeCertificateTableEntry();
entry.Length = data.ReadUInt32(ref offset);
entry.Revision = (WindowsCertificateRevision)data.ReadUInt16(ref offset);
entry.CertificateType = (WindowsCertificateType)data.ReadUInt16(ref offset);
if (entry.Length > 0)
entry.Certificate = data.ReadBytes(ref offset, (int)entry.Length - 8);
int certificateDataLength = (int)(entry.Length - 8);
if (certificateDataLength > 0)
entry.Certificate = data.ReadBytes(ref offset, certificateDataLength);
attributeCertificateTable.Add(entry);
// Align to the 8-byte boundary
while ((offset % 8) != 0)
while ((offset % 8) != 0 && offset < endOffset - 1 && offset != data.Length)
_ = data.ReadByte(ref offset);
}
@@ -744,7 +769,49 @@ namespace BurnOutSharp.Builder
}
/// <summary>
/// Parse a Stream into a debug table
/// Parse a byte array into a base relocation table
/// </summary>
/// <param name="data">Byte array to parse</param>
/// <param name="offset">Offset into the byte array</param>
/// <param name="endOffset">First address not part of the base relocation table</param>
/// <param name="sections">Section table to use for virtual address translation</param>
/// <returns>Filled base relocation table on success, null on error</returns>
private static BaseRelocationBlock[] ParseBaseRelocationTable(byte[] data, int offset, int endOffset, SectionHeader[] sections)
{
// TODO: Use marshalling here instead of building
var baseRelocationTable = new List<BaseRelocationBlock>();
while (offset < endOffset)
{
var baseRelocationBlock = new BaseRelocationBlock();
baseRelocationBlock.PageRVA = data.ReadUInt32(ref offset);
baseRelocationBlock.BlockSize = data.ReadUInt32(ref offset);
var typeOffsetFieldEntries = new List<BaseRelocationTypeOffsetFieldEntry>();
int totalSize = 8;
while (totalSize < baseRelocationBlock.BlockSize)
{
var baseRelocationTypeOffsetFieldEntry = new BaseRelocationTypeOffsetFieldEntry();
ushort typeAndOffsetField = data.ReadUInt16(ref offset);
baseRelocationTypeOffsetFieldEntry.BaseRelocationType = (BaseRelocationTypes)(typeAndOffsetField >> 12);
baseRelocationTypeOffsetFieldEntry.Offset = (ushort)(typeAndOffsetField & 0x0FFF);
typeOffsetFieldEntries.Add(baseRelocationTypeOffsetFieldEntry);
totalSize += 2;
}
baseRelocationBlock.TypeOffsetFieldEntries = typeOffsetFieldEntries.ToArray();
baseRelocationTable.Add(baseRelocationBlock);
}
return baseRelocationTable.ToArray();
}
/// <summary>
/// Parse a byte array into a debug table
/// </summary>
/// <param name="data">Byte array to parse</param>
/// <param name="offset">Offset into the byte array</param>
@@ -1327,6 +1394,30 @@ namespace BurnOutSharp.Builder
#endregion
#region Base Relocation Table
// Should also be in a '.reloc' section
if (optionalHeader.BaseRelocationTable != null && optionalHeader.BaseRelocationTable.VirtualAddress.ConvertVirtualAddress(executable.SectionTable) != 0)
{
// If the offset for the base relocation table doesn't exist
int baseRelocationTableAddress = initialOffset
+ (int)optionalHeader.BaseRelocationTable.VirtualAddress.ConvertVirtualAddress(executable.SectionTable);
if (baseRelocationTableAddress >= data.Length)
return executable;
// Try to parse the base relocation table
data.Seek(baseRelocationTableAddress, SeekOrigin.Begin);
int endOffset = (int)(baseRelocationTableAddress + optionalHeader.BaseRelocationTable.Size);
var baseRelocationTable = ParseBaseRelocationTable(data, endOffset, executable.SectionTable);
if (baseRelocationTable == null)
return null;
// Set the base relocation table
executable.BaseRelocationTable = baseRelocationTable;
}
#endregion
#region Debug Table
// Should also be in a '.debug' section
@@ -1849,20 +1940,22 @@ namespace BurnOutSharp.Builder
{
var attributeCertificateTable = new List<AttributeCertificateTableEntry>();
while (data.Position < endOffset)
while (data.Position < endOffset && data.Position != data.Length)
{
var entry = new AttributeCertificateTableEntry();
entry.Length = data.ReadUInt32();
entry.Revision = (WindowsCertificateRevision)data.ReadUInt16();
entry.CertificateType = (WindowsCertificateType)data.ReadUInt16();
if (entry.Length > 0)
entry.Certificate = data.ReadBytes((int)entry.Length - 8);
int certificateDataLength = (int)(entry.Length - 8);
if (certificateDataLength > 0)
entry.Certificate = data.ReadBytes(certificateDataLength);
attributeCertificateTable.Add(entry);
// Align to the 8-byte boundary
while ((data.Position % 8) != 0)
while ((data.Position % 8) != 0 && data.Position < endOffset && data.Position != data.Length)
_ = data.ReadByteValue();
}
@@ -1891,6 +1984,47 @@ namespace BurnOutSharp.Builder
return delayLoadDirectoryTable;
}
/// <summary>
/// Parse a Stream into a base relocation table
/// </summary>
/// <param name="data">Stream to parse</param>
/// <param name="endOffset">First address not part of the base relocation table</param>
/// <param name="sections">Section table to use for virtual address translation</param>
/// <returns>Filled base relocation table on success, null on error</returns>
private static BaseRelocationBlock[] ParseBaseRelocationTable(Stream data, int endOffset, SectionHeader[] sections)
{
// TODO: Use marshalling here instead of building
var baseRelocationTable = new List<BaseRelocationBlock>();
while (data.Position < endOffset)
{
var baseRelocationBlock = new BaseRelocationBlock();
baseRelocationBlock.PageRVA = data.ReadUInt32();
baseRelocationBlock.BlockSize = data.ReadUInt32();
var typeOffsetFieldEntries = new List<BaseRelocationTypeOffsetFieldEntry>();
int totalSize = 8;
while (totalSize < baseRelocationBlock.BlockSize)
{
var baseRelocationTypeOffsetFieldEntry = new BaseRelocationTypeOffsetFieldEntry();
ushort typeAndOffsetField = data.ReadUInt16();
baseRelocationTypeOffsetFieldEntry.BaseRelocationType = (BaseRelocationTypes)(typeAndOffsetField >> 12);
baseRelocationTypeOffsetFieldEntry.Offset = (ushort)(typeAndOffsetField & 0x0FFF);
typeOffsetFieldEntries.Add(baseRelocationTypeOffsetFieldEntry);
totalSize += 2;
}
baseRelocationBlock.TypeOffsetFieldEntries = typeOffsetFieldEntries.ToArray();
baseRelocationTable.Add(baseRelocationBlock);
}
return baseRelocationTable.ToArray();
}
/// <summary>
/// Parse a Stream into a debug table
/// </summary>
@@ -2250,51 +2384,49 @@ namespace BurnOutSharp.Builder
resourceDirectoryTable.NumberOfNameEntries = data.ReadUInt16();
resourceDirectoryTable.NumberOfIDEntries = data.ReadUInt16();
// Perform top-level pass of data
// If we have no entries
int totalEntryCount = resourceDirectoryTable.NumberOfNameEntries + resourceDirectoryTable.NumberOfIDEntries;
if (totalEntryCount > 0)
if (totalEntryCount == 0)
return resourceDirectoryTable;
// Perform top-level pass of data
resourceDirectoryTable.Entries = new ResourceDirectoryEntry[totalEntryCount];
for (int i = 0; i < totalEntryCount; i++)
{
resourceDirectoryTable.Entries = new ResourceDirectoryEntry[totalEntryCount];
for (int i = 0; i < totalEntryCount; i++)
var entry = new ResourceDirectoryEntry();
uint offset = data.ReadUInt32();
if ((offset & 0x80000000) != 0)
entry.NameOffset = offset & ~0x80000000;
else
entry.IntegerID = offset;
offset = data.ReadUInt32();
if ((offset & 0x80000000) != 0)
entry.SubdirectoryOffset = offset & ~0x80000000;
else
entry.DataEntryOffset = offset;
// Read the name from the offset, if needed
if (entry.NameOffset != default)
{
var entry = new ResourceDirectoryEntry();
uint offset = data.ReadUInt32();
if ((offset & 0x80000000) != 0)
entry.NameOffset = offset & ~0x80000000;
else
entry.IntegerID = offset;
offset = data.ReadUInt32();
if ((offset & 0x80000000) != 0)
entry.SubdirectoryOffset = offset & ~0x80000000;
else
entry.DataEntryOffset = offset;
// Read the name from the offset, if needed
if (entry.NameOffset != default)
{
long currentOffset = data.Position;
offset = entry.NameOffset + (uint)initialOffset;
data.Seek(offset, SeekOrigin.Begin);
var resourceDirectoryString = new ResourceDirectoryString();
resourceDirectoryString.Length = data.ReadUInt16();
resourceDirectoryString.UnicodeString = data.ReadBytes(resourceDirectoryString.Length * 2);
entry.Name = resourceDirectoryString;
data.Seek(currentOffset, SeekOrigin.Begin);
}
resourceDirectoryTable.Entries[i] = entry;
long currentOffset = data.Position;
offset = entry.NameOffset + (uint)initialOffset;
data.Seek(offset, SeekOrigin.Begin);
var resourceDirectoryString = new ResourceDirectoryString();
resourceDirectoryString.Length = data.ReadUInt16();
resourceDirectoryString.UnicodeString = data.ReadBytes(resourceDirectoryString.Length * 2);
entry.Name = resourceDirectoryString;
data.Seek(currentOffset, SeekOrigin.Begin);
}
resourceDirectoryTable.Entries[i] = entry;
}
// Read all leaves at this level
if (totalEntryCount > 0)
// Loop through and process the entries
foreach (var entry in resourceDirectoryTable.Entries)
{
foreach (var entry in resourceDirectoryTable.Entries)
if (entry.DataEntryOffset != 0)
{
if (entry.SubdirectoryOffset != 0)
continue;
uint offset = entry.DataEntryOffset + (uint)initialOffset;
data.Seek(offset, SeekOrigin.Begin);
@@ -2314,18 +2446,11 @@ namespace BurnOutSharp.Builder
entry.DataEntry = resourceDataEntry;
}
}
// Now go one level lower
if (totalEntryCount > 0)
{
foreach (var entry in resourceDirectoryTable.Entries)
else if (entry.SubdirectoryOffset != 0)
{
if (entry.DataEntryOffset != 0)
continue;
uint offset = entry.SubdirectoryOffset + (uint)initialOffset;
data.Seek(offset, SeekOrigin.Begin);
entry.Subdirectory = ParseResourceDirectoryTable(data, initialOffset, sections);
}
}

View File

@@ -46,6 +46,6 @@
/// in the Page RVA field for the block. This offset
/// specifies where the base relocation is to be applied.
/// </summary>
public ushort[] TypeOffsetFieldEntries;
public BaseRelocationTypeOffsetFieldEntry[] TypeOffsetFieldEntries;
}
}

View File

@@ -0,0 +1,22 @@
namespace BurnOutSharp.Models.PortableExecutable
{
/// <summary>
/// Type or Offset field entry is a WORD (2 bytes).
/// </summary>
/// <see href="https://learn.microsoft.com/en-us/windows/win32/debug/pe-format"/>
public class BaseRelocationTypeOffsetFieldEntry
{
/// <summary>
/// Stored in the high 4 bits of the WORD, a value that indicates the type
/// of base relocation to be applied. For more information, see <see cref="BaseRelocationTypes"/>
/// </summary>
public BaseRelocationTypes BaseRelocationType;
/// <summary>
/// Stored in the remaining 12 bits of the WORD, an offset from the starting
/// address that was specified in the Page RVA field for the block. This
/// offset specifies where the base relocation is to be applied.
/// </summary>
public ushort Offset;
}
}

View File

@@ -68,6 +68,11 @@ namespace BurnOutSharp.Models.PortableExecutable
// the object file contains managed code. The format of the metadata is not
// documented, but can be handed to the CLR interfaces for handling metadata.
/// <summary>
/// Base relocation table (.reloc)
/// </summary>
public BaseRelocationBlock[] BaseRelocationTable { get; set; }
/// <summary>
/// Debug table (.debug*)
/// </summary>
@@ -125,7 +130,6 @@ namespace BurnOutSharp.Models.PortableExecutable
// - Delay Bound Import Address Table
// - Delay Unload Import Address Table
// - The .pdata Section [Multiple formats per entry]
// - The .reloc Section (Image Only)
// - The .tls Section
// - TLS Callback Functions
// - [The Load Configuration Structure (Image Only)]

View File

@@ -35,7 +35,7 @@ namespace BurnOutSharp.Wrappers
public ushort Stub_InitialSSValue => _executable.Stub.Header.InitialSSValue;
/// <inheritdoc cref="Models.MSDOS.ExecutableHeader.InitialSPValue"/>
public ushort Stub_Stub_InitialSPValue => _executable.Stub.Header.InitialSPValue;
public ushort Stub_InitialSPValue => _executable.Stub.Header.InitialSPValue;
/// <inheritdoc cref="Models.MSDOS.ExecutableHeader.Checksum"/>
public ushort Stub_Checksum => _executable.Stub.Header.Checksum;

View File

@@ -161,20 +161,20 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Header Information:");
Console.WriteLine(" -------------------------");
Console.WriteLine($" Magic number: {BitConverter.ToString(_executable.Header.Magic).Replace("-", string.Empty)}");
Console.WriteLine($" Last page bytes: {_executable.Header.LastPageBytes}");
Console.WriteLine($" Pages: {_executable.Header.Pages}");
Console.WriteLine($" Relocation items: {_executable.Header.RelocationItems}");
Console.WriteLine($" Header paragraph size: {_executable.Header.HeaderParagraphSize}");
Console.WriteLine($" Minimum extra paragraphs: {_executable.Header.MinimumExtraParagraphs}");
Console.WriteLine($" Maximum extra paragraphs: {_executable.Header.MaximumExtraParagraphs}");
Console.WriteLine($" Initial SS value: {_executable.Header.InitialSSValue}");
Console.WriteLine($" Initial SP value: {_executable.Header.InitialSPValue}");
Console.WriteLine($" Checksum: {_executable.Header.Checksum}");
Console.WriteLine($" Initial IP value: {_executable.Header.InitialIPValue}");
Console.WriteLine($" Initial CS value: {_executable.Header.InitialCSValue}");
Console.WriteLine($" Relocation table address: {_executable.Header.RelocationTableAddr}");
Console.WriteLine($" Overlay number: {_executable.Header.OverlayNumber}");
Console.WriteLine($" Magic number: {BitConverter.ToString(Magic).Replace("-", string.Empty)}");
Console.WriteLine($" Last page bytes: {LastPageBytes}");
Console.WriteLine($" Pages: {Pages}");
Console.WriteLine($" Relocation items: {RelocationItems}");
Console.WriteLine($" Header paragraph size: {HeaderParagraphSize}");
Console.WriteLine($" Minimum extra paragraphs: {MinimumExtraParagraphs}");
Console.WriteLine($" Maximum extra paragraphs: {MaximumExtraParagraphs}");
Console.WriteLine($" Initial SS value: {InitialSSValue}");
Console.WriteLine($" Initial SP value: {InitialSPValue}");
Console.WriteLine($" Checksum: {Checksum}");
Console.WriteLine($" Initial IP value: {InitialIPValue}");
Console.WriteLine($" Initial CS value: {InitialCSValue}");
Console.WriteLine($" Relocation table address: {RelocationTableAddr}");
Console.WriteLine($" Overlay number: {OverlayNumber}");
}
/// <summary>
@@ -184,15 +184,15 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Relocation Table Information:");
Console.WriteLine(" -------------------------");
if (_executable.Header.RelocationItems == 0 || _executable.RelocationTable.Length == 0)
if (RelocationItems == 0 || RelocationTable.Length == 0)
{
Console.WriteLine(" No relocation table items");
}
else
{
for (int i = 0; i < _executable.RelocationTable.Length; i++)
for (int i = 0; i < RelocationTable.Length; i++)
{
var entry = _executable.RelocationTable[i];
var entry = RelocationTable[i];
Console.WriteLine($" Relocation Table Entry {i}");
Console.WriteLine($" Offset = {entry.Offset}");
Console.WriteLine($" Segment = {entry.Segment}");

View File

@@ -39,7 +39,7 @@ namespace BurnOutSharp.Wrappers
public ushort Stub_InitialSSValue => _executable.Stub.Header.InitialSSValue;
/// <inheritdoc cref="Models.MSDOS.ExecutableHeader.InitialSPValue"/>
public ushort Stub_Stub_InitialSPValue => _executable.Stub.Header.InitialSPValue;
public ushort Stub_InitialSPValue => _executable.Stub.Header.InitialSPValue;
/// <inheritdoc cref="Models.MSDOS.ExecutableHeader.Checksum"/>
public ushort Stub_Checksum => _executable.Stub.Header.Checksum;
@@ -302,20 +302,20 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" MS-DOS Stub Header Information:");
Console.WriteLine(" -------------------------");
Console.WriteLine($" Magic number: {BitConverter.ToString(_executable.Stub.Header.Magic).Replace("-", string.Empty)}");
Console.WriteLine($" Last page bytes: {_executable.Stub.Header.LastPageBytes}");
Console.WriteLine($" Pages: {_executable.Stub.Header.Pages}");
Console.WriteLine($" Relocation items: {_executable.Stub.Header.RelocationItems}");
Console.WriteLine($" Header paragraph size: {_executable.Stub.Header.HeaderParagraphSize}");
Console.WriteLine($" Minimum extra paragraphs: {_executable.Stub.Header.MinimumExtraParagraphs}");
Console.WriteLine($" Maximum extra paragraphs: {_executable.Stub.Header.MaximumExtraParagraphs}");
Console.WriteLine($" Initial SS value: {_executable.Stub.Header.InitialSSValue}");
Console.WriteLine($" Initial SP value: {_executable.Stub.Header.InitialSPValue}");
Console.WriteLine($" Checksum: {_executable.Stub.Header.Checksum}");
Console.WriteLine($" Initial IP value: {_executable.Stub.Header.InitialIPValue}");
Console.WriteLine($" Initial CS value: {_executable.Stub.Header.InitialCSValue}");
Console.WriteLine($" Relocation table address: {_executable.Stub.Header.RelocationTableAddr}");
Console.WriteLine($" Overlay number: {_executable.Stub.Header.OverlayNumber}");
Console.WriteLine($" Magic number: {BitConverter.ToString(Stub_Magic).Replace("-", string.Empty)}");
Console.WriteLine($" Last page bytes: {Stub_LastPageBytes}");
Console.WriteLine($" Pages: {Stub_Pages}");
Console.WriteLine($" Relocation items: {Stub_RelocationItems}");
Console.WriteLine($" Header paragraph size: {Stub_HeaderParagraphSize}");
Console.WriteLine($" Minimum extra paragraphs: {Stub_MinimumExtraParagraphs}");
Console.WriteLine($" Maximum extra paragraphs: {Stub_MaximumExtraParagraphs}");
Console.WriteLine($" Initial SS value: {Stub_InitialSSValue}");
Console.WriteLine($" Initial SP value: {Stub_InitialSPValue}");
Console.WriteLine($" Checksum: {Stub_Checksum}");
Console.WriteLine($" Initial IP value: {Stub_InitialIPValue}");
Console.WriteLine($" Initial CS value: {Stub_InitialCSValue}");
Console.WriteLine($" Relocation table address: {Stub_RelocationTableAddr}");
Console.WriteLine($" Overlay number: {Stub_OverlayNumber}");
Console.WriteLine();
}
@@ -326,11 +326,11 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" MS-DOS Stub Extended Header Information:");
Console.WriteLine(" -------------------------");
Console.WriteLine($" Reserved words: {string.Join(", ", _executable.Stub.Header.Reserved1)}");
Console.WriteLine($" OEM identifier: {_executable.Stub.Header.OEMIdentifier}");
Console.WriteLine($" OEM information: {_executable.Stub.Header.OEMInformation}");
Console.WriteLine($" Reserved words: {string.Join(", ", _executable.Stub.Header.Reserved2)}");
Console.WriteLine($" New EXE header address: {_executable.Stub.Header.NewExeHeaderAddr}");
Console.WriteLine($" Reserved words: {string.Join(", ", Stub_Reserved1)}");
Console.WriteLine($" OEM identifier: {Stub_OEMIdentifier}");
Console.WriteLine($" OEM information: {Stub_OEMInformation}");
Console.WriteLine($" Reserved words: {string.Join(", ", Stub_Reserved2)}");
Console.WriteLine($" New EXE header address: {Stub_NewExeHeaderAddr}");
Console.WriteLine();
}
@@ -341,37 +341,37 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Header Information:");
Console.WriteLine(" -------------------------");
Console.WriteLine($" Magic number: {BitConverter.ToString(_executable.Header.Magic).Replace("-", string.Empty)}");
Console.WriteLine($" Linker version: {_executable.Header.LinkerVersion}");
Console.WriteLine($" Linker revision: {_executable.Header.LinkerRevision}");
Console.WriteLine($" Entry table offset: {_executable.Header.EntryTableOffset}");
Console.WriteLine($" Entry table size: {_executable.Header.EntryTableSize}");
Console.WriteLine($" CRC checksum: {_executable.Header.CrcChecksum}");
Console.WriteLine($" Flag word: {_executable.Header.FlagWord}");
Console.WriteLine($" Automatic data segment number: {_executable.Header.AutomaticDataSegmentNumber}");
Console.WriteLine($" Initial heap allocation: {_executable.Header.InitialHeapAlloc}");
Console.WriteLine($" Initial stack allocation: {_executable.Header.InitialStackAlloc}");
Console.WriteLine($" Initial CS:IP setting: {_executable.Header.InitialCSIPSetting}");
Console.WriteLine($" Initial SS:SP setting: {_executable.Header.InitialSSSPSetting}");
Console.WriteLine($" File segment count: {_executable.Header.FileSegmentCount}");
Console.WriteLine($" Module reference table size: {_executable.Header.ModuleReferenceTableSize}");
Console.WriteLine($" Non-resident name table size: {_executable.Header.NonResidentNameTableSize}");
Console.WriteLine($" Segment table offset: {_executable.Header.SegmentTableOffset}");
Console.WriteLine($" Resource table offset: {_executable.Header.ResourceTableOffset}");
Console.WriteLine($" Resident name table offset: {_executable.Header.ResidentNameTableOffset}");
Console.WriteLine($" Module reference table offset: {_executable.Header.ModuleReferenceTableOffset}");
Console.WriteLine($" Imported names table offset: {_executable.Header.ImportedNamesTableOffset}");
Console.WriteLine($" Non-resident name table offset: {_executable.Header.NonResidentNamesTableOffset}");
Console.WriteLine($" Moveable entries count: {_executable.Header.MovableEntriesCount}");
Console.WriteLine($" Segment alignment shift count: {_executable.Header.SegmentAlignmentShiftCount}");
Console.WriteLine($" Resource entries count: {_executable.Header.ResourceEntriesCount}");
Console.WriteLine($" Target operating system: {_executable.Header.TargetOperatingSystem}");
Console.WriteLine($" Additional flags: {_executable.Header.AdditionalFlags}");
Console.WriteLine($" Return thunk offset: {_executable.Header.ReturnThunkOffset}");
Console.WriteLine($" Segment reference thunk offset: {_executable.Header.SegmentReferenceThunkOffset}");
Console.WriteLine($" Minimum code swap area size: {_executable.Header.MinCodeSwapAreaSize}");
Console.WriteLine($" Windows SDK revision: {_executable.Header.WindowsSDKRevision}");
Console.WriteLine($" Windows SDK version: {_executable.Header.WindowsSDKVersion}");
Console.WriteLine($" Magic number: {BitConverter.ToString(Magic).Replace("-", string.Empty)}");
Console.WriteLine($" Linker version: {LinkerVersion}");
Console.WriteLine($" Linker revision: {LinkerRevision}");
Console.WriteLine($" Entry table offset: {EntryTableOffset}");
Console.WriteLine($" Entry table size: {EntryTableSize}");
Console.WriteLine($" CRC checksum: {CrcChecksum}");
Console.WriteLine($" Flag word: {FlagWord}");
Console.WriteLine($" Automatic data segment number: {AutomaticDataSegmentNumber}");
Console.WriteLine($" Initial heap allocation: {InitialHeapAlloc}");
Console.WriteLine($" Initial stack allocation: {InitialStackAlloc}");
Console.WriteLine($" Initial CS:IP setting: {InitialCSIPSetting}");
Console.WriteLine($" Initial SS:SP setting: {InitialSSSPSetting}");
Console.WriteLine($" File segment count: {FileSegmentCount}");
Console.WriteLine($" Module reference table size: {ModuleReferenceTableSize}");
Console.WriteLine($" Non-resident name table size: {NonResidentNameTableSize}");
Console.WriteLine($" Segment table offset: {SegmentTableOffset}");
Console.WriteLine($" Resource table offset: {ResourceTableOffset}");
Console.WriteLine($" Resident name table offset: {ResidentNameTableOffset}");
Console.WriteLine($" Module reference table offset: {ModuleReferenceTableOffset}");
Console.WriteLine($" Imported names table offset: {ImportedNamesTableOffset}");
Console.WriteLine($" Non-resident name table offset: {NonResidentNamesTableOffset}");
Console.WriteLine($" Moveable entries count: {MovableEntriesCount}");
Console.WriteLine($" Segment alignment shift count: {SegmentAlignmentShiftCount}");
Console.WriteLine($" Resource entries count: {ResourceEntriesCount}");
Console.WriteLine($" Target operating system: {TargetOperatingSystem}");
Console.WriteLine($" Additional flags: {AdditionalFlags}");
Console.WriteLine($" Return thunk offset: {ReturnThunkOffset}");
Console.WriteLine($" Segment reference thunk offset: {SegmentReferenceThunkOffset}");
Console.WriteLine($" Minimum code swap area size: {MinCodeSwapAreaSize}");
Console.WriteLine($" Windows SDK revision: {WindowsSDKRevision}");
Console.WriteLine($" Windows SDK version: {WindowsSDKVersion}");
Console.WriteLine();
}
@@ -382,15 +382,15 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Segment Table Information:");
Console.WriteLine(" -------------------------");
if (_executable.Header.FileSegmentCount == 0 || _executable.SegmentTable.Length == 0)
if (FileSegmentCount == 0 || SegmentTable.Length == 0)
{
Console.WriteLine(" No segment table items");
}
else
{
for (int i = 0; i < _executable.SegmentTable.Length; i++)
for (int i = 0; i < SegmentTable.Length; i++)
{
var entry = _executable.SegmentTable[i];
var entry = SegmentTable[i];
Console.WriteLine($" Segment Table Entry {i}");
Console.WriteLine($" Offset = {entry.Offset}");
Console.WriteLine($" Length = {entry.Length}");
@@ -408,17 +408,17 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Resource Table Information:");
Console.WriteLine(" -------------------------");
Console.WriteLine($" Alignment shift count: {_executable.ResourceTable.AlignmentShiftCount}");
if (_executable.Header.ResourceEntriesCount == 0 || _executable.ResourceTable.ResourceTypes.Length == 0)
Console.WriteLine($" Alignment shift count: {ResourceTable.AlignmentShiftCount}");
if (ResourceEntriesCount == 0 || ResourceTable.ResourceTypes.Length == 0)
{
Console.WriteLine(" No resource table items");
}
else
{
for (int i = 0; i < _executable.ResourceTable.ResourceTypes.Length; i++)
for (int i = 0; i < ResourceTable.ResourceTypes.Length; i++)
{
// TODO: If not integer type, print out name
var entry = _executable.ResourceTable.ResourceTypes[i];
var entry = ResourceTable.ResourceTypes[i];
Console.WriteLine($" Resource Table Entry {i}");
Console.WriteLine($" Type ID = {entry.TypeID} (Is Integer Type: {entry.IsIntegerType()})");
Console.WriteLine($" Resource count = {entry.ResourceCount}");
@@ -445,13 +445,13 @@ namespace BurnOutSharp.Wrappers
}
}
if (_executable.ResourceTable.TypeAndNameStrings.Count == 0)
if (ResourceTable.TypeAndNameStrings.Count == 0)
{
Console.WriteLine(" No resource table type/name strings");
}
else
{
foreach (var typeAndNameString in _executable.ResourceTable.TypeAndNameStrings)
foreach (var typeAndNameString in ResourceTable.TypeAndNameStrings)
{
Console.WriteLine($" Resource Type/Name Offset {typeAndNameString.Key}");
Console.WriteLine($" Length = {typeAndNameString.Value.Length}");
@@ -468,15 +468,15 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Resident-Name Table Information:");
Console.WriteLine(" -------------------------");
if (_executable.Header.ResidentNameTableOffset == 0 || _executable.ResidentNameTable.Length == 0)
if (ResidentNameTableOffset == 0 || ResidentNameTable.Length == 0)
{
Console.WriteLine(" No resident-name table items");
}
else
{
for (int i = 0; i < _executable.ResidentNameTable.Length; i++)
for (int i = 0; i < ResidentNameTable.Length; i++)
{
var entry = _executable.ResidentNameTable[i];
var entry = ResidentNameTable[i];
Console.WriteLine($" Resident-Name Table Entry {i}");
Console.WriteLine($" Length = {entry.Length}");
Console.WriteLine($" Name string = {(entry.NameString != null ? Encoding.ASCII.GetString(entry.NameString) : "[EMPTY]")}");
@@ -493,18 +493,18 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Module-Reference Table Information:");
Console.WriteLine(" -------------------------");
if (_executable.Header.ModuleReferenceTableSize == 0 || _executable.ModuleReferenceTable.Length == 0)
if (ModuleReferenceTableSize == 0 || ModuleReferenceTable.Length == 0)
{
Console.WriteLine(" No module-reference table items");
}
else
{
for (int i = 0; i < _executable.ModuleReferenceTable.Length; i++)
for (int i = 0; i < ModuleReferenceTable.Length; i++)
{
// TODO: Read the imported names table and print value here
var entry = _executable.ModuleReferenceTable[i];
var entry = ModuleReferenceTable[i];
Console.WriteLine($" Module-Reference Table Entry {i}");
Console.WriteLine($" Offset = {entry.Offset} (adjusted to be {entry.Offset + _executable.Stub.Header.NewExeHeaderAddr + _executable.Header.ImportedNamesTableOffset})");
Console.WriteLine($" Offset = {entry.Offset} (adjusted to be {entry.Offset + Stub_NewExeHeaderAddr + ImportedNamesTableOffset})");
}
}
Console.WriteLine();
@@ -517,13 +517,13 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Imported-Name Table Information:");
Console.WriteLine(" -------------------------");
if (_executable.Header.ImportedNamesTableOffset == 0 || _executable.ImportedNameTable.Count == 0)
if (ImportedNamesTableOffset == 0 || ImportedNameTable.Count == 0)
{
Console.WriteLine(" No imported-name table items");
}
else
{
foreach (var entry in _executable.ImportedNameTable)
foreach (var entry in ImportedNameTable)
{
Console.WriteLine($" Imported-Name Table at Offset {entry.Key}");
Console.WriteLine($" Length = {entry.Value.Length}");
@@ -540,15 +540,15 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Entry Table Information:");
Console.WriteLine(" -------------------------");
if (_executable.Header.EntryTableSize == 0 || _executable.EntryTable.Length == 0)
if (EntryTableSize == 0 || EntryTable.Length == 0)
{
Console.WriteLine(" No entry table items");
}
else
{
for (int i = 0; i < _executable.EntryTable.Length; i++)
for (int i = 0; i < EntryTable.Length; i++)
{
var entry = _executable.EntryTable[i];
var entry = EntryTable[i];
Console.WriteLine($" Entry Table Entry {i}");
Console.WriteLine($" Entry count = {entry.EntryCount}");
Console.WriteLine($" Segment indicator = {entry.SegmentIndicator} ({entry.GetEntryType()})");
@@ -577,15 +577,15 @@ namespace BurnOutSharp.Wrappers
{
Console.WriteLine(" Nonresident-Name Table Information:");
Console.WriteLine(" -------------------------");
if (_executable.Header.NonResidentNameTableSize == 0 || _executable.NonResidentNameTable.Length == 0)
if (NonResidentNameTableSize == 0 || NonResidentNameTable.Length == 0)
{
Console.WriteLine(" No nonresident-name table items");
}
else
{
for (int i = 0; i < _executable.NonResidentNameTable.Length; i++)
for (int i = 0; i < NonResidentNameTable.Length; i++)
{
var entry = _executable.NonResidentNameTable[i];
var entry = NonResidentNameTable[i];
Console.WriteLine($" Nonresident-Name Table Entry {i}");
Console.WriteLine($" Length = {entry.Length}");
Console.WriteLine($" Name string = {(entry.NameString != null ? Encoding.ASCII.GetString(entry.NameString) : "[EMPTY]")}");

File diff suppressed because it is too large Load Diff

View File

@@ -73,10 +73,10 @@ namespace BurnOutSharp.Wrappers
switch (_dataSource)
{
case DataSource.ByteArray:
return _byteArrayOffset + position + length < _byteArrayData.Length;
return _byteArrayOffset + position + length <= _byteArrayData.Length;
case DataSource.Stream:
return position + length < _streamData.Length;
return position + length <= _streamData.Length;
// Everything else is invalid
case DataSource.UNKNOWN:

View File

@@ -73,11 +73,8 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Folder Include="ExecutableType\Apple\" />
<Folder Include="ExecutableType\ELF\" />
<ProjectReference Include="..\BurnOutSharp.Wrappers\BurnOutSharp.Wrappers.csproj" />
<ProjectReference Include="..\BurnOutSharp.Models\BurnOutSharp.Models.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,74 +0,0 @@
namespace BurnOutSharp.ExecutableType.Microsoft
{
/// <summary>
/// All constant values needed for file header reading
/// </summary>
internal static class Constants
{
public const ushort IMAGE_DOS_SIGNATURE = 0x5A4D; // MZ
public const ushort IMAGE_OS2_SIGNATURE = 0x454E; // NE
public const ushort IMAGE_OS2_SIGNATURE_LE = 0x454C; // LE
public const uint IMAGE_NT_SIGNATURE = 0x00004550; // PE00
#region IMAGE_DOS_HEADER
public const ushort ENEWEXE = 0x40; // Value of E_LFARLC for new .EXEs
public const ushort ENEWHDR = 0x003C; // Offset in old hdr. of ptr. to new
public const ushort ERESWDS = 0x0010; // No. of reserved words (OLD)
public const ushort ERES1WDS = 0x0004; // No. of reserved words in e_res
public const ushort ERES2WDS = 0x000A; // No. of reserved words in e_res2
public const ushort ECP = 0x0004; // Offset in struct of E_CP
public const ushort ECBLP = 0x0002; // Offset in struct of E_CBLP
public const ushort EMINALLOC = 0x000A; // Offset in struct of E_MINALLOC
#endregion
#region IMAGE_OS2_HEADER
public const ushort NERESWORDS = 3; // 6 bytes reserved
public const ushort NECRC = 8; //Offset into new header of NE_CRC
#endregion
#region NewSeg
public const ushort NSALIGN = 9; // Segment data aligned on 512 byte boundaries
public const ushort NSLOADED = 0x0004; // ns_sector field contains memory addr
#endregion
#region RsrcNameInfo
public const ushort RSORDID = 0x8000; /* if high bit of ID set then integer id */
/* otherwise ID is offset of string from
the beginning of the resource table */
/* Ideally these are the same as the */
/* corresponding segment flags */
public const ushort RNMOVE = 0x0010; /* Moveable resource */
public const ushort RNPURE = 0x0020; /* Pure (read-only) resource */
public const ushort RNPRELOAD = 0x0040; /* Preloaded resource */
public const ushort RNDISCARD = 0xF000; /* Discard priority level for resource */
#endregion
#region IMAGE_OPTIONAL_HEADER
public const ushort IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
#endregion
#region IMAGE_SECTION_HEADER
public const int IMAGE_SIZEOF_SHORT_NAME = 8;
#endregion
#region IMAGE_RESOURCE_DATA_ENTRY
public const uint IMAGE_RESOURCE_DATA_IS_DIRECTORY = 0x80000000;
public const uint IMAGE_RESOURCE_NAME_IS_STRING = 0x80000000;
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +0,0 @@
namespace BurnOutSharp.ExecutableType.Microsoft.LE
{
/// <summary>
/// PLACEHOLDER LE/LX
/// </summary>
public class LinearExecutable
{
}
}

View File

@@ -1,217 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.MZ.Headers
{
/// <summary>
/// The MS-DOS EXE format, also known as MZ after its signature (the initials of Microsoft engineer Mark Zbykowski),
/// was introduced with MS-DOS 2.0 (version 1.0 only sported the simple COM format). It is designed as a relocatable
/// executable running under real mode. As such, only DOS and Windows 9x can use this format natively, but there are
/// several free DOS emulators (e.g., DOSBox) that support it and that run under various operating systems (e.g.,
/// Linux, Amiga, Windows NT, etc.). Although they can exist on their own, MZ executables are embedded in all NE, LE,
/// and PE executables, usually as stubs so that when they are ran under DOS, they display a warning.
/// </summary>
/// <remarks>https://wiki.osdev.org/MZ</remarks>
public class MSDOSExecutableHeader
{
#region Standard Fields
/// <summary>
/// 0x5A4D (ASCII for 'M' and 'Z') [00]
/// </summary>
public ushort Magic;
/// <summary>
/// Number of bytes in the last page. [02]
/// </summary>
public ushort LastPageBytes;
/// <summary>
/// Number of whole/partial pages. [04]
/// </summary>
public ushort Pages;
/// <summary>
/// Number of entries in the relocation table. [06]
/// </summary>
public ushort Relocations;
/// <summary>
/// The number of paragraphs taken up by the header.It can be any value, as the loader
/// just uses it to find where the actual executable data starts. It may be larger than
/// what the "standard" fields take up, and you may use it if you want to include your
/// own header metadata, or put the relocation table there, or use it for any other purpose. [08]
/// </summary>
public ushort HeaderParagraphSize;
/// <summary>
/// The number of paragraphs required by the program, excluding the PSP and program image.
/// If no free block is big enough, the loading stops. [0A]
/// </summary>
public ushort MinimumExtraParagraphs;
/// <summary>
/// The number of paragraphs requested by the program.
/// If no free block is big enough, the biggest one possible is allocated. [0C]
/// </summary>
public ushort MaximumExtraParagraphs;
/// <summary>
/// Relocatable segment address for SS. [0E]
/// </summary>
public ushort InitialSSValue;
/// <summary>
/// Initial value for SP. [10]
/// </summary>
public ushort InitialSPValue;
/// <summary>
/// When added to the sum of all other words in the file, the result should be zero. [12]
/// </summary>
public ushort Checksum;
/// <summary>
/// Initial value for IP. [14]
/// </summary>
public ushort InitialIPValue;
/// <summary>
/// Relocatable segment address for CS. [16]
/// </summary>
public ushort InitialCSValue;
/// <summary>
/// The (absolute) offset to the relocation table. [18]
/// </summary>
public ushort RelocationTableAddr;
/// <summary>
/// Value used for overlay management.
/// If zero, this is the main executable. [1A]
/// </summary>
public ushort OverlayNumber;
#endregion
#region PE Extensions
/// <summary>
/// Reserved words [1C]
/// </summary>
public ushort[] Reserved1;
/// <summary>
/// Defined by name but no other information is given; typically zeroes [24]
/// </summary>
public ushort OEMIdentifier;
/// <summary>
/// Defined by name but no other information is given; typically zeroes [26]
/// </summary>
public ushort OEMInformation;
/// <summary>
/// Reserved words [28]
/// </summary>
public ushort[] Reserved2;
/// <summary>
/// Starting address of the PE header [3C]
/// </summary>
public int NewExeHeaderAddr;
#endregion
/// <summary>
/// All data after the last item in the header but before the new EXE header address
/// </summary>
public byte[] ExecutableData;
public static MSDOSExecutableHeader Deserialize(Stream stream, bool asStub = true)
{
MSDOSExecutableHeader idh = new MSDOSExecutableHeader();
idh.Magic = stream.ReadUInt16();
idh.LastPageBytes = stream.ReadUInt16();
idh.Pages = stream.ReadUInt16();
idh.Relocations = stream.ReadUInt16();
idh.HeaderParagraphSize = stream.ReadUInt16();
idh.MinimumExtraParagraphs = stream.ReadUInt16();
idh.MaximumExtraParagraphs = stream.ReadUInt16();
idh.InitialSSValue = stream.ReadUInt16();
idh.InitialSPValue = stream.ReadUInt16();
idh.Checksum = stream.ReadUInt16();
idh.InitialIPValue = stream.ReadUInt16();
idh.InitialCSValue = stream.ReadUInt16();
idh.RelocationTableAddr = stream.ReadUInt16();
idh.OverlayNumber = stream.ReadUInt16();
// If we're not reading as a stub, return now
if (!asStub)
return idh;
idh.Reserved1 = new ushort[Constants.ERES1WDS];
for (int i = 0; i < Constants.ERES1WDS; i++)
{
idh.Reserved1[i] = stream.ReadUInt16();
}
idh.OEMIdentifier = stream.ReadUInt16();
idh.OEMInformation = stream.ReadUInt16();
idh.Reserved2 = new ushort[Constants.ERES2WDS];
for (int i = 0; i < Constants.ERES2WDS; i++)
{
idh.Reserved2[i] = stream.ReadUInt16();
}
idh.NewExeHeaderAddr = stream.ReadInt32();
idh.ExecutableData = stream.ReadBytes(idh.NewExeHeaderAddr - (int)stream.Position);
return idh;
}
public static MSDOSExecutableHeader Deserialize(byte[] content, ref int offset, bool asStub = true)
{
MSDOSExecutableHeader idh = new MSDOSExecutableHeader();
idh.Magic = content.ReadUInt16(ref offset);
idh.LastPageBytes = content.ReadUInt16(ref offset);
idh.Pages = content.ReadUInt16(ref offset);
idh.Relocations = content.ReadUInt16(ref offset);
idh.HeaderParagraphSize = content.ReadUInt16(ref offset);
idh.MinimumExtraParagraphs = content.ReadUInt16(ref offset);
idh.MaximumExtraParagraphs = content.ReadUInt16(ref offset);
idh.InitialSSValue = content.ReadUInt16(ref offset);
idh.InitialSPValue = content.ReadUInt16(ref offset);
idh.Checksum = content.ReadUInt16(ref offset);
idh.InitialIPValue = content.ReadUInt16(ref offset);
idh.InitialCSValue = content.ReadUInt16(ref offset);
idh.RelocationTableAddr = content.ReadUInt16(ref offset);
idh.OverlayNumber = content.ReadUInt16(ref offset);
// If we're not reading as a stub, return now
if (!asStub)
return idh;
idh.Reserved1 = new ushort[Constants.ERES1WDS];
for (int i = 0; i < Constants.ERES1WDS; i++)
{
idh.Reserved1[i] = content.ReadUInt16(ref offset);
}
idh.OEMIdentifier = content.ReadUInt16(ref offset);
idh.OEMInformation = content.ReadUInt16(ref offset);
idh.Reserved2 = new ushort[Constants.ERES2WDS];
for (int i = 0; i < Constants.ERES2WDS; i++)
{
idh.Reserved2[i] = content.ReadUInt16(ref offset);
}
idh.NewExeHeaderAddr = content.ReadInt32(ref offset);
idh.ExecutableData = content.ReadBytes(ref offset, idh.NewExeHeaderAddr - offset);
return idh;
}
}
}

View File

@@ -1,79 +0,0 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// These name strings are case-sensitive and are not null-terminated
/// </summary>
public class ResidentNameTableEntry
{
/// <summary>
/// Length of the name string that follows.
/// A zero value indicates the end of the name table.
/// </summary>
public byte Length;
/// <summary>
/// ASCII text of the name string.
/// </summary>
public byte[] Data;
/// <summary>
/// Ordinal number (index into entry table).
/// This value is ignored for the module name.
/// </summary>
public ushort OrdinalNumber;
/// <summary>
/// ASCII text of the name string
/// </summary>
public string DataAsString
{
get
{
if (Data == null)
return string.Empty;
// Try to read direct as ASCII
try
{
return Encoding.ASCII.GetString(Data);
}
catch { }
// If ASCII encoding fails, then just return an empty string
return string.Empty;
}
}
public static ResidentNameTableEntry Deserialize(Stream stream)
{
var rnte = new ResidentNameTableEntry();
rnte.Length = stream.ReadByteValue();
if (rnte.Length == 0)
return rnte;
rnte.Data = stream.ReadBytes(rnte.Length);
rnte.OrdinalNumber = stream.ReadUInt16();
return rnte;
}
public static ResidentNameTableEntry Deserialize(byte[] content, ref int offset)
{
var rnte = new ResidentNameTableEntry();
rnte.Length = content.ReadByte(ref offset);
if (rnte.Length == 0)
return rnte;
rnte.Data = content.ReadBytes(ref offset, rnte.Length);
rnte.OrdinalNumber = content.ReadUInt16(ref offset);
return rnte;
}
}
}

View File

@@ -1,44 +0,0 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// Resource type and name strings
/// </summary>
public class ResourceNameString
{
/// <summary>
/// Length of the type or name string that follows. A zero value
/// indicates the end of the resource type and name string, also
/// the end of the resource table.
/// </summary>
public byte Length;
/// <summary>
/// ASCII text of the type or name string.
/// </summary>
public char[] Value;
public static ResourceNameString Deserialize(Stream stream)
{
var rns = new ResourceNameString();
rns.Length = stream.ReadByteValue();
rns.Value = stream.ReadChars(rns.Length, Encoding.ASCII);
return rns;
}
public static ResourceNameString Deserialize(byte[] content, ref int offset)
{
var rns = new ResourceNameString();
rns.Length = content.ReadByte(ref offset);
rns.Value = Encoding.ASCII.GetChars(content, offset, rns.Length); offset += rns.Length;
return rns;
}
}
}

View File

@@ -1,75 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// A table of resources for this type
/// </summary>
public class ResourceTableEntry
{
/// <summary>
/// File offset to the contents of the resource data,
/// relative to beginning of file. The offset is in terms
/// of the alignment shift count value specified at
/// beginning of the resource table.
/// </summary>
public ushort Offset;
/// <summary>
/// Length of the resource in the file (in bytes).
/// </summary>
public ushort Length;
/// <summary>
/// Resource flags
/// </summary>
public ResourceTableEntryFlags Flags;
/// <summary>
/// This is an integer type if the high-order
/// bit is set (8000h), otherwise it is the offset to the
/// resource string, the offset is relative to the
/// beginning of the resource table.
/// </summary>
public ushort ResourceID;
/// <summary>
/// Reserved.
/// </summary>
public ushort Handle;
/// <summary>
/// Reserved.
/// </summary>
public ushort Usage;
public static ResourceTableEntry Deserialize(Stream stream)
{
var ni = new ResourceTableEntry();
ni.Offset = stream.ReadUInt16();
ni.Length = stream.ReadUInt16();
ni.Flags = (ResourceTableEntryFlags)stream.ReadUInt16();
ni.ResourceID = stream.ReadUInt16();
ni.Handle = stream.ReadUInt16();
ni.Usage = stream.ReadUInt16();
return ni;
}
public static ResourceTableEntry Deserialize(byte[] content, ref int offset)
{
var ni = new ResourceTableEntry();
ni.Offset = content.ReadUInt16(ref offset);
ni.Length = content.ReadUInt16(ref offset);
ni.Flags = (ResourceTableEntryFlags)content.ReadUInt16(ref offset);
ni.ResourceID = content.ReadUInt16(ref offset);
ni.Handle = content.ReadUInt16(ref offset);
ni.Usage = content.ReadUInt16(ref offset);
return ni;
}
}
}

View File

@@ -1,69 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// Resource type information block
/// </summary>
public class ResourceTypeInformationBlock
{
/// <summary>
/// Type ID. This is an integer type if the high-order bit is
/// set (8000h); otherwise, it is an offset to the type string,
/// the offset is relative to the beginning of the resource
/// table. A zero type ID marks the end of the resource type
/// information blocks.
/// </summary>
public ushort TypeID;
/// <summary>
/// Number of resources for this type.
/// </summary>
public ushort ResourceCount;
/// <summary>
/// Reserved.
/// </summary>
public uint Reserved;
/// <summary>
/// Reserved.
/// </summary>
public ResourceTableEntry[] ResourceTable;
public static ResourceTypeInformationBlock Deserialize(Stream stream)
{
var rtib = new ResourceTypeInformationBlock();
rtib.TypeID = stream.ReadUInt16();
rtib.ResourceCount = stream.ReadUInt16();
rtib.Reserved = stream.ReadUInt32();
rtib.ResourceTable = new ResourceTableEntry[rtib.ResourceCount];
for (int i = 0; i < rtib.ResourceCount; i++)
{
rtib.ResourceTable[i] = ResourceTableEntry.Deserialize(stream);
}
return rtib;
}
public static ResourceTypeInformationBlock Deserialize(byte[] content, ref int offset)
{
var rtib = new ResourceTypeInformationBlock();
rtib.TypeID = content.ReadUInt16(ref offset);
rtib.ResourceCount = content.ReadUInt16(ref offset);
rtib.Reserved = content.ReadUInt32(ref offset);
rtib.ResourceTable = new ResourceTableEntry[rtib.ResourceCount];
for (int i = 0; i < rtib.ResourceCount; i++)
{
rtib.ResourceTable[i] = ResourceTableEntry.Deserialize(content, ref offset);
}
return rtib;
}
}
}

View File

@@ -1,61 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Entries
{
/// <summary>
/// The segment table contains an entry for each segment in the executable
/// file. The number of segment table entries are defined in the segmented
/// EXE header. The first entry in the segment table is segment number 1.
/// The following is the structure of a segment table entry.
/// </summary>
public class SegmentTableEntry
{
/// <summary>
/// Logical-sector offset (n byte) to the contents of the segment
/// data, relative to the beginning of the file. Zero means no
/// file data.
/// </summary>
public ushort StartFileSector;
/// <summary>
/// Length of the segment in the file, in bytes. Zero means 64K.
/// </summary>
public ushort BytesInFile;
/// <summary>
/// Attribute flags
/// </summary>
public SegmentTableEntryFlags Flags;
/// <summary>
/// Minimum allocation size of the segment, in bytes.
/// Total size of the segment. Zero means 64K
/// </summary>
public ushort MinimumAllocation;
public static SegmentTableEntry Deserialize(Stream stream)
{
var nste = new SegmentTableEntry();
nste.StartFileSector = stream.ReadUInt16();
nste.BytesInFile = stream.ReadUInt16();
nste.Flags = (SegmentTableEntryFlags)stream.ReadUInt16();
nste.MinimumAllocation = stream.ReadUInt16();
return nste;
}
public static SegmentTableEntry Deserialize(byte[] content, ref int offset)
{
var nste = new SegmentTableEntry();
nste.StartFileSector = content.ReadUInt16(ref offset);
nste.BytesInFile = content.ReadUInt16(ref offset);
nste.Flags = (SegmentTableEntryFlags)content.ReadUInt16(ref offset);
nste.MinimumAllocation = content.ReadUInt16(ref offset);
return nste;
}
}
}

View File

@@ -1,256 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Headers
{
/// <summary>
/// The NE header is a relatively large structure with multiple characteristics.
/// Because of the age of the format some items are unclear in meaning.
/// </summary>
/// <remarks>http://bytepointer.com/resources/win16_ne_exe_format_win3.0.htm</remarks>
public class NewExecutableHeader
{
/// <summary>
/// Signature word. [00]
/// "N" is low-order byte.
/// "E" is high-order byte.
/// </summary>
public ushort Magic;
/// <summary>
/// Version number of the linker. [02]
/// </summary>
public byte LinkerVersion;
/// <summary>
/// Revision number of the linker. [03]
/// </summary>
public byte LinkerRevision;
/// <summary>
/// Entry Table file offset, relative to the beginning of the segmented EXE header. [04]
/// </summary>
public ushort EntryTableOffset;
/// <summary>
/// Number of bytes in the entry table. [06]
/// </summary>
public ushort EntryTableSize;
/// <summary>
/// 32-bit CRC of entire contents of file. [08]
/// These words are taken as 00 during the calculation.
/// </summary>
public uint CrcChecksum;
/// <summary>
/// Program flags, bitmapped [0C]
/// </summary>
public byte ProgramFlags;
/// <summary>
/// Application flags, bitmapped [0D]
/// </summary>
public byte ApplicationFlags;
/// <summary>
/// Automatic data segment number [0E]
/// </summary>
public ushort Autodata;
/// <summary>
/// Initial heap allocation [10]
/// </summary>
public ushort InitialHeapAlloc;
/// <summary>
/// Initial stack allocation [12]
/// </summary>
public ushort InitialStackAlloc;
/// <summary>
/// CS:IP entry point, CS is index into segment table [14]
/// </summary>
public uint InitialCSIPSetting;
/// <summary>
/// SS:SP inital stack pointer, SS is index into segment table [18]
/// </summary>
public uint InitialSSSPSetting;
/// <summary>
/// Number of segments in segment table [1C]
/// </summary>
public ushort FileSegmentCount;
/// <summary>
/// Entries in Module Reference Table [1E]
/// </summary>
public ushort ModuleReferenceTableSize;
/// <summary>
/// Size of non-resident name table [20]
/// </summary>
public ushort NonResidentNameTableSize;
/// <summary>
/// Offset of Segment Table [22]
/// </summary>
public ushort SegmentTableOffset;
/// <summary>
/// Offset of Resource Table [24]
/// </summary>
public ushort ResourceTableOffset;
/// <summary>
/// Offset of resident name table [26]
/// </summary>
public ushort ResidentNameTableOffset;
/// <summary>
/// Offset of Module Reference Table [28]
/// </summary>
public ushort ModuleReferenceTableOffset;
/// <summary>
/// Offset of Imported Names Table [2A]
/// </summary>
public ushort ImportedNamesTableOffset;
/// <summary>
/// Offset of Non-resident Names Table [2C]
/// </summary>
public uint NonResidentNamesTableOffset;
/// <summary>
/// Count of moveable entry points listed in entry table [30]
/// </summary>
public ushort MovableEntriesCount;
/// <summary>
/// File allignment size shift count (0-9 (default 512 byte pages)) [32]
/// </summary>
public ushort SegmentAlignmentShiftCount;
/// <summary>
/// Count of resource table entries [34]
/// </summary>
public ushort ResourceEntriesCount;
/// <summary>
/// Target operating system [36]
/// </summary>
public byte TargetOperatingSystem;
/// <summary>
/// Other OS/2 flags [37]
/// </summary>
public byte AdditionalFlags;
/// <summary>
/// Offset to return thunks or start of gangload area [38]
/// </summary>
public ushort ReturnThunkOffset;
/// <summary>
/// Offset to segment reference thunks or size of gangload area [3A]
/// </summary>
public ushort SegmentReferenceThunkOffset;
/// <summary>
/// Minimum code swap area size [3C]
/// </summary>
public ushort MinCodeSwapAreaSize;
/// <summary>
/// Windows SDK revison number [3E]
/// </summary>
public byte WindowsSDKRevision;
/// <summary>
/// Windows SDK version number [3F]
/// </summary>
public byte WindowsSDKVersion;
public static NewExecutableHeader Deserialize(Stream stream)
{
var neh = new NewExecutableHeader();
neh.Magic = stream.ReadUInt16();
neh.LinkerVersion = stream.ReadByteValue();
neh.LinkerRevision = stream.ReadByteValue();
neh.EntryTableOffset = stream.ReadUInt16();
neh.EntryTableSize = stream.ReadUInt16();
neh.CrcChecksum = stream.ReadUInt32();
neh.ProgramFlags = stream.ReadByteValue();
neh.ApplicationFlags = stream.ReadByteValue();
neh.Autodata = stream.ReadUInt16();
neh.InitialHeapAlloc = stream.ReadUInt16();
neh.InitialStackAlloc = stream.ReadUInt16();
neh.InitialCSIPSetting = stream.ReadUInt32();
neh.InitialSSSPSetting = stream.ReadUInt32();
neh.FileSegmentCount = stream.ReadUInt16();
neh.ModuleReferenceTableSize = stream.ReadUInt16();
neh.NonResidentNameTableSize = stream.ReadUInt16();
neh.SegmentTableOffset = stream.ReadUInt16();
neh.ResourceTableOffset = stream.ReadUInt16();
neh.ResidentNameTableOffset = stream.ReadUInt16();
neh.ModuleReferenceTableOffset = stream.ReadUInt16();
neh.ImportedNamesTableOffset = stream.ReadUInt16();
neh.NonResidentNamesTableOffset = stream.ReadUInt32();
neh.MovableEntriesCount = stream.ReadUInt16();
neh.SegmentAlignmentShiftCount = stream.ReadUInt16();
neh.ResourceEntriesCount = stream.ReadUInt16();
neh.TargetOperatingSystem = stream.ReadByteValue();
neh.AdditionalFlags = stream.ReadByteValue();
neh.ReturnThunkOffset = stream.ReadUInt16();
neh.SegmentReferenceThunkOffset = stream.ReadUInt16();
neh.MinCodeSwapAreaSize = stream.ReadUInt16();
neh.WindowsSDKRevision = stream.ReadByteValue();
neh.WindowsSDKVersion = stream.ReadByteValue();
return neh;
}
public static NewExecutableHeader Deserialize(byte[] content, ref int offset)
{
var neh = new NewExecutableHeader();
neh.Magic = content.ReadUInt16(ref offset);
neh.LinkerVersion = content.ReadByte(ref offset);
neh.LinkerRevision = content.ReadByte(ref offset);
neh.EntryTableOffset = content.ReadUInt16(ref offset);
neh.EntryTableSize = content.ReadUInt16(ref offset);
neh.CrcChecksum = content.ReadUInt32(ref offset);
neh.ProgramFlags = content.ReadByte(ref offset);
neh.ApplicationFlags = content.ReadByte(ref offset);
neh.Autodata = content.ReadUInt16(ref offset);
neh.InitialHeapAlloc = content.ReadUInt16(ref offset);
neh.InitialStackAlloc = content.ReadUInt16(ref offset);
neh.InitialCSIPSetting = content.ReadUInt32(ref offset);
neh.InitialSSSPSetting = content.ReadUInt32(ref offset);
neh.FileSegmentCount = content.ReadUInt16(ref offset);
neh.ModuleReferenceTableSize = content.ReadUInt16(ref offset);
neh.NonResidentNameTableSize = content.ReadUInt16(ref offset);
neh.SegmentTableOffset = content.ReadUInt16(ref offset);
neh.ResourceTableOffset = content.ReadUInt16(ref offset);
neh.ResidentNameTableOffset = content.ReadUInt16(ref offset);
neh.ModuleReferenceTableOffset = content.ReadUInt16(ref offset);
neh.ImportedNamesTableOffset = content.ReadUInt16(ref offset);
neh.NonResidentNamesTableOffset = content.ReadUInt32(ref offset);
neh.MovableEntriesCount = content.ReadUInt16(ref offset);
neh.SegmentAlignmentShiftCount = content.ReadUInt16(ref offset);
neh.ResourceEntriesCount = content.ReadUInt16(ref offset);
neh.TargetOperatingSystem = content.ReadByte(ref offset);
neh.AdditionalFlags = content.ReadByte(ref offset);
neh.ReturnThunkOffset = content.ReadUInt16(ref offset);
neh.SegmentReferenceThunkOffset = content.ReadUInt16(ref offset);
neh.MinCodeSwapAreaSize = content.ReadUInt16(ref offset);
neh.WindowsSDKRevision = content.ReadByte(ref offset);
neh.WindowsSDKVersion = content.ReadByte(ref offset);
return neh;
}
}
}

View File

@@ -1,233 +0,0 @@
using System;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.MZ.Headers;
using BurnOutSharp.ExecutableType.Microsoft.NE.Headers;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE
{
/// <summary>
/// The WIN-NE executable format, designed for Windows 3.x, was the "NE", or "New Executable" format.
/// Again, a 16bit format, it alleviated the maximum size restrictions that the MZ format had.
/// </summary>
public class NewExecutable
{
/// <summary>
/// Value determining if the executable is initialized or not
/// </summary>
public bool Initialized { get; } = false;
/// <summary>
/// Source array that the executable was parsed from
/// </summary>
private readonly byte[] _sourceArray = null;
/// <summary>
/// Source stream that the executable was parsed from
/// </summary>
private readonly Stream _sourceStream = null;
#region Headers
/// <summary>
/// he DOS stub is a valid MZ exe.
/// This enables the develper to package both an MS-DOS and Win16 version of the program,
/// but normally just prints "This Program requires Microsoft Windows".
/// The e_lfanew field (offset 0x3C) points to the NE header.
// </summary>
public MSDOSExecutableHeader DOSStubHeader;
/// <summary>
/// The NE header is a relatively large structure with multiple characteristics.
/// Because of the age of the format some items are unclear in meaning.
/// </summary>
public NewExecutableHeader NewExecutableHeader;
#endregion
#region Tables
#endregion
#region Constructors
// TODO: Add more and more parts of a standard NE executable, not just the header
// TODO: Tables? What about the tables?
// TODO: Implement the rest of the structures found at http://bytepointer.com/resources/win16_ne_exe_format_win3.0.htm
// (Left off at RESIDENT-NAME TABLE)
/// <summary>
/// Create a NewExecutable object from a stream
/// </summary>
/// <param name="stream">Stream representing a file</param>
/// <remarks>
/// This constructor assumes that the stream is already in the correct position to start parsing
/// </remarks>
public NewExecutable(Stream stream)
{
if (stream == null || !stream.CanRead || !stream.CanSeek)
return;
this.Initialized = Deserialize(stream);
this._sourceStream = stream;
}
/// <summary>
/// Create a NewExecutable object from a byte array
/// </summary>
/// <param name="fileContent">Byte array representing a file</param>
/// <param name="offset">Positive offset representing the current position in the array</param>
public NewExecutable(byte[] fileContent, int offset)
{
if (fileContent == null || fileContent.Length == 0 || offset < 0)
return;
this.Initialized = Deserialize(fileContent, offset);
this._sourceArray = fileContent;
}
/// <summary>
/// Deserialize a NewExecutable object from a stream
/// </summary>
/// <param name="stream">Stream representing a file</param>
private bool Deserialize(Stream stream)
{
try
{
// Attempt to read the DOS header first
this.DOSStubHeader = MSDOSExecutableHeader.Deserialize(stream);
stream.Seek(this.DOSStubHeader.NewExeHeaderAddr, SeekOrigin.Begin);
if (this.DOSStubHeader.Magic != Constants.IMAGE_DOS_SIGNATURE)
return false;
// If the new header address is invalid for the file, it's not a NE
if (this.DOSStubHeader.NewExeHeaderAddr >= stream.Length)
return false;
// Then attempt to read the NE header
this.NewExecutableHeader = NewExecutableHeader.Deserialize(stream);
if (this.NewExecutableHeader.Magic != Constants.IMAGE_OS2_SIGNATURE)
return false;
}
catch (Exception ex)
{
//Console.WriteLine($"Errored out on a file: {ex}");
return false;
}
return true;
}
/// <summary>
/// Deserialize a NewExecutable object from a byte array
/// </summary>
/// <param name="fileContent">Byte array representing a file</param>
/// <param name="offset">Positive offset representing the current position in the array</param>
private bool Deserialize(byte[] content, int offset)
{
try
{
// Attempt to read the DOS header first
this.DOSStubHeader = MSDOSExecutableHeader.Deserialize(content, ref offset);
offset = this.DOSStubHeader.NewExeHeaderAddr;
if (this.DOSStubHeader.Magic != Constants.IMAGE_DOS_SIGNATURE)
return false;
// If the new header address is invalid for the file, it's not a PE
if (this.DOSStubHeader.NewExeHeaderAddr >= content.Length)
return false;
// Then attempt to read the NE header
this.NewExecutableHeader = NewExecutableHeader.Deserialize(content, ref offset);
if (this.NewExecutableHeader.Magic != Constants.IMAGE_OS2_SIGNATURE)
return false;
}
catch (Exception ex)
{
//Console.WriteLine($"Errored out on a file: {ex}");
return false;
}
return true;
}
#endregion
#region Helpers
/// <summary>
/// Read an arbitrary range from the source
/// </summary>
/// <param name="rangeStart">The start of where to read data from, -1 means start of source</param>
/// <param name="length">How many bytes to read, -1 means read until end</param>
/// <returns></returns>
public byte[] ReadArbitraryRange(int rangeStart = -1, int length = -1)
{
try
{
// If we have a source stream, use that
if (this._sourceStream != null)
return ReadArbitraryRangeFromSourceStream(rangeStart, length);
// If we have a source array, use that
if (this._sourceArray != null)
return ReadArbitraryRangeFromSourceArray(rangeStart, length);
// Otherwise, return null
return null;
}
catch (Exception ex)
{
// TODO: How to handle this differently?
return null;
}
}
/// <summary>
/// Read an arbitrary range from the stream source, if possible
/// </summary>
/// <param name="rangeStart">The start of where to read data from, -1 means start of source</param>
/// <param name="length">How many bytes to read, -1 means read until end</param>
/// <returns></returns>
private byte[] ReadArbitraryRangeFromSourceStream(int rangeStart, int length)
{
lock (this._sourceStream)
{
int startingIndex = (int)Math.Max(rangeStart, 0);
int readLength = (int)Math.Min(length == -1 ? length = Int32.MaxValue : length, this._sourceStream.Length);
long originalPosition = this._sourceStream.Position;
this._sourceStream.Seek(startingIndex, SeekOrigin.Begin);
byte[] sectionData = this._sourceStream.ReadBytes(readLength);
this._sourceStream.Seek(originalPosition, SeekOrigin.Begin);
return sectionData;
}
}
/// <summary>
/// Read an arbitrary range from the array source, if possible
/// </summary>
/// <param name="rangeStart">The start of where to read data from, -1 means start of source</param>
/// <param name="length">How many bytes to read, -1 means read until end</param>
/// <returns></returns>
private byte[] ReadArbitraryRangeFromSourceArray(int rangeStart, int length)
{
int startingIndex = (int)Math.Max(rangeStart, 0);
int readLength = (int)Math.Min(length == -1 ? length = Int32.MaxValue : length, this._sourceArray.Length);
try
{
return this._sourceArray.ReadBytes(ref startingIndex, readLength);
}
catch
{
// Just absorb errors for now
// TODO: Investigate why and when this would be hit
return null;
}
}
#endregion
}
}

View File

@@ -1,59 +0,0 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.NE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Tables
{
/// <summary>
/// The resident-name table follows the resource table, and contains this
/// module's name string and resident exported procedure name strings. The
/// first string in this table is this module's name. These name strings
/// are case-sensitive and are not null-terminated.
/// </summary>
public class ResidentNameTable
{
/// <summary>
/// The first string in this table is this module's name.
/// These name strings are case-sensitive and are not null-terminated.
/// </summary>
public ResidentNameTableEntry[] NameTableEntries;
public static ResidentNameTable Deserialize(Stream stream)
{
var rnt = new ResidentNameTable();
var nameTableEntries = new List<ResidentNameTableEntry>();
while (true)
{
var rnte = ResidentNameTableEntry.Deserialize(stream);
if (rnte == null || rnte.Length == 0)
break;
nameTableEntries.Add(rnte);
}
rnt.NameTableEntries = nameTableEntries.ToArray();
return rnt;
}
public static ResidentNameTable Deserialize(byte[] content, ref int offset)
{
var rnt = new ResidentNameTable();
var nameTableEntries = new List<ResidentNameTableEntry>();
while (true)
{
var rnte = ResidentNameTableEntry.Deserialize(content, ref offset);
if (rnte == null || rnte.Length == 0)
break;
nameTableEntries.Add(rnte);
}
rnt.NameTableEntries = nameTableEntries.ToArray();
return rnt;
}
}
}

View File

@@ -1,101 +0,0 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.NE.Entries;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.NE.Tables
{
/// <summary>
/// The resource table follows the segment table and contains entries for
/// each resource in the executable file. The resource table consists of
/// an alignment shift count, followed by a table of resource records. The
/// resource records define the type ID for a set of resources. Each
/// resource record contains a table of resource entries of the defined
/// type. The resource entry defines the resource ID or name ID for the
/// resource. It also defines the location and size of the resource.
/// </summary>
/// <remarks>http://bytepointer.com/resources/win16_ne_exe_format_win3.0.htm</remarks>
public class ResourceTable
{
/// <summary>
/// Alignment shift count for resource data.
/// </summary>
public ushort AlignmentShiftCount;
/// <summary>
/// A table of resource type information blocks.
/// </summary>
public ResourceTypeInformationBlock[] TypeInformationBlocks;
/// <summary>
/// Resource type and name strings are stored at the end of the
/// resource table. Note that these strings are NOT null terminated and
/// are case sensitive.
/// </summary>
public ResourceNameString[] TypeAndNameStrings;
public static ResourceTable Deserialize(Stream stream)
{
var rt = new ResourceTable();
rt.AlignmentShiftCount = stream.ReadUInt16();
var typeInformationBlocks = new List<ResourceTypeInformationBlock>();
while (true)
{
var block = ResourceTypeInformationBlock.Deserialize(stream);
if (block.TypeID == 0)
break;
typeInformationBlocks.Add(block);
}
rt.TypeInformationBlocks = typeInformationBlocks.ToArray();
var typeAndNameStrings = new List<ResourceNameString>();
while (true)
{
var str = ResourceNameString.Deserialize(stream);
if (str.Length == 0)
break;
typeAndNameStrings.Add(str);
}
rt.TypeAndNameStrings = typeAndNameStrings.ToArray();
return rt;
}
public static ResourceTable Deserialize(byte[] content, ref int offset)
{
var rt = new ResourceTable();
rt.AlignmentShiftCount = content.ReadUInt16(ref offset);
var typeInformationBlocks = new List<ResourceTypeInformationBlock>();
while (true)
{
var block = ResourceTypeInformationBlock.Deserialize(content, ref offset);
if (block.TypeID == 0)
break;
typeInformationBlocks.Add(block);
}
rt.TypeInformationBlocks = typeInformationBlocks.ToArray();
var typeAndNameStrings = new List<ResourceNameString>();
while (true)
{
var str = ResourceNameString.Deserialize(content, ref offset);
if (str.Length == 0)
break;
typeAndNameStrings.Add(str);
}
rt.TypeAndNameStrings = typeAndNameStrings.ToArray();
return rt;
}
}
}

View File

@@ -1,48 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// The base relocation table is divided into blocks.
/// Each block represents the base relocations for a 4K page.
/// Each block must start on a 32-bit boundary.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#base-relocation-block</remarks>
public class BaseRelocationBlock
{
/// <summary>
/// The image base plus the page RVA is added to each offset to create the VA where the base relocation must be applied.
/// </summary>
public uint PageRVA;
/// <summary>
/// The total number of bytes in the base relocation block, including the Page RVA and Block Size fields and the Type/Offset fields that follow.
/// </summary>
public uint BlockSize;
public static BaseRelocationBlock Deserialize(Stream stream)
{
var brb = new BaseRelocationBlock();
brb.PageRVA = stream.ReadUInt32();
brb.BlockSize = stream.ReadUInt32();
// TODO: Read in the type/offset field entries
return brb;
}
public static BaseRelocationBlock Deserialize(byte[] content, ref int offset)
{
var brb = new BaseRelocationBlock();
brb.PageRVA = content.ReadUInt32(ref offset);
brb.BlockSize = content.ReadUInt32(ref offset);
// TODO: Read in the type/offset field entries
return brb;
}
}
}

View File

@@ -1,69 +0,0 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each entry in the export address table is a field that uses one of two formats in the following table.
/// If the address specified is not within the export section (as defined by the address and length that are indicated in the optional header), the field is an export RVA, which is an actual address in code or data.
/// Otherwise, the field is a forwarder RVA, which names a symbol in another DLL.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#export-address-table</remarks>
public class ExportAddressTableEntry
{
/// <summary>
/// The address of the exported symbol when loaded into memory, relative to the image base.
/// For example, the address of an exported function.
/// </summary>
public uint ExportRVA;
/// <summary>
/// The pointer to a null-terminated ASCII string in the export section.
/// This string must be within the range that is given by the export table data directory entry.
/// This string gives the DLL name and the name of the export (for example, "MYDLL.expfunc") or the DLL name and the ordinal number of the export (for example, "MYDLL.#27").
/// </summary>
public uint ForwarderRVA; // TODO: Read this into a separate field
/// <summary>
/// A null-terminated ASCII string in the export section.
/// This string must be within the range that is given by the export table data directory entry.
/// This string gives the DLL name and the name of the export (for example, "MYDLL.expfunc") or the DLL name and the ordinal number of the export (for example, "MYDLL.#27").
/// </summary>
public string Forwarder;
public static ExportAddressTableEntry Deserialize(Stream stream, SectionHeader[] sections)
{
var eate = new ExportAddressTableEntry();
eate.ExportRVA = stream.ReadUInt32();
eate.ForwarderRVA = eate.ExportRVA;
int forwarderAddress = (int)PortableExecutable.ConvertVirtualAddress(eate.ForwarderRVA, sections);
if (forwarderAddress > -1 && forwarderAddress < stream.Length)
{
long originalPosition = stream.Position;
stream.Seek(forwarderAddress, SeekOrigin.Begin);
eate.Forwarder = stream.ReadString(Encoding.ASCII);
stream.Seek(originalPosition, SeekOrigin.Begin);
}
return eate;
}
public static ExportAddressTableEntry Deserialize(byte[] content, ref int offset, SectionHeader[] sections)
{
var eate = new ExportAddressTableEntry();
eate.ExportRVA = content.ReadUInt32(ref offset);
eate.ForwarderRVA = eate.ExportRVA;
int forwarderAddress = (int)PortableExecutable.ConvertVirtualAddress(eate.ForwarderRVA, sections);
if (forwarderAddress > -1 && forwarderAddress < content.Length)
eate.Forwarder = content.ReadString(ref forwarderAddress, Encoding.ASCII);
return eate;
}
}
}

View File

@@ -1,78 +0,0 @@
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each entry in the export address table is a field that uses one of two formats in the following table.
/// If the address specified is not within the export section (as defined by the address and length that are indicated in the optional header), the field is an export RVA, which is an actual address in code or data.
/// Otherwise, the field is a forwarder RVA, which names a symbol in another DLL.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-pdata-section</remarks>
public class FunctionTableEntry
{
#region 32-bit MIPS
/// <summary>
/// The VA of the corresponding function.
/// </summary>
public uint MIPSBeginAddress;
/// <summary>
/// The VA of the end of the function.
/// </summary>
public uint MIPSEndAddress;
/// <summary>
/// The pointer to the exception handler to be executed.
/// </summary>
public uint MIPSExceptionHandler;
/// <summary>
/// The pointer to additional information to be passed to the handler.
/// </summary>
public uint MIPSHandlerData;
/// <summary>
/// The VA of the end of the function's prolog.
/// </summary>
public uint MIPSPrologEndAddress;
#endregion
#region ARM, PowerPC, SH3 and SH4 Windows CE
/// <summary>
/// The VA of the corresponding function.
/// </summary>
public uint ARMBeginAddress;
/// <summary>
/// The VA of the end of the function.
///
/// 8 bits Prolog Length The number of instructions in the function's prolog.
/// 22 bits Function Length The number of instructions in the function.
/// 1 bit 32-bit Flag If set, the function consists of 32-bit instructions. If clear, the function consists of 16-bit instructions.
/// 1 bit Exception Flag If set, an exception handler exists for the function. Otherwise, no exception handler exists.
/// </summary>
public uint ARMLengthsAndFlags;
#endregion
#region x64 and Itanium
/// <summary>
/// The RVA of the corresponding function.
/// </summary>
public uint X64BeginAddress;
/// <summary>
/// The RVA of the end of the function.
/// </summary>
public uint X64EndAddress;
/// <summary>
/// The RVA of the unwind information.
/// </summary>
public uint X64UnwindInformation;
#endregion
}
}

View File

@@ -1,89 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each entry in the hint/name table has the following format
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#hintname-table</remarks>
public class HintNameTableEntry
{
/// <summary>
/// An index into the export name pointer table.
/// A match is attempted first with this value.
/// If it fails, a binary search is performed on the DLL's export name pointer table.
/// </summary>
public ushort Hint;
/// <summary>
/// An ASCII string that contains the name to import.
/// This is the string that must be matched to the public name in the DLL.
/// This string is case sensitive and terminated by a null byte.
/// </summary>
public string Name;
/// <summary>
/// A trailing zero-pad byte that appears after the trailing null byte, if necessary, to align the next entry on an even boundary.
/// </summary>
public byte Pad;
public static HintNameTableEntry Deserialize(Stream stream)
{
var hnte = new HintNameTableEntry();
hnte.Hint = stream.ReadUInt16();
hnte.Name = string.Empty;
while (true)
{
char c = stream.ReadChar();
if (c == (char)0x00)
break;
hnte.Name += c;
}
// If the name length is not even, read and pad
if (hnte.Name.Length % 2 != 0)
{
stream.ReadByte();
hnte.Pad = 1;
}
else
{
hnte.Pad = 0;
}
return hnte;
}
public static HintNameTableEntry Deserialize(byte[] content, ref int offset)
{
var hnte = new HintNameTableEntry();
hnte.Hint = content.ReadUInt16(ref offset);
hnte.Name = string.Empty;
while (true)
{
char c = (char)content[offset]; offset += 1;
if (c == (char)0x00)
break;
hnte.Name += c;
}
// If the name length is not even, read and pad
if (hnte.Name.Length % 2 != 0)
{
offset += 1;
hnte.Pad = 1;
}
else
{
hnte.Pad = 0;
}
return hnte;
}
}
}

View File

@@ -1,81 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each import address entry has the following format
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-address-table</remarks>
public class ImportAddressTableEntry
{
/// <summary>
/// The RVA of the import lookup table.
/// This table contains a name or ordinal for each import.
/// (The name "Characteristics" is used in Winnt.h, but no longer describes this field.)
/// </summary>
public uint ImportLookupTableRVA;
/// <summary>
/// The stamp that is set to zero until the image is bound.
/// After the image is bound, this field is set to the time/data stamp of the DLL.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The index of the first forwarder reference.
/// </summary>
public uint ForwarderChain;
/// <summary>
/// The address of an ASCII string that contains the name of the DLL.
/// This address is relative to the image base.
/// </summary>
public uint NameRVA;
/// <summary>
/// The RVA of the import address table.
/// The contents of this table are identical to the contents of the import lookup table until the image is bound.
/// </summary>
public uint ImportAddressTableRVA;
/// <summary>
/// Determine if the entry is null or not
/// This indicates the last entry in a table
/// </summary>
public bool IsNull()
{
return ImportLookupTableRVA == 0
&& TimeDateStamp == 0
&& ForwarderChain == 0
&& NameRVA == 0
&& ImportAddressTableRVA == 0;
}
public static ImportAddressTableEntry Deserialize(Stream stream)
{
var iate = new ImportAddressTableEntry();
iate.ImportLookupTableRVA = stream.ReadUInt32();
iate.TimeDateStamp = stream.ReadUInt32();
iate.ForwarderChain = stream.ReadUInt32();
iate.NameRVA = stream.ReadUInt32();
iate.ImportAddressTableRVA = stream.ReadUInt32();
return iate;
}
public static ImportAddressTableEntry Deserialize(byte[] content, ref int offset)
{
var iate = new ImportAddressTableEntry();
iate.ImportLookupTableRVA = content.ReadUInt32(ref offset);
iate.TimeDateStamp = content.ReadUInt32(ref offset);
iate.ForwarderChain = content.ReadUInt32(ref offset);
iate.NameRVA = content.ReadUInt32(ref offset);
iate.ImportAddressTableRVA = content.ReadUInt32(ref offset);
return iate;
}
}
}

View File

@@ -1,81 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each import directory entry has the following format
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-directory-table</remarks>
public class ImportDirectoryTableEntry
{
/// <summary>
/// The RVA of the import lookup table.
/// This table contains a name or ordinal for each import.
/// (The name "Characteristics" is used in Winnt.h, but no longer describes this field.)
/// </summary>
public uint ImportLookupTableRVA;
/// <summary>
/// The stamp that is set to zero until the image is bound.
/// After the image is bound, this field is set to the time/data stamp of the DLL.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The index of the first forwarder reference.
/// </summary>
public uint ForwarderChain;
/// <summary>
/// The address of an ASCII string that contains the name of the DLL.
/// This address is relative to the image base.
/// </summary>
public uint NameRVA;
/// <summary>
/// The RVA of the import address table.
/// The contents of this table are identical to the contents of the import lookup table until the image is bound.
/// </summary>
public uint ImportAddressTableRVA;
/// <summary>
/// Determine if the entry is null or not
/// This indicates the last entry in a table
/// </summary>
public bool IsNull()
{
return ImportLookupTableRVA == 0
&& TimeDateStamp == 0
&& ForwarderChain == 0
&& NameRVA == 0
&& ImportAddressTableRVA == 0;
}
public static ImportDirectoryTableEntry Deserialize(Stream stream)
{
var idte = new ImportDirectoryTableEntry();
idte.ImportLookupTableRVA = stream.ReadUInt32();
idte.TimeDateStamp = stream.ReadUInt32();
idte.ForwarderChain = stream.ReadUInt32();
idte.NameRVA = stream.ReadUInt32();
idte.ImportAddressTableRVA = stream.ReadUInt32();
return idte;
}
public static ImportDirectoryTableEntry Deserialize(byte[] content, ref int offset)
{
var idte = new ImportDirectoryTableEntry();
idte.ImportLookupTableRVA = content.ReadUInt32(ref offset);
idte.TimeDateStamp = content.ReadUInt32(ref offset);
idte.ForwarderChain = content.ReadUInt32(ref offset);
idte.NameRVA = content.ReadUInt32(ref offset);
idte.ImportAddressTableRVA = content.ReadUInt32(ref offset);
return idte;
}
}
}

View File

@@ -1,111 +0,0 @@
using System;
using System.IO;
using System.Linq;
using System.Text;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// Each Resource Data entry describes an actual unit of raw data in the Resource Data area.
/// </summary>
public class ResourceDataEntry
{
/// <summary>
/// The address of a unit of resource data in the Resource Data area.
/// </summary>
public uint OffsetToData;
/// <summary>
/// A unit of resource data in the Resource Data area.
/// </summary>
public byte[] Data;
/// <summary>
/// A unit of resource data in the Resource Data area.
/// </summary>
public string DataAsUTF8String
{
get
{
int codePage = (int)CodePage;
if (Data == null || codePage < 0)
return string.Empty;
// Try to convert to UTF-8 first
try
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var originalEncoding = Encoding.GetEncoding(codePage);
byte[] convertedData = Encoding.Convert(originalEncoding, Encoding.UTF8, Data);
return Encoding.UTF8.GetString(convertedData);
}
catch { }
// Then try to read direct as ASCII
try
{
return Encoding.ASCII.GetString(Data);
}
catch { }
// If both encodings fail, then just return an empty string
return string.Empty;
}
}
/// <summary>
/// The size, in bytes, of the resource data that is pointed to by the Data RVA field.
/// </summary>
public uint Size;
/// <summary>
/// The code page that is used to decode code point values within the resource data.
/// Typically, the code page would be the Unicode code page.
/// </summary>
public uint CodePage;
/// <summary>
/// Reserved, must be 0.
/// </summary>
public uint Reserved;
public static ResourceDataEntry Deserialize(Stream stream, SectionHeader[] sections)
{
var rde = new ResourceDataEntry();
rde.OffsetToData = stream.ReadUInt32();
rde.Size = stream.ReadUInt32();
rde.CodePage = stream.ReadUInt32();
rde.Reserved = stream.ReadUInt32();
int realOffsetToData = (int)PortableExecutable.ConvertVirtualAddress(rde.OffsetToData, sections);
if (realOffsetToData > -1 && realOffsetToData < stream.Length && (int)rde.Size > 0 && realOffsetToData + (int)rde.Size < stream.Length)
{
long lastPosition = stream.Position;
stream.Seek(realOffsetToData, SeekOrigin.Begin);
rde.Data = stream.ReadBytes((int)rde.Size);
stream.Seek(lastPosition, SeekOrigin.Begin);
}
return rde;
}
public static ResourceDataEntry Deserialize(byte[] content, ref int offset, SectionHeader[] sections)
{
var rde = new ResourceDataEntry();
rde.OffsetToData = content.ReadUInt32(ref offset);
rde.Size = content.ReadUInt32(ref offset);
rde.CodePage = content.ReadUInt32(ref offset);
rde.Reserved = content.ReadUInt32(ref offset);
int realOffsetToData = (int)PortableExecutable.ConvertVirtualAddress(rde.OffsetToData, sections);
if (realOffsetToData > -1 && realOffsetToData < content.Length && (int)rde.Size > 0 && realOffsetToData + (int)rde.Size < content.Length)
rde.Data = new ArraySegment<byte>(content, realOffsetToData, (int)rde.Size).ToArray();
return rde;
}
}
}

View File

@@ -1,50 +0,0 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// The resource directory string area consists of Unicode strings, which are word-aligned.
/// These strings are stored together after the last Resource Directory entry and before the first Resource Data entry.
/// This minimizes the impact of these variable-length strings on the alignment of the fixed-size directory entries.
/// </summary>
public class ResourceDirectoryString
{
/// <summary>
/// The size of the string, not including length field itself.
/// </summary>
public ushort Length;
/// <summary>
/// The variable-length Unicode string data, word-aligned.
/// </summary>
public string UnicodeString;
public static ResourceDirectoryString Deserialize(Stream stream)
{
var rds = new ResourceDirectoryString();
rds.Length = stream.ReadUInt16();
if (rds.Length + stream.Position > stream.Length)
return null;
rds.UnicodeString = new string(stream.ReadChars(rds.Length, Encoding.Unicode));
return rds;
}
public static ResourceDirectoryString Deserialize(byte[] content, ref int offset)
{
var rds = new ResourceDirectoryString();
rds.Length = content.ReadUInt16(ref offset);
if (rds.Length + offset > content.Length)
return null;
rds.UnicodeString = Encoding.Unicode.GetString(content, offset, rds.Length); offset += rds.Length;
return rds;
}
}
}

View File

@@ -1,140 +0,0 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Entries
{
/// <summary>
/// The directory entries make up the rows of a table.
/// Each resource directory entry has the following format.
/// Whether the entry is a Name or ID entry is indicated by the
/// resource directory table, which indicates how many Name and
/// ID entries follow it (remember that all the Name entries
/// precede all the ID entries for the table). All entries for
/// the table are sorted in ascending order: the Name entries
/// by case-sensitive string and the ID entries by numeric value.
/// Offsets are relative to the address in the IMAGE_DIRECTORY_ENTRY_RESOURCE DataDirectory.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#resource-directory-entries</remarks>
public class ResourceDirectoryTableEntry
{
/// <summary>
/// The offset of a string that gives the Type, Name, or Language ID entry, depending on level of table.
/// </summary>
public uint NameOffset => (uint)(IntegerId ^ (1 << 31));
/// <summary>
/// The string that gives the Type, Name, or Language ID entry, depending on level of table pointed to by NameOffset
/// </summary>
public ResourceDirectoryString Name;
/// <summary>
/// A 32-bit integer that identifies the Type, Name, or Language ID entry.
/// </summary>
public uint IntegerId;
/// <summary>
/// High bit 0. Address of a Resource Data entry (a leaf).
/// </summary>
public uint DataEntryOffset;
/// <summary>
/// High bit 1. The lower 31 bits are the address of another resource directory table (the next level down).
/// </summary>
public uint SubdirectoryOffset => (uint)(DataEntryOffset ^ (1 << 31));
/// <summary>
/// Resource Data entry (a leaf).
/// </summary>
public ResourceDataEntry DataEntry;
/// <summary>
/// Another resource directory table (the next level down).
/// </summary>
public ResourceDirectoryTable Subdirectory;
/// <summary>
/// Determine if an entry has a name or integer identifier
/// </summary>
public bool IsIntegerIDEntry() => (IntegerId & (1 << 31)) == 0;
/// <summary>
/// Determine if an entry represents a leaf or another directory table
/// </summary>
public bool IsResourceDataEntry() => (DataEntryOffset & (1 << 31)) == 0;
public static ResourceDirectoryTableEntry Deserialize(Stream stream, long sectionStart, SectionHeader[] sections)
{
var rdte = new ResourceDirectoryTableEntry();
rdte.IntegerId = stream.ReadUInt32();
if (!rdte.IsIntegerIDEntry())
{
int nameAddress = (int)(rdte.NameOffset + sectionStart);
if (nameAddress >= 0 && nameAddress < stream.Length)
{
long lastPosition = stream.Position;
stream.Seek(nameAddress, SeekOrigin.Begin);
rdte.Name = ResourceDirectoryString.Deserialize(stream);
stream.Seek(lastPosition, SeekOrigin.Begin);
}
}
rdte.DataEntryOffset = stream.ReadUInt32();
if (rdte.IsResourceDataEntry())
{
int dataEntryAddress = (int)(rdte.DataEntryOffset + sectionStart);
if (dataEntryAddress > 0 && dataEntryAddress < stream.Length)
{
long lastPosition = stream.Position;
stream.Seek(dataEntryAddress, SeekOrigin.Begin);
rdte.DataEntry = ResourceDataEntry.Deserialize(stream, sections);
stream.Seek(lastPosition, SeekOrigin.Begin);
}
}
else
{
int subdirectoryAddress = (int)(rdte.SubdirectoryOffset + sectionStart);
if (subdirectoryAddress > 0 && subdirectoryAddress < stream.Length)
{
long lastPosition = stream.Position;
stream.Seek(subdirectoryAddress, SeekOrigin.Begin);
rdte.Subdirectory = ResourceDirectoryTable.Deserialize(stream, sectionStart, sections);
stream.Seek(lastPosition, SeekOrigin.Begin);
}
}
return rdte;
}
public static ResourceDirectoryTableEntry Deserialize(byte[] content, ref int offset, long sectionStart, SectionHeader[] sections)
{
var rdte = new ResourceDirectoryTableEntry();
rdte.IntegerId = content.ReadUInt32(ref offset);
if (!rdte.IsIntegerIDEntry())
{
int nameAddress = (int)(rdte.NameOffset + sectionStart);
if (nameAddress >= 0 && nameAddress < content.Length)
rdte.Name = ResourceDirectoryString.Deserialize(content, ref nameAddress);
}
rdte.DataEntryOffset = content.ReadUInt32(ref offset);
if (rdte.IsResourceDataEntry())
{
int dataEntryAddress = (int)(rdte.DataEntryOffset + sectionStart);
if (dataEntryAddress > 0 && dataEntryAddress < content.Length)
rdte.DataEntry = ResourceDataEntry.Deserialize(content, ref dataEntryAddress, sections);
}
else
{
int subdirectoryAddress = (int)(rdte.SubdirectoryOffset + sectionStart);
if (subdirectoryAddress > 0 && subdirectoryAddress < content.Length)
rdte.Subdirectory = ResourceDirectoryTable.Deserialize(content, ref subdirectoryAddress, sectionStart, sections);
}
return rdte;
}
}
}

View File

@@ -1,88 +0,0 @@
using System;
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Headers
{
public class CommonObjectFileFormatHeader
{
/// <summary>
/// After the MS-DOS stub, at the file offset specified at offset 0x3c, is a 4-byte signature that identifies the file as a PE format image file.
// This signature is "PE\0\0" (the letters "P" and "E" followed by two null bytes).
/// </summary>
public uint Signature;
/// <summary>
/// The number that identifies the type of target machine.
/// </summary>
public MachineType Machine;
/// <summary>
/// The number of sections.
/// This indicates the size of the section table, which immediately follows the headers.
/// </summary>
public ushort NumberOfSections;
/// <summary>
/// The low 32 bits of the number of seconds since 00:00 January 1, 1970 (a C run-time time_t value), which indicates when the file was created.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The file offset of the COFF symbol table, or zero if no COFF symbol table is present.
/// This value should be zero for an image because COFF debugging information is deprecated.
/// </summary>
[Obsolete]
public uint PointerToSymbolTable;
/// <summary>
/// The number of entries in the symbol table. This data can be used to locate the string table, which immediately follows the symbol table.
/// This value should be zero for an image because COFF debugging information is deprecated.
/// </summary>
[Obsolete]
public uint NumberOfSymbols;
/// <summary>
/// The size of the optional header, which is required for executable files but not for object files.
// This value should be zero for an object file.
/// </summary>
public ushort SizeOfOptionalHeader;
/// <summary>
/// The flags that indicate the attributes of the file.
/// </summary>
public ImageObjectCharacteristics Characteristics;
public static CommonObjectFileFormatHeader Deserialize(Stream stream)
{
var ifh = new CommonObjectFileFormatHeader();
ifh.Signature = stream.ReadUInt32();
ifh.Machine = (MachineType)stream.ReadUInt16();
ifh.NumberOfSections = stream.ReadUInt16();
ifh.TimeDateStamp = stream.ReadUInt32();
ifh.PointerToSymbolTable = stream.ReadUInt32();
ifh.NumberOfSymbols = stream.ReadUInt32();
ifh.SizeOfOptionalHeader = stream.ReadUInt16();
ifh.Characteristics = (ImageObjectCharacteristics)stream.ReadUInt16();
return ifh;
}
public static CommonObjectFileFormatHeader Deserialize(byte[] content, ref int offset)
{
var ifh = new CommonObjectFileFormatHeader();
ifh.Signature = content.ReadUInt32(ref offset);
ifh.Machine = (MachineType)content.ReadUInt16(ref offset);
ifh.NumberOfSections = content.ReadUInt16(ref offset);
ifh.TimeDateStamp = content.ReadUInt32(ref offset);
ifh.PointerToSymbolTable = content.ReadUInt32(ref offset);
ifh.NumberOfSymbols = content.ReadUInt32(ref offset);
ifh.SizeOfOptionalHeader = content.ReadUInt16(ref offset);
ifh.Characteristics = (ImageObjectCharacteristics)content.ReadUInt16(ref offset);
return ifh;
}
}
}

View File

@@ -1,39 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Headers
{
public class DataDirectoryHeader
{
/// <summary>
/// The first field, VirtualAddress, is actually the RVA of the table.
/// The RVA is the address of the table relative to the base address of the image when the table is loaded.
/// </summary>
public uint VirtualAddress;
/// <summary>
/// The second field gives the size in bytes.
/// </summary>
public uint Size;
public static DataDirectoryHeader Deserialize(Stream stream)
{
var ddh = new DataDirectoryHeader();
ddh.VirtualAddress = stream.ReadUInt32();
ddh.Size = stream.ReadUInt32();
return ddh;
}
public static DataDirectoryHeader Deserialize(byte[] content, ref int offset)
{
var ddh = new DataDirectoryHeader();
ddh.VirtualAddress = content.ReadUInt32(ref offset);
ddh.Size = content.ReadUInt32(ref offset);
return ddh;
}
}
}

View File

@@ -1,369 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Headers
{
/// <summary>
/// Every image file has an optional header that provides information to the loader.
/// This header is optional in the sense that some files (specifically, object files) do not have it.
/// For image files, this header is required. An object file can have an optional header, but generally
/// this header has no function in an object file except to increase its size.
///
/// Note that the size of the optional header is not fixed.
/// The SizeOfOptionalHeader field in the COFF header must be used to validate that a probe into the file
/// for a particular data directory does not go beyond SizeOfOptionalHeader.
///
/// The NumberOfRvaAndSizes field of the optional header should also be used to ensure that no probe for
/// a particular data directory entry goes beyond the optional header.
/// In addition, it is important to validate the optional header magic number for format compatibility.
/// </summary>
public class OptionalHeader
{
#region Standard Fields
/// <summary>
/// The unsigned integer that identifies the state of the image file.
/// The most common number is 0x10B, which identifies it as a normal executable file.
/// 0x107 identifies it as a ROM image, and 0x20B identifies it as a PE32+ executable.
/// </summary>
public OptionalHeaderType Magic;
/// <summary>
/// The linker major version number.
/// </summary>
public byte MajorLinkerVersion;
/// <summary>
/// The linker minor version number.
/// </summary>
public byte MinorLinkerVersion;
/// <summary>
/// The size of the code (text) section, or the sum of all code sections if there are multiple sections.
/// </summary>
public uint SizeOfCode;
/// <summary>
/// The size of the initialized data section, or the sum of all such sections if there are multiple data sections.
/// </summary>
public uint SizeOfInitializedData;
/// <summary>
/// The size of the uninitialized data section (BSS), or the sum of all such sections if there are multiple BSS sections.
/// </summary>
public uint SizeOfUninitializedData;
/// <summary>
/// The address of the entry point relative to the image base when the executable file is loaded into memory.
/// For program images, this is the starting address.
/// For device drivers, this is the address of the initialization function.
/// An entry point is optional for DLLs.
/// When no entry point is present, this field must be zero.
/// </summary>
public uint AddressOfEntryPoint;
/// <summary>
/// The address that is relative to the image base of the beginning-of-code section when it is loaded into memory.
/// </summary>
public uint BaseOfCode;
/// <summary>
/// The address that is relative to the image base of the beginning-of-data section when it is loaded into memory.
/// </summary>
public uint BaseOfData;
#endregion
#region Windows-Specific Fields
/// <summary>
/// The preferred address of the first byte of image when loaded into memory; must be a multiple of 64 K.
/// The default for DLLs is 0x10000000.
/// The default for Windows CE EXEs is 0x00010000.
/// The default for Windows NT, Windows 2000, Windows XP, Windows 95, Windows 98, and Windows Me is 0x00400000.
/// </summary>
public uint ImageBasePE32;
/// <summary>
/// The preferred address of the first byte of image when loaded into memory; must be a multiple of 64 K.
/// The default for DLLs is 0x10000000.
/// The default for Windows CE EXEs is 0x00010000.
/// The default for Windows NT, Windows 2000, Windows XP, Windows 95, Windows 98, and Windows Me is 0x00400000.
/// </summary>
public ulong ImageBasePE32Plus;
/// <summary>
/// The alignment (in bytes) of sections when they are loaded into memory.
/// It must be greater than or equal to FileAlignment.
/// The default is the page size for the architecture.
/// </summary>
public uint SectionAlignment;
/// <summary>
/// The alignment factor (in bytes) that is used to align the raw data of sections in the image file.
/// The value should be a power of 2 between 512 and 64 K, inclusive.
/// The default is 512.
/// If the SectionAlignment is less than the architecture's page size, then FileAlignment must match SectionAlignment.
/// </summary>
public uint FileAlignment;
/// <summary>
/// The major version number of the required operating system.
/// </summary>
public ushort MajorOperatingSystemVersion;
/// <summary>
/// The minor version number of the required operating system.
/// </summary>
public ushort MinorOperatingSystemVersion;
/// <summary>
/// The major version number of the image.
/// </summary>
public ushort MajorImageVersion;
/// <summary>
/// The minor version number of the image.
/// </summary>
public ushort MinorImageVersion;
/// <summary>
/// The major version number of the subsystem.
/// </summary>
public ushort MajorSubsystemVersion;
/// <summary>
/// The minor version number of the subsystem.
/// </summary>
public ushort MinorSubsystemVersion;
/// <summary>
/// Reserved, must be zero.
/// </summary>
public uint Reserved1;
/// <summary>
/// The size (in bytes) of the image, including all headers, as the image is loaded in memory.
/// It must be a multiple of SectionAlignment.
/// </summary>
public uint SizeOfImage;
/// <summary>
/// The combined size of an MS-DOS stub, PE header, and section headers rounded up to a multiple of FileAlignment.
/// </summary>
public uint SizeOfHeaders;
/// <summary>
/// The image file checksum.
/// The algorithm for computing the checksum is incorporated into IMAGHELP.DLL.
/// The following are checked for validation at load time: all drivers, any DLL loaded at boot time, and any DLL that is loaded into a critical Windows process.
/// </summary>
public uint CheckSum;
/// <summary>
/// The subsystem that is required to run this image.
/// </summary>
public WindowsSubsystem Subsystem;
/// <summary>
/// DLL Characteristics
/// </summary>
public DllCharacteristics DllCharacteristics;
/// <summary>
/// The size of the stack to reserve.
/// Only SizeOfStackCommit is committed; the rest is made available one page at a time until the reserve size is reached.
/// </summary>
public uint SizeOfStackReservePE32;
/// <summary>
/// The size of the stack to reserve.
/// Only SizeOfStackCommit is committed; the rest is made available one page at a time until the reserve size is reached.
/// </summary>
public ulong SizeOfStackReservePE32Plus;
/// <summary>
/// The size of the stack to commit.
/// </summary>
public uint SizeOfStackCommitPE32;
/// <summary>
/// The size of the stack to commit.
/// </summary>
public ulong SizeOfStackCommitPE32Plus;
/// <summary>
/// The size of the local heap space to reserve.
/// Only SizeOfHeapCommit is committed; the rest is made available one page at a time until the reserve size is reached.
/// </summary>
public uint SizeOfHeapReservePE32;
/// <summary>
/// The size of the local heap space to reserve.
/// Only SizeOfHeapCommit is committed; the rest is made available one page at a time until the reserve size is reached.
/// </summary>
public ulong SizeOfHeapReservePE32Plus;
/// <summary>
/// The size of the local heap space to commit.
/// </summary>
public uint SizeOfHeapCommitPE32;
/// <summary>
/// The size of the local heap space to commit.
/// </summary>
public ulong SizeOfHeapCommitPE32Plus;
/// <summary>
/// Reserved, must be zero.
/// </summary>
public uint LoaderFlags;
/// <summary>
/// The number of data-directory entries in the remainder of the optional header.
/// Each describes a location and size.
/// </summary>
public uint NumberOfRvaAndSizes;
/// <summary>
/// Data-directory entries following the optional header
/// </summary>
public DataDirectoryHeader[] DataDirectories;
#endregion
public static OptionalHeader Deserialize(Stream stream)
{
var ioh = new OptionalHeader();
ioh.Magic = (OptionalHeaderType)stream.ReadUInt16();
ioh.MajorLinkerVersion = stream.ReadByteValue();
ioh.MinorLinkerVersion = stream.ReadByteValue();
ioh.SizeOfCode = stream.ReadUInt32();
ioh.SizeOfInitializedData = stream.ReadUInt32();
ioh.SizeOfUninitializedData = stream.ReadUInt32();
ioh.AddressOfEntryPoint = stream.ReadUInt32();
ioh.BaseOfCode = stream.ReadUInt32();
// Only standard PE32 has this value
if (ioh.Magic == OptionalHeaderType.PE32)
ioh.BaseOfData = stream.ReadUInt32();
// PE32+ has an 8-byte value here
if (ioh.Magic == OptionalHeaderType.PE32Plus)
ioh.ImageBasePE32Plus = stream.ReadUInt64();
else
ioh.ImageBasePE32 = stream.ReadUInt32();
ioh.SectionAlignment = stream.ReadUInt32();
ioh.FileAlignment = stream.ReadUInt32();
ioh.MajorOperatingSystemVersion = stream.ReadUInt16();
ioh.MinorOperatingSystemVersion = stream.ReadUInt16();
ioh.MajorImageVersion = stream.ReadUInt16();
ioh.MinorImageVersion = stream.ReadUInt16();
ioh.MajorSubsystemVersion = stream.ReadUInt16();
ioh.MinorSubsystemVersion = stream.ReadUInt16();
ioh.Reserved1 = stream.ReadUInt32();
ioh.SizeOfImage = stream.ReadUInt32();
ioh.SizeOfHeaders = stream.ReadUInt32();
ioh.CheckSum = stream.ReadUInt32();
ioh.Subsystem = (WindowsSubsystem)stream.ReadUInt16();
ioh.DllCharacteristics = (DllCharacteristics)stream.ReadUInt16();
// PE32+ uses 8-byte values
if (ioh.Magic == OptionalHeaderType.PE32Plus)
{
ioh.SizeOfStackReservePE32Plus = stream.ReadUInt64();
ioh.SizeOfStackCommitPE32Plus = stream.ReadUInt64();
ioh.SizeOfHeapReservePE32Plus = stream.ReadUInt64();
ioh.SizeOfHeapCommitPE32Plus = stream.ReadUInt64();
}
else
{
ioh.SizeOfStackReservePE32 = stream.ReadUInt32();
ioh.SizeOfStackCommitPE32 = stream.ReadUInt32();
ioh.SizeOfHeapReservePE32 = stream.ReadUInt32();
ioh.SizeOfHeapCommitPE32 = stream.ReadUInt32();
}
ioh.LoaderFlags = stream.ReadUInt32();
ioh.NumberOfRvaAndSizes = stream.ReadUInt32();
ioh.DataDirectories = new DataDirectoryHeader[Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
for (int i = 0; i < Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++)
{
ioh.DataDirectories[i] = DataDirectoryHeader.Deserialize(stream);
}
return ioh;
}
public static OptionalHeader Deserialize(byte[] content, ref int offset)
{
var ioh = new OptionalHeader();
ioh.Magic = (OptionalHeaderType)content.ReadUInt16(ref offset);
ioh.MajorLinkerVersion = content[offset]; offset++;
ioh.MinorLinkerVersion = content[offset]; offset++;
ioh.SizeOfCode = content.ReadUInt32(ref offset);
ioh.SizeOfInitializedData = content.ReadUInt32(ref offset);
ioh.SizeOfUninitializedData = content.ReadUInt32(ref offset);
ioh.AddressOfEntryPoint = content.ReadUInt32(ref offset);
ioh.BaseOfCode = content.ReadUInt32(ref offset);
// Only standard PE32 has this value
if (ioh.Magic == OptionalHeaderType.PE32)
ioh.BaseOfData = content.ReadUInt32(ref offset);
// PE32+ has an 8-bit value here
if (ioh.Magic == OptionalHeaderType.PE32Plus)
{
ioh.ImageBasePE32Plus = content.ReadUInt64(ref offset);
}
else
{
ioh.ImageBasePE32 = content.ReadUInt32(ref offset);
}
ioh.SectionAlignment = content.ReadUInt32(ref offset);
ioh.FileAlignment = content.ReadUInt32(ref offset);
ioh.MajorOperatingSystemVersion = content.ReadUInt16(ref offset);
ioh.MinorOperatingSystemVersion = content.ReadUInt16(ref offset);
ioh.MajorImageVersion = content.ReadUInt16(ref offset);
ioh.MinorImageVersion = content.ReadUInt16(ref offset);
ioh.MajorSubsystemVersion = content.ReadUInt16(ref offset);
ioh.MinorSubsystemVersion = content.ReadUInt16(ref offset);
ioh.Reserved1 = content.ReadUInt32(ref offset);
ioh.SizeOfImage = content.ReadUInt32(ref offset);
ioh.SizeOfHeaders = content.ReadUInt32(ref offset);
ioh.CheckSum = content.ReadUInt32(ref offset);
ioh.Subsystem = (WindowsSubsystem)content.ReadUInt16(ref offset);
ioh.DllCharacteristics = (DllCharacteristics)content.ReadUInt16(ref offset);
// PE32+ uses 8-byte values
if (ioh.Magic == OptionalHeaderType.PE32Plus)
{
ioh.SizeOfStackReservePE32Plus = content.ReadUInt64(ref offset);
ioh.SizeOfStackCommitPE32Plus = content.ReadUInt64(ref offset);
ioh.SizeOfHeapReservePE32Plus = content.ReadUInt64(ref offset);
ioh.SizeOfHeapCommitPE32Plus = content.ReadUInt64(ref offset);
}
else
{
ioh.SizeOfStackReservePE32 = content.ReadUInt32(ref offset);
ioh.SizeOfStackCommitPE32 = content.ReadUInt32(ref offset);
ioh.SizeOfHeapReservePE32 = content.ReadUInt32(ref offset);
ioh.SizeOfHeapCommitPE32 = content.ReadUInt32(ref offset);
}
ioh.LoaderFlags = content.ReadUInt32(ref offset);
ioh.NumberOfRvaAndSizes = content.ReadUInt32(ref offset);
ioh.DataDirectories = new DataDirectoryHeader[Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
for (int i = 0; i < Constants.IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++)
{
ioh.DataDirectories[i] = DataDirectoryHeader.Deserialize(content, ref offset);
}
return ioh;
}
}
}

View File

@@ -1,159 +0,0 @@
using System;
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Headers
{
/// <summary>
/// Each row of the section table is, in effect, a section header.
/// This table immediately follows the optional header, if any.
/// This positioning is required because the file header does not contain a direct pointer to the section table.
/// Instead, the location of the section table is determined by calculating the location of the first byte after the headers.
/// Make sure to use the size of the optional header as specified in the file header.
/// </summary>
public class SectionHeader
{
/// <summary>
/// An 8-byte, null-padded UTF-8 encoded string.
/// If the string is exactly 8 characters long, there is no terminating null.
/// For longer names, this field contains a slash (/) that is followed by an ASCII representation of a decimal number
/// that is an offset into the string table.
/// Executable images do not use a string table and do not support section names longer than 8 characters.
/// Long names in object files are truncated if they are emitted to an executable file.
/// </summary>
public byte[] Name;
/// <summary>
/// Section name as a string, trimming any trailing null bytes
/// </summary>
public string NameString
{
get
{
if (this.Name == null || this.Name.Length == 0)
return null;
// First try decoding as UTF-8
try
{
return Encoding.UTF8.GetString(this.Name).TrimEnd('\0');
}
catch { }
// Then try decoding as ASCII
try
{
return Encoding.ASCII.GetString(this.Name).TrimEnd('\0');
}
catch { }
// If it fails, return null
return null;
}
}
/// <summary>
/// The total size of the section when loaded into memory.
/// If this value is greater than SizeOfRawData, the section is zero-padded.
/// This field is valid only for executable images and should be set to zero for object files.
/// </summary>
public uint VirtualSize;
/// <summary>
/// For executable images, the address of the first byte of the section relative to the image base when the section
/// is loaded into memory.
/// For object files, this field is the address of the first byte before relocation is applied; for simplicity,
/// compilers should set this to zero.
/// Otherwise, it is an arbitrary value that is subtracted from offsets during relocation.
/// </summary>
public uint VirtualAddress;
/// <summary>
/// The size of the section (for object files) or the size of the initialized data on disk (for image files).
/// For executable images, this must be a multiple of FileAlignment from the optional header.
/// If this is less than VirtualSize, the remainder of the section is zero-filled.
/// Because the SizeOfRawData field is rounded but the VirtualSize field is not, it is possible for SizeOfRawData
/// to be greater than VirtualSize as well.
/// When a section contains only uninitialized data, this field should be zero.
/// </summary>
public uint SizeOfRawData;
/// <summary>
/// The file pointer to the first page of the section within the COFF file.
/// For executable images, this must be a multiple of FileAlignment from the optional header.
/// For object files, the value should be aligned on a 4-byte boundary for best performance.
/// When a section contains only uninitialized data, this field should be zero.
/// </summary>
public uint PointerToRawData;
/// <summary>
/// The file pointer to the beginning of relocation entries for the section.
/// This is set to zero for executable images or if there are no relocations.
/// </summary>
public uint PointerToRelocations;
/// <summary>
/// The file pointer to the beginning of line-number entries for the section.
/// This is set to zero if there are no COFF line numbers.
/// This value should be zero for an image because COFF debugging information is deprecated.
/// </summary>
[Obsolete]
public uint PointerToLinenumbers;
/// <summary>
/// The number of relocation entries for the section.
/// This is set to zero for executable images.
/// </summary>
public ushort NumberOfRelocations;
/// <summary>
/// The number of line-number entries for the section.
/// This value should be zero for an image because COFF debugging information is deprecated.
/// </summary>
[Obsolete]
public ushort NumberOfLinenumbers;
/// <summary>
/// The flags that describe the characteristics of the section.
/// </summary>
public SectionCharacteristics Characteristics;
public static SectionHeader Deserialize(Stream stream)
{
var ish = new SectionHeader();
ish.Name = stream.ReadBytes(Constants.IMAGE_SIZEOF_SHORT_NAME);
ish.VirtualSize = stream.ReadUInt32();
ish.VirtualAddress = stream.ReadUInt32();
ish.SizeOfRawData = stream.ReadUInt32();
ish.PointerToRawData = stream.ReadUInt32();
ish.PointerToRelocations = stream.ReadUInt32();
ish.PointerToLinenumbers = stream.ReadUInt32();
ish.NumberOfRelocations = stream.ReadUInt16();
ish.NumberOfLinenumbers = stream.ReadUInt16();
ish.Characteristics = (SectionCharacteristics)stream.ReadUInt32();
return ish;
}
public static SectionHeader Deserialize(byte[] content, ref int offset)
{
var ish = new SectionHeader();
ish.Name = new byte[Constants.IMAGE_SIZEOF_SHORT_NAME];
Array.Copy(content, offset, ish.Name, 0, Constants.IMAGE_SIZEOF_SHORT_NAME); offset += Constants.IMAGE_SIZEOF_SHORT_NAME;
ish.VirtualSize = content.ReadUInt32(ref offset);
ish.VirtualAddress = content.ReadUInt32(ref offset);
ish.SizeOfRawData = content.ReadUInt32(ref offset);
ish.PointerToRawData = content.ReadUInt32(ref offset);
ish.PointerToRelocations = content.ReadUInt32(ref offset);
ish.PointerToLinenumbers = content.ReadUInt32(ref offset);
ish.NumberOfRelocations = content.ReadUInt16(ref offset);
ish.NumberOfLinenumbers = content.ReadUInt16(ref offset);
ish.Characteristics = (SectionCharacteristics)content.ReadUInt32(ref offset);
return ish;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,46 +0,0 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// The .debug section is used in object files to contain compiler-generated debug information and in image files to contain
/// all of the debug information that is generated.
/// This section describes the packaging of debug information in object and image files.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-debug-section</remarks>
public class DebugSection
{
/// <summary>
/// Image files contain an optional debug directory that indicates what form of debug information is present and where it is.
/// This directory consists of an array of debug directory entries whose location and size are indicated in the image optional header.
/// </summary>
public DebugDirectory DebugDirectory;
public static DebugSection Deserialize(Stream stream)
{
long originalPosition = stream.Position;
var ds = new DebugSection();
ds.DebugDirectory = DebugDirectory.Deserialize(stream);
// TODO: Read in raw debug data
stream.Seek(originalPosition, SeekOrigin.Begin);
return ds;
}
public static DebugSection Deserialize(byte[] content, ref int offset)
{
int originalPosition = offset;
var ds = new DebugSection();
ds.DebugDirectory = DebugDirectory.Deserialize(content, ref offset);
// TODO: Read in raw debug data
offset = originalPosition;
return ds;
}
}
}

View File

@@ -1,19 +0,0 @@
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// The .pdata section contains an array of function table entries that are used for exception handling.
/// It is pointed to by the exception table entry in the image data directory.
/// The entries must be sorted according to the function addresses (the first field in each structure) before being emitted into the final image.
/// The target platform determines which of the three function table entry format variations described below is used.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-edata-section-image-only</remarks>
public class ExceptionHandlingSection
{
/// <summary>
/// Array of function table entries that are used for exception handling
/// </summary>
public FunctionTable FunctionTable;
}
}

View File

@@ -1,95 +0,0 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// The export data section, named .edata, contains information about symbols that other images can access through dynamic linking.
/// Exported symbols are generally found in DLLs, but DLLs can also import symbols.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-edata-section-image-only</remarks>
public class ExportDataSection
{
/// <summary>
/// A table with just one row (unlike the debug directory).
/// This table indicates the locations and sizes of the other export tables.
/// </summary>
public ExportDirectoryTable ExportDirectoryTable;
/// <summary>
/// An array of RVAs of exported symbols.
/// These are the actual addresses of the exported functions and data within the executable code and data sections.
/// Other image files can import a symbol by using an index to this table (an ordinal) or, optionally, by using the public name that corresponds to the ordinal if a public name is defined.
/// </summary>
public ExportAddressTableEntry[] ExportAddressTable;
/// <summary>
/// An array of pointers to the public export names, sorted in ascending order.
/// </summary>
public uint[] ExportNamePointerTable;
/// <summary>
/// An array of the ordinals that correspond to members of the name pointer table.
/// The correspondence is by position; therefore, the name pointer table and the ordinal table must have the same number of members.
/// Each ordinal is an index into the export address table.
/// </summary>
public ExportOrdinalTable OrdinalTable;
public static ExportDataSection Deserialize(Stream stream, SectionHeader[] sections)
{
long originalPosition = stream.Position;
var eds = new ExportDataSection();
eds.ExportDirectoryTable = ExportDirectoryTable.Deserialize(stream);
stream.Seek((int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.ExportAddressTableRVA, sections), SeekOrigin.Begin);
eds.ExportAddressTable = new ExportAddressTableEntry[(int)eds.ExportDirectoryTable.AddressTableEntries];
for (int i = 0; i < eds.ExportAddressTable.Length; i++)
{
eds.ExportAddressTable[i] = ExportAddressTableEntry.Deserialize(stream, sections);
}
stream.Seek((int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.NamePointerRVA, sections), SeekOrigin.Begin);
eds.ExportNamePointerTable = new uint[(int)eds.ExportDirectoryTable.NumberOfNamePointers];
for (int i = 0; i < eds.ExportNamePointerTable.Length; i++)
{
eds.ExportNamePointerTable[i] = stream.ReadUInt32();
}
stream.Seek((int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.OrdinalTableRVA, sections), SeekOrigin.Begin);
// eds.OrdinalTable = ExportOrdinalTable.Deserialize(stream, count: 0); // TODO: Figure out where this count comes from
return eds;
}
public static ExportDataSection Deserialize(byte[] content, ref int offset, SectionHeader[] sections)
{
int originalPosition = offset;
var eds = new ExportDataSection();
eds.ExportDirectoryTable = ExportDirectoryTable.Deserialize(content, ref offset);
offset = (int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.ExportAddressTableRVA, sections);
eds.ExportAddressTable = new ExportAddressTableEntry[(int)eds.ExportDirectoryTable.AddressTableEntries];
for (int i = 0; i < eds.ExportAddressTable.Length; i++)
{
eds.ExportAddressTable[i] = ExportAddressTableEntry.Deserialize(content, ref offset, sections);
}
offset = (int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.NamePointerRVA, sections);
eds.ExportNamePointerTable = new uint[(int)eds.ExportDirectoryTable.NumberOfNamePointers];
for (int i = 0; i < eds.ExportNamePointerTable.Length; i++)
{
eds.ExportNamePointerTable[i] = content.ReadUInt32(ref offset);
}
offset = (int)PortableExecutable.ConvertVirtualAddress(eds.ExportDirectoryTable.OrdinalTableRVA, sections);
// eds.OrdinalTable = ExportOrdinalTable.Deserialize(content, ref offset, count: 0); // TODO: Figure out where this count comes from
return eds;
}
}
}

View File

@@ -1,80 +0,0 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// All image files that import symbols, including virtually all executable (EXE) files, have an .idata section.
/// A typical file layout for the import information follows:
/// Directory Table
/// Null Directory Entry
/// DLL1 Import Lookup Table
/// Null
/// DLL2 Import Lookup Table
/// Null
/// DLL3 Import Lookup Table
/// Null
/// Hint-Name Table
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-idata-section</remarks>
public class ImportDataSection
{
/// <summary>
/// Import directory table
/// </summary>
public ImportDirectoryTable ImportDirectoryTable;
/// <summary>
/// Import lookup tables
/// </summary>
public ImportLookupTable[] ImportLookupTables;
/// <summary>
/// Hint/Name table
/// </summary>
public HintNameTable HintNameTable;
public static ImportDataSection Deserialize(Stream stream, bool pe32plus, int hintCount)
{
var ids = new ImportDataSection();
ids.ImportDirectoryTable = ImportDirectoryTable.Deserialize(stream);
List<ImportLookupTable> tempLookupTables = new List<ImportLookupTable>();
while (true)
{
var tempLookupTable = ImportLookupTable.Deserialize(stream, pe32plus);
if (tempLookupTable.EntriesPE32 == null && tempLookupTable.EntriesPE32Plus == null)
break;
tempLookupTables.Add(tempLookupTable);
}
ids.HintNameTable = HintNameTable.Deserialize(stream, hintCount);
return ids;
}
public static ImportDataSection Deserialize(byte[] content, ref int offset, bool pe32plus, int hintCount)
{
var ids = new ImportDataSection();
ids.ImportDirectoryTable = ImportDirectoryTable.Deserialize(content, ref offset);
List<ImportLookupTable> tempLookupTables = new List<ImportLookupTable>();
while (true)
{
var tempLookupTable = ImportLookupTable.Deserialize(content, ref offset, pe32plus);
if (tempLookupTable.EntriesPE32 == null && tempLookupTable.EntriesPE32Plus == null)
break;
tempLookupTables.Add(tempLookupTable);
}
ids.HintNameTable = HintNameTable.Deserialize(content, ref offset, hintCount);
return ids;
}
}
}

View File

@@ -1,51 +0,0 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// The base relocation table contains entries for all base relocations in the image.
/// The Base Relocation Table field in the optional header data directories gives the number of bytes in the base relocation table.
/// The base relocation table is divided into blocks.
/// Each block represents the base relocations for a 4K page.
/// Each block must start on a 32-bit boundary.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-reloc-section-image-only</remarks>
public class RelocationSection
{
/// <summary>
/// The base relocation table is divided into blocks.
/// </summary>
public BaseRelocationBlock[] BaseRelocationTable;
public static RelocationSection Deserialize(Stream stream, int blockCount)
{
long originalPosition = stream.Position;
var rs = new RelocationSection();
rs.BaseRelocationTable = new BaseRelocationBlock[blockCount];
for (int i = 0; i < blockCount; i++)
{
rs.BaseRelocationTable[i] = BaseRelocationBlock.Deserialize(stream);
}
stream.Seek(originalPosition, SeekOrigin.Begin);
return rs;
}
public static RelocationSection Deserialize(byte[] content, ref int offset, int blockCount)
{
int originalPosition = offset;
var rs = new RelocationSection();
rs.BaseRelocationTable = new BaseRelocationBlock[blockCount];
for (int i = 0; i < blockCount; i++)
{
rs.BaseRelocationTable[i] = BaseRelocationBlock.Deserialize(content, ref offset);
}
offset = originalPosition;
return rs;
}
}
}

View File

@@ -1,44 +0,0 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.ExecutableType.Microsoft.PE.Tables;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Sections
{
/// <summary>
/// A series of resource directory tables relates all of the levels in the following way:
// Each directory table is followed by a series of directory entries that give the name or
// identifier (ID) for that level (Type, Name, or Language level) and an address of either
// a data description or another directory table. If the address points to a data description,
// then the data is a leaf in the tree. If the address points to another directory table,
// then that table lists directory entries at the next level down
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-rsrc-section</remarks>
public class ResourceSection
{
/// <summary>
/// A table with just one row (unlike the debug directory).
/// This table indicates the locations and sizes of the other export tables.
/// </summary>
public ResourceDirectoryTable ResourceDirectoryTable;
public static ResourceSection Deserialize(Stream stream, SectionHeader[] sections)
{
var rs = new ResourceSection();
long sectionStart = stream.Position;
rs.ResourceDirectoryTable = ResourceDirectoryTable.Deserialize(stream, sectionStart, sections);
return rs;
}
public static ResourceSection Deserialize(byte[] content, ref int offset, SectionHeader[] sections)
{
var rs = new ResourceSection();
long sectionStart = offset;
rs.ResourceDirectoryTable = ResourceDirectoryTable.Deserialize(content, ref offset, sectionStart, sections);
return rs;
}
}
}

View File

@@ -1,85 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// Image files contain an optional debug directory that indicates what form of debug information is present and where it is.
/// This directory consists of an array of debug directory entries whose location and size are indicated in the image optional header.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#debug-directory-image-only</remarks>
public class DebugDirectory
{
/// <summary>
/// Reserved, must be 0.
/// </summary>
public uint Characteristics;
/// <summary>
/// The time and date that the debug data was created.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The major version number of the debug data format.
/// </summary>
public ushort MajorVersion;
/// <summary>
/// The minor version number of the debug data format.
/// </summary>
public ushort MinorVersion;
/// <summary>
/// The format of debugging information. This field enables support of multiple debuggers.
/// </summary>
public DebugType DebugType;
/// <summary>
/// The size of the debug data (not including the debug directory itself).
/// </summary>
public uint SizeOfData;
/// <summary>
/// The address of the debug data when loaded, relative to the image base.
/// </summary>
public uint AddressOfRawData;
/// <summary>
/// The file pointer to the debug data.
/// </summary>
public uint PointerToRawData;
public static DebugDirectory Deserialize(Stream stream)
{
var dd = new DebugDirectory();
dd.Characteristics = stream.ReadUInt32();
dd.TimeDateStamp = stream.ReadUInt32();
dd.MajorVersion = stream.ReadUInt16();
dd.MinorVersion = stream.ReadUInt16();
dd.DebugType = (DebugType)stream.ReadUInt32();
dd.SizeOfData = stream.ReadUInt32();
dd.AddressOfRawData = stream.ReadUInt32();
dd.PointerToRawData = stream.ReadUInt32();
return dd;
}
public static DebugDirectory Deserialize(byte[] content, ref int offset)
{
var dd = new DebugDirectory();
dd.Characteristics = content.ReadUInt32(ref offset);
dd.TimeDateStamp = content.ReadUInt32(ref offset);
dd.MajorVersion = content.ReadUInt16(ref offset);
dd.MinorVersion = content.ReadUInt16(ref offset);
dd.DebugType = (DebugType)content.ReadUInt32(ref offset);
dd.SizeOfData = content.ReadUInt32(ref offset);
dd.AddressOfRawData = content.ReadUInt32(ref offset);
dd.PointerToRawData = content.ReadUInt32(ref offset);
return dd;
}
}
}

View File

@@ -1,111 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The export symbol information begins with the export directory table, which describes the remainder of the export symbol information.
/// The export directory table contains address information that is used to resolve imports to the entry points within this image.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#export-directory-table</remarks>
public class ExportDirectoryTable
{
/// <summary>
/// Reserved, must be 0.
/// </summary>
public uint ExportFlags;
/// <summary>
/// The time and date that the export data was created.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The major version number. The major and minor version numbers can be set by the user.
/// </summary>
public ushort MajorVersion;
/// <summary>
/// The minor version number.
/// </summary>
public ushort MinorVersion;
/// <summary>
/// The address of the ASCII string that contains the name of the DLL.
/// This address is relative to the image base.
/// </summary>
public uint NameRVA; // TODO: Read this into a separate field
/// <summary>
/// The starting ordinal number for exports in this image.
/// This field specifies the starting ordinal number for the export address table.
/// It is usually set to 1.
/// </summary>
public uint OrdinalBase;
/// <summary>
/// The number of entries in the export address table.
/// </summary>
public uint AddressTableEntries;
/// <summary>
/// The number of entries in the name pointer table.
/// This is also the number of entries in the ordinal table.
/// </summary>
public uint NumberOfNamePointers;
/// <summary>
/// The address of the export address table, relative to the image base.
/// </summary>
public uint ExportAddressTableRVA;
/// <summary>
/// The address of the export name pointer table, relative to the image base.
/// The table size is given by the Number of Name Pointers field.
/// </summary>
public uint NamePointerRVA;
/// <summary>
/// The address of the ordinal table, relative to the image base.
/// </summary>
public uint OrdinalTableRVA;
public static ExportDirectoryTable Deserialize(Stream stream)
{
var edt = new ExportDirectoryTable();
edt.ExportFlags = stream.ReadUInt32();
edt.TimeDateStamp = stream.ReadUInt32();
edt.MajorVersion = stream.ReadUInt16();
edt.MinorVersion = stream.ReadUInt16();
edt.NameRVA = stream.ReadUInt32();
edt.OrdinalBase = stream.ReadUInt32();
edt.AddressTableEntries = stream.ReadUInt32();
edt.NumberOfNamePointers = stream.ReadUInt32();
edt.ExportAddressTableRVA = stream.ReadUInt32();
edt.NamePointerRVA = stream.ReadUInt32();
edt.OrdinalTableRVA = stream.ReadUInt32();
return edt;
}
public static ExportDirectoryTable Deserialize(byte[] content, ref int offset)
{
var edt = new ExportDirectoryTable();
edt.ExportFlags = content.ReadUInt32(ref offset);
edt.TimeDateStamp = content.ReadUInt32(ref offset);
edt.MajorVersion = content.ReadUInt16(ref offset);
edt.MinorVersion = content.ReadUInt16(ref offset);
edt.NameRVA = content.ReadUInt32(ref offset);
edt.OrdinalBase = content.ReadUInt32(ref offset);
edt.AddressTableEntries = content.ReadUInt32(ref offset);
edt.NumberOfNamePointers = content.ReadUInt32(ref offset);
edt.ExportAddressTableRVA = content.ReadUInt32(ref offset);
edt.NamePointerRVA = content.ReadUInt32(ref offset);
edt.OrdinalTableRVA = content.ReadUInt32(ref offset);
return edt;
}
}
}

View File

@@ -1,44 +0,0 @@
using System;
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The export ordinal table is an array of 16-bit unbiased indexes into the export address table.
/// Ordinals are biased by the Ordinal Base field of the export directory table.
/// In other words, the ordinal base must be subtracted from the ordinals to obtain true indexes into the export address table.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#export-ordinal-table</remarks>
public class ExportOrdinalTable
{
/// <remarks>Number of entries is defined externally</remarks>
public ushort[] Entries;
public static ExportOrdinalTable Deserialize(Stream stream, int count)
{
var edt = new ExportOrdinalTable();
edt.Entries = new ushort[count];
for (int i = 0; i < count; i++)
{
edt.Entries[i] = stream.ReadUInt16();
}
return edt;
}
public static ExportOrdinalTable Deserialize(byte[] content, ref int offset, int count)
{
var edt = new ExportOrdinalTable();
edt.Entries = new ushort[count];
for (int i = 0; i < count; i++)
{
edt.Entries[i] = content.ReadUInt16(ref offset);
}
return edt;
}
}
}

View File

@@ -1,17 +0,0 @@
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The .pdata section contains an array of function table entries that are used for exception handling.
/// It is pointed to by the exception table entry in the image data directory.
/// The entries must be sorted according to the function addresses (the first field in each structure) before being emitted into the final image.
/// The target platform determines which of the three function table entry format variations described below is used.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-pdata-section</remarks>
public class FunctionTable
{
/// <remarks>Number of entries is defined externally</remarks>
public FunctionTableEntry[] Entries;
}
}

View File

@@ -1,42 +0,0 @@
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// One hint/name table suffices for the entire import section.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#hintname-table</remarks>
public class HintNameTable
{
/// <remarks>Number of entries is defined externally</remarks>
public HintNameTableEntry[] Entries;
public static HintNameTable Deserialize(Stream stream, int count)
{
var hnt = new HintNameTable();
hnt.Entries = new HintNameTableEntry[count];
for (int i = 0; i < count; i++)
{
hnt.Entries[i] = HintNameTableEntry.Deserialize(stream);
}
return hnt;
}
public static HintNameTable Deserialize(byte[] content, ref int offset, int count)
{
var hnt = new HintNameTable();
hnt.Entries = new HintNameTableEntry[count];
for (int i = 0; i < count; i++)
{
hnt.Entries[i] = HintNameTableEntry.Deserialize(content, ref offset);
offset += 2 + hnt.Entries[i].Name.Length + hnt.Entries[i].Pad;
}
return hnt;
}
}
}

View File

@@ -1,53 +0,0 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The structure and content of the import address table are identical to those of the import lookup table, until the file is bound.
/// During binding, the entries in the import address table are overwritten with the 32-bit (for PE32) or 64-bit (for PE32+) addresses of the symbols that are being imported.
/// These addresses are the actual memory addresses of the symbols, although technically they are still called "virtual addresses."
/// The loader typically processes the binding.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-address-table</remarks>
public class ImportAddressTable
{
/// <remarks>Number of entries is known after parsing</remarks>
public ImportAddressTableEntry[] Entries;
public static ImportAddressTable Deserialize(Stream stream)
{
var iat = new ImportAddressTable();
List<ImportAddressTableEntry> tempEntries = new List<ImportAddressTableEntry>();
while (true)
{
var entry = ImportAddressTableEntry.Deserialize(stream);
tempEntries.Add(entry);
if (entry.IsNull())
break;
}
iat.Entries = tempEntries.ToArray();
return iat;
}
public static ImportAddressTable Deserialize(byte[] content, ref int offset)
{
var iat = new ImportAddressTable();
List<ImportAddressTableEntry> tempEntries = new List<ImportAddressTableEntry>();
while (true)
{
var entry = ImportAddressTableEntry.Deserialize(content, ref offset);
tempEntries.Add(entry);
if (entry.IsNull())
break;
}
iat.Entries = tempEntries.ToArray();
return iat;
}
}
}

View File

@@ -1,53 +0,0 @@
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// The import information begins with the import directory table, which describes the remainder of the import information.
/// The import directory table contains address information that is used to resolve fixup references to the entry points within a DLL image.
/// The import directory table consists of an array of import directory entries, one entry for each DLL to which the image refers.
/// The last directory entry is empty (filled with null values), which indicates the end of the directory table.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-directory-table</remarks>
public class ImportDirectoryTable
{
/// <remarks>Number of entries is known after parsing</remarks>
public ImportDirectoryTableEntry[] Entries;
public static ImportDirectoryTable Deserialize(Stream stream)
{
var idt = new ImportDirectoryTable();
List<ImportDirectoryTableEntry> tempEntries = new List<ImportDirectoryTableEntry>();
while (true)
{
var entry = ImportDirectoryTableEntry.Deserialize(stream);
tempEntries.Add(entry);
if (entry.IsNull())
break;
}
idt.Entries = tempEntries.ToArray();
return idt;
}
public static ImportDirectoryTable Deserialize(byte[] content, ref int offset)
{
var idt = new ImportDirectoryTable();
List<ImportDirectoryTableEntry> tempEntries = new List<ImportDirectoryTableEntry>();
while (true)
{
var entry = ImportDirectoryTableEntry.Deserialize(content, ref offset);
tempEntries.Add(entry);
if (entry.IsNull())
break;
}
idt.Entries = tempEntries.ToArray();
return idt;
}
}
}

View File

@@ -1,98 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// An import lookup table is an array of 32-bit numbers for PE32 or an array of 64-bit numbers for PE32+.
/// Each entry uses the bit-field format that is described in the following table.
/// In this format, bit 31 is the most significant bit for PE32 and bit 63 is the most significant bit for PE32+.
/// The collection of these entries describes all imports from a given DLL.
/// The last entry is set to zero (NULL) to indicate the end of the table.
/// </summary>
/// <remarks>https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-lookup-table</remarks>
public class ImportLookupTable
{
/// <remarks>Number of entries is known after parsing</remarks>
public uint[] EntriesPE32;
/// <remarks>Number of entries is known after parsing</remarks>
public ulong[] EntriesPE32Plus;
public static ImportLookupTable Deserialize(Stream stream, bool pe32plus)
{
var ilt = new ImportLookupTable();
// PE32+ has 8-byte values
if (pe32plus)
{
List<ulong> tempEntries = new List<ulong>();
while (true)
{
ulong bitfield = stream.ReadUInt64();
tempEntries.Add(bitfield);
if (bitfield == 0)
break;
}
if (tempEntries.Count > 0)
ilt.EntriesPE32Plus = tempEntries.ToArray();
}
else
{
List<uint> tempEntries = new List<uint>();
while (true)
{
uint bitfield = stream.ReadUInt32();
tempEntries.Add(bitfield);
if (bitfield == 0)
break;
}
if (tempEntries.Count > 0)
ilt.EntriesPE32 = tempEntries.ToArray();
}
return ilt;
}
public static ImportLookupTable Deserialize(byte[] content, ref int offset, bool pe32plus)
{
var ilt = new ImportLookupTable();
// PE32+ has 8-byte values
if (pe32plus)
{
List<ulong> tempEntries = new List<ulong>();
while (true)
{
ulong bitfield = content.ReadUInt64(ref offset);
tempEntries.Add(bitfield);
if (bitfield == 0)
break;
}
if (tempEntries.Count > 0)
ilt.EntriesPE32Plus = tempEntries.ToArray();
}
else
{
List<uint> tempEntries = new List<uint>();
while (true)
{
uint bitfield = content.ReadUInt32(ref offset);
tempEntries.Add(bitfield);
if (bitfield == 0)
break;
}
if (tempEntries.Count > 0)
ilt.EntriesPE32 = tempEntries.ToArray();
}
return ilt;
}
}
}

View File

@@ -1,118 +0,0 @@
using System;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE.Entries;
using BurnOutSharp.ExecutableType.Microsoft.PE.Headers;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.PE.Tables
{
/// <summary>
/// Each resource directory table has the following format.
/// This data structure should be considered the heading of a table
/// because the table actually consists of directory entries and this structure
/// </summary>
public class ResourceDirectoryTable
{
/// <summary>
/// Resource flags.
/// This field is reserved for future use.
/// It is currently set to zero.
/// </summary>
public uint Characteristics;
/// <summary>
/// The time that the resource data was created by the resource compiler.
/// </summary>
public uint TimeDateStamp;
/// <summary>
/// The major version number, set by the user.
/// </summary>
public ushort MajorVersion;
/// <summary>
/// The minor version number, set by the user.
/// </summary>
public ushort MinorVersion;
/// <summary>
/// The number of directory entries immediately following
/// the table that use strings to identify Type, Name, or
/// Language entries (depending on the level of the table).
/// </summary>
public ushort NumberOfNamedEntries;
/// <summary>
/// The number of directory entries immediately following
/// the Name entries that use numeric IDs for Type, Name,
/// or Language entries.
/// </summary>
public ushort NumberOfIdEntries;
/// <summary>
/// The directory entries immediately following
/// the table that use strings to identify Type, Name, or
/// Language entries (depending on the level of the table).
/// </summary>
public ResourceDirectoryTableEntry[] NamedEntries;
/// <summary>
/// The directory entries immediately following
/// the Name entries that use numeric IDs for Type, Name,
/// or Language entries.
/// </summary>
public ResourceDirectoryTableEntry[] IdEntries;
public static ResourceDirectoryTable Deserialize(Stream stream, long sectionStart, SectionHeader[] sections)
{
var rdt = new ResourceDirectoryTable();
rdt.Characteristics = stream.ReadUInt32();
rdt.TimeDateStamp = stream.ReadUInt32();
rdt.MajorVersion = stream.ReadUInt16();
rdt.MinorVersion = stream.ReadUInt16();
rdt.NumberOfNamedEntries = stream.ReadUInt16();
rdt.NumberOfIdEntries = stream.ReadUInt16();
rdt.NamedEntries = new ResourceDirectoryTableEntry[rdt.NumberOfNamedEntries];
for (int i = 0; i < rdt.NumberOfNamedEntries; i++)
{
rdt.NamedEntries[i] = ResourceDirectoryTableEntry.Deserialize(stream, sectionStart, sections);
}
rdt.IdEntries = new ResourceDirectoryTableEntry[rdt.NumberOfIdEntries];
for (int i = 0; i < rdt.NumberOfIdEntries; i++)
{
rdt.IdEntries[i] = ResourceDirectoryTableEntry.Deserialize(stream, sectionStart, sections);
}
return rdt;
}
public static ResourceDirectoryTable Deserialize(byte[] content, ref int offset, long sectionStart, SectionHeader[] sections)
{
var rdt = new ResourceDirectoryTable();
rdt.Characteristics = content.ReadUInt32(ref offset);
rdt.TimeDateStamp = content.ReadUInt32(ref offset);
rdt.MajorVersion = content.ReadUInt16(ref offset);
rdt.MinorVersion = content.ReadUInt16(ref offset);
rdt.NumberOfNamedEntries = content.ReadUInt16(ref offset);
rdt.NumberOfIdEntries = content.ReadUInt16(ref offset);
rdt.NamedEntries = new ResourceDirectoryTableEntry[rdt.NumberOfNamedEntries];
for (int i = 0; i < rdt.NumberOfNamedEntries; i++)
{
rdt.NamedEntries[i] = ResourceDirectoryTableEntry.Deserialize(content, ref offset, sectionStart, sections);
}
rdt.IdEntries = new ResourceDirectoryTableEntry[rdt.NumberOfIdEntries];
for (int i = 0; i < rdt.NumberOfIdEntries; i++)
{
rdt.IdEntries[i] = ResourceDirectoryTableEntry.Deserialize(content, ref offset, sectionStart, sections);
}
return rdt;
}
}
}

View File

@@ -1,147 +0,0 @@
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class FixedFileInfo
{
/// <summary>
/// Contains the value 0xFEEF04BD.
/// This is used with the szKey member of the VS_VERSIONINFO structure when searching a file for the VS_FIXEDFILEINFO structure.
/// </summary>
public uint Signature;
/// <summary>
/// The binary version number of this structure.
/// The high-order word of this member contains the major version number, and the low-order word contains the minor version number.
/// </summary>
public uint StrucVersion;
/// <summary>
/// The most significant 32 bits of the file's binary version number.
/// This member is used with dwFileVersionLS to form a 64-bit value used for numeric comparisons.
/// </summary>
public uint FileVersionMS;
/// <summary>
/// The least significant 32 bits of the file's binary version number.
/// This member is used with dwFileVersionMS to form a 64-bit value used for numeric comparisons.
/// </summary>
public uint FileVersionLS;
/// <summary>
/// The most significant 32 bits of the binary version number of the product with which this file was distributed.
/// This member is used with dwProductVersionLS to form a 64-bit value used for numeric comparisons.
/// </summary>
public uint ProductVersionMS;
/// <summary>
/// The least significant 32 bits of the binary version number of the product with which this file was distributed.
/// This member is used with dwProductVersionMS to form a 64-bit value used for numeric comparisons.
/// </summary>
public uint ProductVersionLS;
/// <summary>
/// Contains a bitmask that specifies the valid bits in dwFileFlags.
/// A bit is valid only if it was defined when the file was created.
/// </summary>
public uint FileFlagsMask;
/// <summary>
/// Contains a bitmask that specifies the Boolean attributes of the file. This member can include one or more of the following values.
/// </summary>
public FileInfoFileFlags FileFlags;
/// <summary>
/// The operating system for which this file was designed. This member can be one of the following values.
///
/// An application can combine these values to indicate that the file was designed for one operating system running on another.
/// The following dwFileOS values are examples of this, but are not a complete list.
/// </summary>
public FileInfoOS FileOS;
/// <summary>
/// The general type of file. This member can be one of the following values. All other values are reserved.
/// </summary>
public FileInfoFileType FileType;
/// <summary>
/// The function of the file. The possible values depend on the value of dwFileType.
/// For all values of dwFileType not described in the following list, dwFileSubtype is zero.
///
/// If dwFileType is VFT_DRV, dwFileSubtype can be one of the following values.
///
/// If dwFileType is VFT_FONT, dwFileSubtype can be one of the following values.
///
/// If dwFileType is VFT_VXD, dwFileSubtype contains the virtual device identifier included in the virtual device control block.
/// All dwFileSubtype values not listed here are reserved.
/// </summary>
public FileInfoFileSubtype FileSubtype;
/// <summary>
/// The most significant 32 bits of the file's 64-bit binary creation date and time stamp.
/// </summary>
public uint FileDateMS;
/// <summary>
/// The least significant 32 bits of the file's 64-bit binary creation date and time stamp.
/// </summary>
public uint FileDateLS;
public static FixedFileInfo Deserialize(Stream stream)
{
FixedFileInfo ffi = new FixedFileInfo();
ushort temp;
while ((temp = stream.ReadUInt16()) == 0x0000);
stream.Seek(-2, SeekOrigin.Current);
ffi.Signature = stream.ReadUInt32();
ffi.StrucVersion = stream.ReadUInt32();
ffi.FileVersionMS = stream.ReadUInt32();
ffi.FileVersionLS = stream.ReadUInt32();
ffi.ProductVersionMS = stream.ReadUInt32();
ffi.ProductVersionLS = stream.ReadUInt32();
ffi.FileFlagsMask = stream.ReadUInt32();
ffi.FileFlags = (FileInfoFileFlags)stream.ReadUInt32();
ffi.FileOS = (FileInfoOS)stream.ReadUInt32();
ffi.FileType = (FileInfoFileType)stream.ReadUInt32();
ffi.FileSubtype = (FileInfoFileSubtype)stream.ReadUInt32();
ffi.FileDateMS = stream.ReadUInt32();
ffi.FileDateLS = stream.ReadUInt32();
return ffi;
}
public static FixedFileInfo Deserialize(byte[] content, ref int offset)
{
FixedFileInfo ffi = new FixedFileInfo();
ushort temp;
bool padded = false;
while ((temp = content.ReadUInt16(ref offset)) == 0x0000)
{
padded = true;
}
if (padded)
offset -= 2;
ffi.Signature = content.ReadUInt32(ref offset);
ffi.StrucVersion = content.ReadUInt32(ref offset);
ffi.FileVersionMS = content.ReadUInt32(ref offset);
ffi.FileVersionLS = content.ReadUInt32(ref offset);
ffi.ProductVersionMS = content.ReadUInt32(ref offset);
ffi.ProductVersionLS = content.ReadUInt32(ref offset);
ffi.FileFlagsMask = content.ReadUInt32(ref offset);
ffi.FileFlags = (FileInfoFileFlags)content.ReadUInt32(ref offset);
ffi.FileOS = (FileInfoOS)content.ReadUInt32(ref offset);
ffi.FileType = (FileInfoFileType)content.ReadUInt32(ref offset);
ffi.FileSubtype = (FileInfoFileSubtype)content.ReadUInt32(ref offset);
ffi.FileDateMS = content.ReadUInt32(ref offset);
ffi.FileDateLS = content.ReadUInt32(ref offset);
return ffi;
}
}
}

View File

@@ -1,46 +0,0 @@
using System;
using System.IO;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
/// <summary>
/// If you use the Var structure to list the languages your application or DLL supports instead of using multiple version resources,
/// use the Value member to contain an array of DWORD values indicating the language and code page combinations supported by this file.
/// The low-order word of each DWORD must contain a Microsoft language identifier, and the high-order word must contain the IBM code page number.
/// Either high-order or low-order word can be zero, indicating that the file is language or code page independent.
/// If the Var structure is omitted, the file will be interpreted as both language and code page independent.
/// </summary>
public class LanguageCodePage
{
/// <summary>
/// The low-order word of each DWORD must contain a Microsoft language identifier
/// </summary>
public ushort MicrosoftLanguageIdentifier;
/// <summary>
/// The high-order word must contain the IBM code page number
/// </summary>
public ushort IBMCodePageNumber;
public static LanguageCodePage Deserialize(Stream stream)
{
LanguageCodePage lcp = new LanguageCodePage();
lcp.MicrosoftLanguageIdentifier = stream.ReadUInt16();
lcp.IBMCodePageNumber = stream.ReadUInt16();
return lcp;
}
public static LanguageCodePage Deserialize(byte[] content, ref int offset)
{
LanguageCodePage lcp = new LanguageCodePage();
lcp.MicrosoftLanguageIdentifier = content.ReadUInt16(ref offset);
lcp.IBMCodePageNumber = content.ReadUInt16(ref offset);
return lcp;
}
}
}

View File

@@ -1,58 +0,0 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class Resource
{
/// <summary>
/// The length, in bytes, of the resource structure.
/// This length does not include any padding that aligns any subsequent version resource data on a 32-bit boundary.
/// </summary>
public ushort Length;
/// <summary>
/// The length, in bytes, of the Value member.
/// This value is zero if there is no Value member associated with the current version structure.
/// </summary>
public ushort ValueLength;
/// <summary>
/// The type of data in the version resource.
/// This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
/// </summary>
public ushort Type;
/// <summary>
/// A Unicode string representing the key
/// </summary>
public string Key;
public static Resource Deserialize(Stream stream)
{
Resource r = new Resource();
while ((r.Length = stream.ReadUInt16()) == 0x0000);
r.ValueLength = stream.ReadUInt16();
r.Type = stream.ReadUInt16();
r.Key = stream.ReadString(Encoding.Unicode);
return r;
}
public static Resource Deserialize(byte[] content, ref int offset)
{
Resource r = new Resource();
while ((r.Length = content.ReadUInt16(ref offset)) == 0x0000);
r.ValueLength = content.ReadUInt16(ref offset);
r.Type = content.ReadUInt16(ref offset);
r.Key = content.ReadString(ref offset, Encoding.Unicode);
return r;
}
}
}

View File

@@ -1,45 +0,0 @@
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class StringFileInfo : Resource
{
/// <summary>
/// An array of one or more StringTable structures.
/// Each StringTable structure's szKey member indicates the appropriate language and code page for displaying the text in that StringTable structure.
/// </summary>
public StringTable Children;
public StringFileInfo(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key?.TrimStart('\u0001') ?? default;
}
public static new StringFileInfo Deserialize(Stream stream)
{
Resource resource = Resource.Deserialize(stream);
if (resource.Key != "StringFileInfo" && resource.Key != "\u0001StringFileInfo")
return null;
StringFileInfo sfi = new StringFileInfo(resource);
sfi.Children = StringTable.Deserialize(stream);
return sfi;
}
public static new StringFileInfo Deserialize(byte[] content, ref int offset)
{
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key != "StringFileInfo" && resource.Key != "\u0001StringFileInfo")
return null;
StringFileInfo sfi = new StringFileInfo(resource);
sfi.Children = StringTable.Deserialize(content, ref offset);
return sfi;
}
}
}

View File

@@ -1,42 +0,0 @@
using System.IO;
using System.Text;
using BurnOutSharp.Tools;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class StringStruct : Resource
{
/// <summary>
/// Typically contains a list of languages that the application or DLL supports.
/// </summary>
public string Value;
public StringStruct(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new StringStruct Deserialize(Stream stream)
{
Resource resource = Resource.Deserialize(stream);
StringStruct s = new StringStruct(resource);
stream.Seek(stream.Position % 4 == 0 ? 0 : 4 - (stream.Position % 4), SeekOrigin.Current);
s.Value = new string(stream.ReadChars(s.ValueLength));
return s;
}
public static new StringStruct Deserialize(byte[] content, ref int offset)
{
Resource resource = Resource.Deserialize(content, ref offset);
StringStruct s = new StringStruct(resource);
offset += offset % 4 == 0 ? 0 : 4 - (offset % 4);
s.Value = Encoding.Unicode.GetString(content, offset, s.ValueLength * 2); offset += s.ValueLength * 2;
return s;
}
}
}

View File

@@ -1,61 +0,0 @@
using System.Collections.Generic;
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class StringTable : Resource
{
/// <summary>
/// An array of one or more String structures.
/// </summary>
public StringStruct[] Children;
public StringTable(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new StringTable Deserialize(Stream stream)
{
long originalPosition = stream.Position;
Resource resource = Resource.Deserialize(stream);
if (resource.Key.Length != 8)
return null;
StringTable st = new StringTable(resource);
var tempValue = new List<StringStruct>();
while (stream.Position - originalPosition < st.Length)
{
tempValue.Add(StringStruct.Deserialize(stream));
}
st.Children = tempValue.ToArray();
return st;
}
public static new StringTable Deserialize(byte[] content, ref int offset)
{
int originalPosition = offset;
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key.Length != 8)
return null;
StringTable st = new StringTable(resource);
var tempValue = new List<StringStruct>();
while (offset - originalPosition < st.Length)
{
tempValue.Add(StringStruct.Deserialize(content, ref offset));
}
st.Children = tempValue.ToArray();
return st;
}
}
}

View File

@@ -1,67 +0,0 @@
using System.Collections.Generic;
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class Var : Resource
{
/// <summary>
/// An array of one or more values that are language and code page identifier pairs.
///
/// If you use the Var structure to list the languages your application or DLL supports instead of using multiple version resources,
/// use the Value member to contain an array of DWORD values indicating the language and code page combinations supported by this file.
/// The low-order word of each DWORD must contain a Microsoft language identifier, and the high-order word must contain the IBM code page number.
/// Either high-order or low-order word can be zero, indicating that the file is language or code page independent.
/// If the Var structure is omitted, the file will be interpreted as both language and code page independent.
/// </summary>
public LanguageCodePage[] Value;
public Var(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new Var Deserialize(Stream stream)
{
long originalPosition = stream.Position;
Resource resource = Resource.Deserialize(stream);
if (resource.Key != "Translation")
return null;
Var v = new Var(resource);
var tempValue = new List<LanguageCodePage>();
while (stream.Position - originalPosition < v.Length)
{
tempValue.Add(LanguageCodePage.Deserialize(stream));
}
v.Value = tempValue.ToArray();
return v;
}
public static new Var Deserialize(byte[] content, ref int offset)
{
int originalPosition = offset;
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key != "Translation")
return null;
Var v = new Var(resource);
var tempValue = new List<LanguageCodePage>();
while (offset - originalPosition < v.Length)
{
tempValue.Add(LanguageCodePage.Deserialize(content, ref offset));
}
v.Value = tempValue.ToArray();
return v;
}
}
}

View File

@@ -1,44 +0,0 @@
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class VarFileInfo : Resource
{
/// <summary>
/// Typically contains a list of languages that the application or DLL supports.
/// </summary>
public Var Children;
public VarFileInfo(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new VarFileInfo Deserialize(Stream stream)
{
Resource resource = Resource.Deserialize(stream);
if (resource.Key != "VarFileInfo")
return null;
VarFileInfo vfi = new VarFileInfo(resource);
vfi.Children = Var.Deserialize(stream);
return vfi;
}
public static new VarFileInfo Deserialize(byte[] content, ref int offset)
{
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key != "VarFileInfo")
return null;
VarFileInfo vfi = new VarFileInfo(resource);
vfi.Children = Var.Deserialize(content, ref offset);
return vfi;
}
}
}

View File

@@ -1,129 +0,0 @@
using System.IO;
namespace BurnOutSharp.ExecutableType.Microsoft.Resources
{
public class VersionInfo : Resource
{
/// <summary>
/// Arbitrary data associated with this VS_VERSIONINFO structure.
/// The wValueLength member specifies the length of this member;
/// if wValueLength is zero, this member does not exist.
/// </summary>
public FixedFileInfo Value;
/// <summary>
/// An array of zero or one StringFileInfo structures, and zero or one VarFileInfo structures
/// that are children of the current VS_VERSIONINFO structure.
/// </summary>
public StringFileInfo ChildrenStringFileInfo;
/// <summary>
/// An array of zero or one StringFileInfo structures, and zero or one VarFileInfo structures
/// that are children of the current VS_VERSIONINFO structure.
/// </summary>
public VarFileInfo ChildrenVarFileInfo;
public VersionInfo(Resource resource)
{
this.Length = resource?.Length ?? default;
this.ValueLength = resource?.ValueLength ?? default;
this.Type = resource?.Type ?? default;
this.Key = resource?.Key ?? default;
}
public static new VersionInfo Deserialize(Stream stream)
{
long originalPosition = stream.Position;
Resource resource = Resource.Deserialize(stream);
if (resource.Key != "VS_VERSION_INFO")
return null;
VersionInfo vi = new VersionInfo(resource);
if (vi.ValueLength > 0)
vi.Value = FixedFileInfo.Deserialize(stream);
if (stream.Position - originalPosition > vi.Length)
return vi;
long preChildOffset = stream.Position;
Resource firstChild = Resource.Deserialize(stream);
if (firstChild.Key == "StringFileInfo" || firstChild.Key == "\u0001StringFileInfo")
{
stream.Seek(preChildOffset, SeekOrigin.Begin);
vi.ChildrenStringFileInfo = StringFileInfo.Deserialize(stream);
}
else if (firstChild.Key == "VarFileInfo" || firstChild.Key == "\u0001VarFileInfo")
{
stream.Seek(preChildOffset, SeekOrigin.Begin);
vi.ChildrenVarFileInfo = VarFileInfo.Deserialize(stream);
}
if (stream.Position - originalPosition > vi.Length)
return vi;
preChildOffset = stream.Position;
Resource secondChild = Resource.Deserialize(stream);
if (secondChild.Key == "StringFileInfo" || secondChild.Key == "\u0001StringFileInfo")
{
stream.Seek(preChildOffset, SeekOrigin.Begin);
vi.ChildrenStringFileInfo = StringFileInfo.Deserialize(stream);
}
else if (secondChild.Key == "VarFileInfo" || secondChild.Key == "\u0001VarFileInfo")
{
stream.Seek(preChildOffset, SeekOrigin.Begin);
vi.ChildrenVarFileInfo = VarFileInfo.Deserialize(stream);
}
return vi;
}
public static new VersionInfo Deserialize(byte[] content, ref int offset)
{
int originalOffset = offset;
Resource resource = Resource.Deserialize(content, ref offset);
if (resource.Key != "VS_VERSION_INFO")
return null;
VersionInfo vi = new VersionInfo(resource);
if (vi.ValueLength > 0)
vi.Value = FixedFileInfo.Deserialize(content, ref offset);
if (offset - originalOffset > vi.Length)
return vi;
int preChildOffset = offset;
Resource firstChild = Resource.Deserialize(content, ref offset);
if (firstChild.Key == "StringFileInfo" || firstChild.Key == "\u0001StringFileInfo")
{
offset = preChildOffset;
vi.ChildrenStringFileInfo = StringFileInfo.Deserialize(content, ref offset);
}
else if (firstChild.Key == "VarFileInfo" || firstChild.Key == "\u0001VarFileInfo")
{
offset = preChildOffset;
vi.ChildrenVarFileInfo = VarFileInfo.Deserialize(content, ref offset);
}
if (offset - originalOffset > vi.Length)
return vi;
preChildOffset = offset;
Resource secondChild = Resource.Deserialize(content, ref offset);
if (secondChild.Key == "StringFileInfo" || secondChild.Key == "\u0001StringFileInfo")
{
offset = preChildOffset;
vi.ChildrenStringFileInfo = StringFileInfo.Deserialize(content, ref offset);
}
else if (secondChild.Key == "VarFileInfo" || secondChild.Key == "\u0001VarFileInfo")
{
offset = preChildOffset;
vi.ChildrenVarFileInfo = VarFileInfo.Deserialize(content, ref offset);
}
return vi;
}
}
}

View File

@@ -3,10 +3,9 @@ using System.Collections.Concurrent;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using BurnOutSharp.ExecutableType.Microsoft.NE;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Tools;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.FileType
{
@@ -86,9 +85,9 @@ namespace BurnOutSharp.FileType
// Create PortableExecutable and NewExecutable objects for use in the checks
stream.Seek(0, SeekOrigin.Begin);
PortableExecutable pex = new PortableExecutable(stream);
PortableExecutable pex = PortableExecutable.Create(stream);
stream.Seek(0, SeekOrigin.Begin);
NewExecutable nex = new NewExecutable(stream);
NewExecutable nex = NewExecutable.Create(stream);
stream.Seek(0, SeekOrigin.Begin);
// Iterate through all generic content checks
@@ -114,7 +113,7 @@ namespace BurnOutSharp.FileType
}
// If we have a NE executable, iterate through all NE content checks
if (nex?.Initialized == true)
if (nex != null)
{
Parallel.ForEach(ScanningClasses.NewExecutableCheckClasses, contentCheckClass =>
{
@@ -137,7 +136,7 @@ namespace BurnOutSharp.FileType
}
// If we have a PE executable, iterate through all PE content checks
if (pex?.Initialized == true)
if (pex != null)
{
// Print the section table for debug
if (scanner.IncludeDebug && pex.SectionTable != null)

View File

@@ -1,4 +1,4 @@
using BurnOutSharp.ExecutableType.Microsoft.LE;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.Interfaces
{

View File

@@ -1,4 +1,4 @@
using BurnOutSharp.ExecutableType.Microsoft.NE;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.Interfaces
{

View File

@@ -1,4 +1,4 @@
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.Interfaces
{

View File

@@ -1,9 +1,10 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using System.Text;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -26,20 +27,21 @@ namespace BurnOutSharp.PackerType
if (aspackSection)
return "ASPack 2.29";
// TODO: Re-enable all Entry Point checks after implementing
// Use the entry point data, if it exists
if (pex.EntryPointRaw != null)
{
var matchers = GenerateMatchers();
string match = MatchUtil.GetFirstMatch(file, pex.EntryPointRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}
// if (pex.EntryPointRaw != null)
// {
// var matchers = GenerateMatchers();
// string match = MatchUtil.GetFirstMatch(file, pex.EntryPointRaw, matchers, includeDebug);
// if (!string.IsNullOrWhiteSpace(match))
// return match;
// }
// Get the .adata* section, if it exists
var adataSection = pex.GetFirstSection(".adata", exact: false);
if (adataSection != null)
{
var adataSectionRaw = pex.ReadRawSection(adataSection.NameString);
var adataSectionRaw = pex.GetFirstSectionData(Encoding.UTF8.GetString(adataSection.Name));
if (adataSectionRaw != null)
{
var matchers = GenerateMatchers();

View File

@@ -1,9 +1,9 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -23,7 +23,7 @@ namespace BurnOutSharp.PackerType
return null;
// Get the .rdata section, if it exists
if (pex.ResourceDataSectionRaw != null)
if (pex.ContainsSection(".rdata"))
{
var matchers = new List<ContentMatchSet>
{
@@ -38,7 +38,7 @@ namespace BurnOutSharp.PackerType
}, "Caphyon Advanced Installer"),
};
return MatchUtil.GetFirstMatch(file, pex.ResourceDataSectionRaw, matchers, includeDebug);
return MatchUtil.GetFirstMatch(file, pex.GetFirstSectionData(".rdata"), matchers, includeDebug);
}
return null;

View File

@@ -2,9 +2,9 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -30,9 +30,9 @@ namespace BurnOutSharp.PackerType
return "Armadillo";
// Loop through all "extension" sections -- usually .data1 or .text1
foreach (var section in sections.Where(s => s != null && s.NameString.EndsWith("1")))
foreach (var sectionName in pex.SectionNames.Where(s => s != null && s.EndsWith("1")))
{
var sectionRaw = pex.ReadRawSection(section.NameString);
var sectionRaw = pex.GetFirstSectionData(sectionName);
if (sectionRaw != null)
{
var matchers = new List<ContentMatchSet>

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Tools;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{

View File

@@ -1,9 +1,9 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -20,8 +20,8 @@ namespace BurnOutSharp.PackerType
public string CheckPortableExecutable(string file, PortableExecutable pex, bool includeDebug)
{
// Get the sections from the executable, if possible
var stub = pex?.DOSStubHeader;
if (stub == null)
var sections = pex?.SectionTable;
if (sections == null)
return null;
var matchers = new List<ContentMatchSet>
@@ -37,7 +37,7 @@ namespace BurnOutSharp.PackerType
}, "CExe")
};
string match = MatchUtil.GetFirstMatch(file, pex.DOSStubHeader.ExecutableData, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, pex.StubExecutableData, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;

View File

@@ -1,9 +1,9 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{

View File

@@ -1,9 +1,9 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -22,8 +22,9 @@ namespace BurnOutSharp.PackerType
if (sections == null)
return null;
// Get the .data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -42,7 +43,7 @@ namespace BurnOutSharp.PackerType
}, "Gentee Installer"),
};
return MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
return MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
}
return null;

View File

@@ -4,10 +4,9 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using BurnOutSharp.ExecutableType.Microsoft.NE;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -21,13 +20,12 @@ namespace BurnOutSharp.PackerType
/// <inheritdoc/>
public string CheckNewExecutable(string file, NewExecutable nex, bool includeDebug)
{
// Get the DOS stub from the executable, if possible
var stub = nex?.DOSStubHeader;
if (stub == null)
// Check we have a valid executable
if (nex == null)
return null;
// Check for "Inno" in the reserved words
if (stub.Reserved2[4] == 0x6E49 && stub.Reserved2[5] == 0x6F6E)
if (nex.Stub_Reserved2[4] == 0x6E49 && nex.Stub_Reserved2[5] == 0x6F6E)
{
string version = GetOldVersion(file, nex);
if (!string.IsNullOrWhiteSpace(version))
@@ -46,9 +44,10 @@ namespace BurnOutSharp.PackerType
var sections = pex?.SectionTable;
if (sections == null)
return null;
// Get the DATA/.data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -61,7 +60,7 @@ namespace BurnOutSharp.PackerType
}, GetVersion, "Inno Setup"),
};
string match = MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}
@@ -102,7 +101,7 @@ namespace BurnOutSharp.PackerType
string version = Encoding.ASCII.GetString(onlyVersion);
if (unicodeBytes.SequenceEqual(new byte[] { 0x28, 0x75, 0x29 }))
return (version + " (Unicode)");
return version + " (Unicode)";
return version;
}

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Tools;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{

View File

@@ -1,9 +1,9 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -23,8 +23,9 @@ namespace BurnOutSharp.PackerType
if (sections == null)
return null;
// Get the DATA/.data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -32,7 +33,7 @@ namespace BurnOutSharp.PackerType
new ContentMatchSet(new byte?[] { 0x56, 0x69, 0x73, 0x65, 0x4D, 0x61, 0x69, 0x6E }, "Installer VISE"),
};
return MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
return MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
}
return null;

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Tools;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -22,17 +22,15 @@ namespace BurnOutSharp.PackerType
return null;
string name = pex.FileDescription;
if (!string.IsNullOrWhiteSpace(name)
&& (name.Equals("Intel(R) Installation Framework", StringComparison.OrdinalIgnoreCase)
|| name.Equals("Intel Installation Framework", StringComparison.OrdinalIgnoreCase)))
if (name?.Equals("Intel(R) Installation Framework", StringComparison.OrdinalIgnoreCase) == true
|| name?.Equals("Intel Installation Framework", StringComparison.OrdinalIgnoreCase) == true)
{
return $"Intel Installation Framework {Utilities.GetInternalVersion(pex)}";
}
name = pex.ProductName;
if (!string.IsNullOrWhiteSpace(name)
&& (name.Equals("Intel(R) Installation Framework", StringComparison.OrdinalIgnoreCase)
|| name.Equals("Intel Installation Framework", StringComparison.OrdinalIgnoreCase)))
if (name.Equals("Intel(R) Installation Framework", StringComparison.OrdinalIgnoreCase) == true
|| name.Equals("Intel Installation Framework", StringComparison.OrdinalIgnoreCase) == true)
{
return $"Intel Installation Framework {Utilities.GetInternalVersion(pex)}";
}

View File

@@ -2,10 +2,10 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Tools;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -28,12 +28,13 @@ namespace BurnOutSharp.PackerType
if (name?.Equals("Wextract", StringComparison.OrdinalIgnoreCase) == true)
return $"Microsoft CAB SFX {GetVersion(pex)}";
name = pex.OriginalFileName;
name = pex.OriginalFilename;
if (name?.Equals("WEXTRACT.EXE", StringComparison.OrdinalIgnoreCase) == true)
return $"Microsoft CAB SFX {GetVersion(pex)}";
// Get the .data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -45,13 +46,13 @@ namespace BurnOutSharp.PackerType
}, "Microsoft CAB SFX"),
};
string match = MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return $"Microsoft CAB SFX {GetVersion(pex)}";
}
// Get the .text section, if it exists
if (pex.TextSectionRaw != null)
if (pex.ContainsSection(".text"))
{
var matchers = new List<ContentMatchSet>
{
@@ -61,7 +62,7 @@ namespace BurnOutSharp.PackerType
new ContentMatchSet(new byte?[] { 0x4D, 0x53, 0x43, 0x46, 0x75 }, "Microsoft CAB SFX"),
};
string match = MatchUtil.GetFirstMatch(file, pex.TextSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, pex.GetFirstSectionData(".text"), matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return $"Microsoft CAB SFX {GetVersion(pex)}";
}

View File

@@ -1,9 +1,9 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -21,12 +21,13 @@ namespace BurnOutSharp.PackerType
if (sections == null)
return null;
string description = pex.ManifestDescription;
string description = pex.AssemblyDescription;
if (!string.IsNullOrWhiteSpace(description) && description.StartsWith("Nullsoft Install System"))
return $"NSIS {description.Substring("Nullsoft Install System".Length).Trim()}";
// Get the .data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -38,7 +39,7 @@ namespace BurnOutSharp.PackerType
}, "NSIS"),
};
string match = MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}

View File

@@ -1,7 +1,7 @@
using System.Collections.Concurrent;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -21,7 +21,7 @@ namespace BurnOutSharp.PackerType
return null;
// 0x4F434550 is "PECO"
if (pex.ImageFileHeader.PointerToSymbolTable == 0x4F434550)
if (pex.PointerToSymbolTable == 0x4F434550)
return "PE Compact v1.x";
// TODO: Get more granular version detection. PiD is somehow able to detect version ranges based

View File

@@ -1,7 +1,7 @@
using System.Collections.Concurrent;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -21,8 +21,8 @@ namespace BurnOutSharp.PackerType
return null;
// Get the .petite section, if it exists -- TODO: Is there a version number that can be found?
bool nicodeSection = pex.ContainsSection(".petite", exact: true);
if (nicodeSection)
bool petiteSection = pex.ContainsSection(".petite", exact: true);
if (petiteSection)
return "PEtite";
return null;

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Tools;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{

View File

@@ -1,7 +1,7 @@
using System.Collections.Concurrent;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{

View File

@@ -2,9 +2,9 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -116,7 +116,7 @@ namespace BurnOutSharp.PackerType
return null;
// This subtract is needed because the version is before the section
return pex.ReadRawSection($"{sectionPrefix}0", first: true, offset: -128);
return pex.GetFirstSectionDataWithOffset($"{sectionPrefix}0", offset: -128);
}
}
}

View File

@@ -2,10 +2,10 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Tools;
using BurnOutSharp.Wrappers;
using SharpCompress.Archives;
using SharpCompress.Archives.Rar;
@@ -24,8 +24,9 @@ namespace BurnOutSharp.PackerType
if (sections == null)
return null;
// Get the .data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -38,7 +39,7 @@ namespace BurnOutSharp.PackerType
}, "WinRAR SFX"),
};
string match = MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}

File diff suppressed because it is too large Load Diff

View File

@@ -2,11 +2,10 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.NE;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Tools;
using BurnOutSharp.Wrappers;
using Wise = WiseUnpacker.WiseUnpacker;
namespace BurnOutSharp.PackerType
@@ -20,9 +19,8 @@ namespace BurnOutSharp.PackerType
/// <inheritdoc/>
public string CheckNewExecutable(string file, NewExecutable nex, bool includeDebug)
{
// Get the DOS stub from the executable, if possible
var stub = nex?.DOSStubHeader;
if (stub == null)
/// Check we have a valid executable
if (nex == null)
return null;
// TODO: Don't read entire file
@@ -49,8 +47,9 @@ namespace BurnOutSharp.PackerType
if (sections == null)
return null;
// Get the .data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -58,13 +57,13 @@ namespace BurnOutSharp.PackerType
new ContentMatchSet(new byte?[] { 0x57, 0x69, 0x73, 0x65, 0x4D, 0x61, 0x69, 0x6E }, "Wise Installation Wizard Module"),
};
string match = MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}
// Get the .rdata section, if it exists
if (pex.ResourceDataSectionRaw != null)
if (pex.ContainsSection(".rdata"))
{
var matchers = new List<ContentMatchSet>
{
@@ -72,7 +71,7 @@ namespace BurnOutSharp.PackerType
new ContentMatchSet(new byte?[] { 0x57, 0x69, 0x73, 0x65, 0x4D, 0x61, 0x69, 0x6E }, "Wise Installation Wizard Module"),
};
string match = MatchUtil.GetFirstMatch(file, pex.ResourceDataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, pex.GetFirstSectionData(".rdata"), matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}

View File

@@ -1,9 +1,9 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.PackerType
{
@@ -22,7 +22,7 @@ namespace BurnOutSharp.PackerType
return null;
// Get the .text section, if it exists
if (pex.TextSectionRaw != null)
if (pex.ContainsSection(".text"))
{
var matchers = new List<ContentMatchSet>
{
@@ -35,7 +35,7 @@ namespace BurnOutSharp.PackerType
}, "dotFuscator"),
};
string match = MatchUtil.GetFirstMatch(file, pex.TextSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, pex.GetFirstSectionData(".text"), matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{
@@ -39,134 +39,135 @@ namespace BurnOutSharp.ProtectionType
if (sections == null)
return null;
// TODO: Re-enable all Entry Point checks after implementing
// Get the entry point data, if it exists
if (pex.EntryPointRaw != null)
{
var matchers = new List<ContentMatchSet>
{
// Checks sourced from https://raw.githubusercontent.com/wolfram77web/app-peid/master/userdb.txt
new ContentMatchSet(new byte?[]
{
0x79, 0x11, 0x7F, 0xAB, 0x9A, 0x4A, 0x83, 0xB5,
0xC9, 0x6B, 0x1A, 0x48, 0xF9, 0x27, 0xB4, 0x25,
}, "ActiveMARK"),
// if (pex.EntryPointRaw != null)
// {
// var matchers = new List<ContentMatchSet>
// {
// // Checks sourced from https://raw.githubusercontent.com/wolfram77web/app-peid/master/userdb.txt
// new ContentMatchSet(new byte?[]
// {
// 0x79, 0x11, 0x7F, 0xAB, 0x9A, 0x4A, 0x83, 0xB5,
// 0xC9, 0x6B, 0x1A, 0x48, 0xF9, 0x27, 0xB4, 0x25,
// }, "ActiveMARK"),
new ContentMatchSet(new byte?[]
{
0x20, 0x2D, 0x2D, 0x4D, 0x50, 0x52, 0x4D, 0x4D,
0x47, 0x56, 0x41, 0x2D, 0x2D, 0x00, 0x75, 0x73,
0x65, 0x72, 0x33, 0x32, 0x2E, 0x64, 0x6C, 0x6C,
0x00, 0x4D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
0x42, 0x6F, 0x78, 0x41, 0x00, 0x54, 0x68, 0x69,
0x73, 0x20, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63,
0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x63, 0x61,
0x6E, 0x6E, 0x6F, 0x74, 0x20, 0x72, 0x75, 0x6E,
0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x6E,
0x20, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x20,
0x64, 0x65, 0x62, 0x75, 0x67,
}, "ActiveMARK 5.x -> Trymedia Systems Inc. (h)"),
// new ContentMatchSet(new byte?[]
// {
// 0x20, 0x2D, 0x2D, 0x4D, 0x50, 0x52, 0x4D, 0x4D,
// 0x47, 0x56, 0x41, 0x2D, 0x2D, 0x00, 0x75, 0x73,
// 0x65, 0x72, 0x33, 0x32, 0x2E, 0x64, 0x6C, 0x6C,
// 0x00, 0x4D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
// 0x42, 0x6F, 0x78, 0x41, 0x00, 0x54, 0x68, 0x69,
// 0x73, 0x20, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63,
// 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x63, 0x61,
// 0x6E, 0x6E, 0x6F, 0x74, 0x20, 0x72, 0x75, 0x6E,
// 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x6E,
// 0x20, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x20,
// 0x64, 0x65, 0x62, 0x75, 0x67,
// }, "ActiveMARK 5.x -> Trymedia Systems Inc. (h)"),
new ContentMatchSet(new byte?[]
{
0x20, 0x2D, 0x2D, 0x4D, 0x50, 0x52, 0x4D, 0x4D,
0x47, 0x56, 0x41, 0x2D, 0x2D, 0x00, 0x75, 0x73,
0x65, 0x72, 0x33, 0x32, 0x2E, 0x64, 0x6C, 0x6C,
0x00, 0x4D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
0x42, 0x6F, 0x78, 0x41, 0x00, 0x54, 0x68, 0x69,
0x73, 0x20, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63,
0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x63, 0x61,
0x6E, 0x6E, 0x6F, 0x74, 0x20, 0x72, 0x75, 0x6E,
0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x6E,
0x20, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x20,
0x64, 0x65, 0x62, 0x75, 0x67, 0x67, 0x65, 0x72,
0x20, 0x69, 0x6E, 0x20, 0x6D, 0x65, 0x6D, 0x6F,
0x72, 0x79, 0x2E, 0x0D, 0x0A, 0x50, 0x6C, 0x65,
0x61, 0x73, 0x65, 0x20, 0x75, 0x6E, 0x6C, 0x6F,
0x61, 0x64, 0x20, 0x74, 0x68, 0x65, 0x20, 0x64,
0x65, 0x62, 0x75, 0x67, 0x67, 0x65, 0x72, 0x20,
0x61, 0x6E, 0x64, 0x20, 0x72, 0x65, 0x73, 0x74,
0x61, 0x72, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20,
0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74,
0x69, 0x6F, 0x6E, 0x2E, 0x00, 0x57, 0x61, 0x72,
0x6E, 0x69, 0x6E, 0x67,
}, "ActiveMARK 5.x -> Trymedia Systems,Inc."),
// new ContentMatchSet(new byte?[]
// {
// 0x20, 0x2D, 0x2D, 0x4D, 0x50, 0x52, 0x4D, 0x4D,
// 0x47, 0x56, 0x41, 0x2D, 0x2D, 0x00, 0x75, 0x73,
// 0x65, 0x72, 0x33, 0x32, 0x2E, 0x64, 0x6C, 0x6C,
// 0x00, 0x4D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
// 0x42, 0x6F, 0x78, 0x41, 0x00, 0x54, 0x68, 0x69,
// 0x73, 0x20, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63,
// 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x63, 0x61,
// 0x6E, 0x6E, 0x6F, 0x74, 0x20, 0x72, 0x75, 0x6E,
// 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x6E,
// 0x20, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x20,
// 0x64, 0x65, 0x62, 0x75, 0x67, 0x67, 0x65, 0x72,
// 0x20, 0x69, 0x6E, 0x20, 0x6D, 0x65, 0x6D, 0x6F,
// 0x72, 0x79, 0x2E, 0x0D, 0x0A, 0x50, 0x6C, 0x65,
// 0x61, 0x73, 0x65, 0x20, 0x75, 0x6E, 0x6C, 0x6F,
// 0x61, 0x64, 0x20, 0x74, 0x68, 0x65, 0x20, 0x64,
// 0x65, 0x62, 0x75, 0x67, 0x67, 0x65, 0x72, 0x20,
// 0x61, 0x6E, 0x64, 0x20, 0x72, 0x65, 0x73, 0x74,
// 0x61, 0x72, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20,
// 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74,
// 0x69, 0x6F, 0x6E, 0x2E, 0x00, 0x57, 0x61, 0x72,
// 0x6E, 0x69, 0x6E, 0x67,
// }, "ActiveMARK 5.x -> Trymedia Systems,Inc."),
new ContentMatchSet(new byte?[]
{
0xBE, 0x48, 0x01, 0x40, 0x00, 0xAD, 0x8B, 0xF8,
0x95, 0xA5, 0x33, 0xC0, 0x33, 0xC9, 0xAB, 0x48,
0xAB, 0xF7, 0xD8, 0xB1, 0x04, 0xF3, 0xAB, 0xC1,
0xE0, 0x0A, 0xB5, 0x1C, 0xF3, 0xAB, 0xAD, 0x50,
0x97, 0x51, 0xAD, 0x87, 0xF5, 0x58, 0x8D, 0x54,
0x86, 0x5C, 0xFF, 0xD5, 0x72, 0x5A, 0x2C, 0x03,
0x73, 0x02, 0xB0, 0x00, 0x3C, 0x07, 0x72, 0x02,
0x2C, 0x03, 0x50, 0x0F, 0xB6, 0x5F, 0xFF, 0xC1,
0xE3, 0x03, 0xB3, 0x00, 0x8D, 0x1C, 0x5B, 0x8D,
0x9C, 0x9E, 0x0C, 0x10, 0x00, 0x00, 0xB0, 0x01,
0x67, 0xE3, 0x29, 0x8B, 0xD7, 0x2B, 0x56, 0x0C,
0x8A, 0x2A, 0x33, 0xD2, 0x84, 0xE9, 0x0F, 0x95,
0xC6, 0x52, 0xFE, 0xC6, 0x8A, 0xD0, 0x8D, 0x14,
0x93, 0xFF, 0xD5, 0x5A, 0x9F, 0x12, 0xC0, 0xD0,
0xE9, 0x74, 0x0E, 0x9E, 0x1A, 0xF2, 0x74, 0xE4,
0xB4, 0x00, 0x33, 0xC9, 0xB5, 0x01, 0xFF, 0x55,
0xCC, 0x33, 0xC9, 0xE9, 0xDF, 0x00, 0x00, 0x00,
0x8B, 0x5E, 0x0C, 0x83, 0xC2, 0x30, 0xFF, 0xD5,
0x73, 0x50, 0x83, 0xC2, 0x30, 0xFF, 0xD5, 0x72,
0x1B, 0x83, 0xC2, 0x30, 0xFF, 0xD5, 0x72, 0x2B,
0x3C, 0x07, 0xB0, 0x09, 0x72, 0x02, 0xB0, 0x0B,
0x50, 0x8B, 0xC7, 0x2B, 0x46, 0x0C, 0xB1, 0x80,
0x8A, 0x00, 0xEB, 0xCF, 0x83, 0xC2, 0x60, 0xFF,
0xD5, 0x87, 0x5E, 0x10, 0x73, 0x0D, 0x83, 0xC2,
0x30, 0xFF, 0xD5, 0x87, 0x5E, 0x14, 0x73, 0x03,
0x87, 0x5E, 0x18, 0x3C, 0x07, 0xB0, 0x08, 0x72,
0x02, 0xB0, 0x0B, 0x50, 0x53, 0x8D, 0x96, 0x7C,
0x07, 0x00, 0x00, 0xFF, 0x55, 0xD0, 0x5B, 0x91,
0xEB, 0x77, 0x3C, 0x07, 0xB0, 0x07, 0x72, 0x02,
0xB0, 0x0A, 0x50, 0x87, 0x5E, 0x10, 0x87, 0x5E,
0x14, 0x89, 0x5E, 0x18, 0x8D, 0x96, 0xC4, 0x0B,
0x00, 0x00, 0xFF, 0x55, 0xD0, 0x50, 0x48,
}, "ActiveMARK 5.x -> Trymedia Systems,Inc. (h)"),
// new ContentMatchSet(new byte?[]
// {
// 0xBE, 0x48, 0x01, 0x40, 0x00, 0xAD, 0x8B, 0xF8,
// 0x95, 0xA5, 0x33, 0xC0, 0x33, 0xC9, 0xAB, 0x48,
// 0xAB, 0xF7, 0xD8, 0xB1, 0x04, 0xF3, 0xAB, 0xC1,
// 0xE0, 0x0A, 0xB5, 0x1C, 0xF3, 0xAB, 0xAD, 0x50,
// 0x97, 0x51, 0xAD, 0x87, 0xF5, 0x58, 0x8D, 0x54,
// 0x86, 0x5C, 0xFF, 0xD5, 0x72, 0x5A, 0x2C, 0x03,
// 0x73, 0x02, 0xB0, 0x00, 0x3C, 0x07, 0x72, 0x02,
// 0x2C, 0x03, 0x50, 0x0F, 0xB6, 0x5F, 0xFF, 0xC1,
// 0xE3, 0x03, 0xB3, 0x00, 0x8D, 0x1C, 0x5B, 0x8D,
// 0x9C, 0x9E, 0x0C, 0x10, 0x00, 0x00, 0xB0, 0x01,
// 0x67, 0xE3, 0x29, 0x8B, 0xD7, 0x2B, 0x56, 0x0C,
// 0x8A, 0x2A, 0x33, 0xD2, 0x84, 0xE9, 0x0F, 0x95,
// 0xC6, 0x52, 0xFE, 0xC6, 0x8A, 0xD0, 0x8D, 0x14,
// 0x93, 0xFF, 0xD5, 0x5A, 0x9F, 0x12, 0xC0, 0xD0,
// 0xE9, 0x74, 0x0E, 0x9E, 0x1A, 0xF2, 0x74, 0xE4,
// 0xB4, 0x00, 0x33, 0xC9, 0xB5, 0x01, 0xFF, 0x55,
// 0xCC, 0x33, 0xC9, 0xE9, 0xDF, 0x00, 0x00, 0x00,
// 0x8B, 0x5E, 0x0C, 0x83, 0xC2, 0x30, 0xFF, 0xD5,
// 0x73, 0x50, 0x83, 0xC2, 0x30, 0xFF, 0xD5, 0x72,
// 0x1B, 0x83, 0xC2, 0x30, 0xFF, 0xD5, 0x72, 0x2B,
// 0x3C, 0x07, 0xB0, 0x09, 0x72, 0x02, 0xB0, 0x0B,
// 0x50, 0x8B, 0xC7, 0x2B, 0x46, 0x0C, 0xB1, 0x80,
// 0x8A, 0x00, 0xEB, 0xCF, 0x83, 0xC2, 0x60, 0xFF,
// 0xD5, 0x87, 0x5E, 0x10, 0x73, 0x0D, 0x83, 0xC2,
// 0x30, 0xFF, 0xD5, 0x87, 0x5E, 0x14, 0x73, 0x03,
// 0x87, 0x5E, 0x18, 0x3C, 0x07, 0xB0, 0x08, 0x72,
// 0x02, 0xB0, 0x0B, 0x50, 0x53, 0x8D, 0x96, 0x7C,
// 0x07, 0x00, 0x00, 0xFF, 0x55, 0xD0, 0x5B, 0x91,
// 0xEB, 0x77, 0x3C, 0x07, 0xB0, 0x07, 0x72, 0x02,
// 0xB0, 0x0A, 0x50, 0x87, 0x5E, 0x10, 0x87, 0x5E,
// 0x14, 0x89, 0x5E, 0x18, 0x8D, 0x96, 0xC4, 0x0B,
// 0x00, 0x00, 0xFF, 0x55, 0xD0, 0x50, 0x48,
// }, "ActiveMARK 5.x -> Trymedia Systems,Inc. (h)"),
new ContentMatchSet(new byte?[]
{
0x79, 0x07, 0x0F, 0xB7, 0x07, 0x47, 0x50, 0x47,
0xB9, 0x57, 0x48, 0xF2, 0xAE, 0x55, 0xFF, 0x96,
0x84, null, 0x00, 0x00, 0x09, 0xC0, 0x74, 0x07,
0x89, 0x03, 0x83, 0xC3, 0x04, 0xEB, 0xD8, 0xFF,
0x96, 0x88, null, 0x00, 0x00, 0x61, 0xE9, null,
null, null, 0xFF,
}, "ActiveMARK R5.31.1140 -> Trymedia"),
// new ContentMatchSet(new byte?[]
// {
// 0x79, 0x07, 0x0F, 0xB7, 0x07, 0x47, 0x50, 0x47,
// 0xB9, 0x57, 0x48, 0xF2, 0xAE, 0x55, 0xFF, 0x96,
// 0x84, null, 0x00, 0x00, 0x09, 0xC0, 0x74, 0x07,
// 0x89, 0x03, 0x83, 0xC3, 0x04, 0xEB, 0xD8, 0xFF,
// 0x96, 0x88, null, 0x00, 0x00, 0x61, 0xE9, null,
// null, null, 0xFF,
// }, "ActiveMARK R5.31.1140 -> Trymedia"),
new ContentMatchSet(new byte?[]
{
0x89, 0x25, null, null, null, null, null, null,
null, null, 0xEB,
}, "ActiveMark -> Trymedia Systems Inc."),
// new ContentMatchSet(new byte?[]
// {
// 0x89, 0x25, null, null, null, null, null, null,
// null, null, 0xEB,
// }, "ActiveMark -> Trymedia Systems Inc."),
new ContentMatchSet(new byte?[]
{
0x89, 0x25, null, null, null, null, 0x33, 0xED,
0x55, 0x8B, 0xEC, 0xE8, null, null, null, null,
0x8B, 0xD0, 0x81, 0xE2, 0xFF, 0x00, 0x00, 0x00,
0x89, 0x15, null, null, null, null, 0x8B, 0xD0,
0xC1, 0xEA, 0x08, 0x81, 0xE2, 0xFF, 0x00, 0x00,
0x00, 0xA3, null, null, null, null, 0xD1, 0xE0,
0x0F, 0x93, 0xC3, 0x33, 0xC0, 0x8A, 0xC3, 0xA3,
null, null, null, null, 0x68, 0xFF, 0x00, 0x00,
0x00, 0xE8, null, null, null, null, 0x6A, 0x00,
0xE8, null, null, null, null, 0xA3, null, null,
null, null, 0xBB, null, null, null, null, 0xC7,
0x03, 0x44, 0x00, 0x00, 0x00,
}, "ActiveMark -> Trymedia Systems Inc."),
};
// new ContentMatchSet(new byte?[]
// {
// 0x89, 0x25, null, null, null, null, 0x33, 0xED,
// 0x55, 0x8B, 0xEC, 0xE8, null, null, null, null,
// 0x8B, 0xD0, 0x81, 0xE2, 0xFF, 0x00, 0x00, 0x00,
// 0x89, 0x15, null, null, null, null, 0x8B, 0xD0,
// 0xC1, 0xEA, 0x08, 0x81, 0xE2, 0xFF, 0x00, 0x00,
// 0x00, 0xA3, null, null, null, null, 0xD1, 0xE0,
// 0x0F, 0x93, 0xC3, 0x33, 0xC0, 0x8A, 0xC3, 0xA3,
// null, null, null, null, 0x68, 0xFF, 0x00, 0x00,
// 0x00, 0xE8, null, null, null, null, 0x6A, 0x00,
// 0xE8, null, null, null, null, 0xA3, null, null,
// null, null, 0xBB, null, null, null, null, 0xC7,
// 0x03, 0x44, 0x00, 0x00, 0x00,
// }, "ActiveMark -> Trymedia Systems Inc."),
// };
string match = MatchUtil.GetFirstMatch(file, pex.EntryPointRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}
// string match = MatchUtil.GetFirstMatch(file, pex.EntryPointRaw, matchers, includeDebug);
// if (!string.IsNullOrWhiteSpace(match))
// return match;
// }
// Get the overlay data, if it exists
if (pex.OverlayRaw != null)
if (pex.Overlay != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -174,13 +175,13 @@ namespace BurnOutSharp.ProtectionType
new ContentMatchSet(new byte?[] { 0x00, 0x54, 0x4D, 0x53, 0x41, 0x4D, 0x56, 0x4F, 0x48, }, "ActiveMARK"),
};
string match = MatchUtil.GetFirstMatch(file, pex.OverlayRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, pex.Overlay, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}
// Get the last .bss section, if it exists
var bssSectionRaw = pex.ReadRawSection(".bss", first: false);
var bssSectionRaw = pex.GetLastSectionData(".bss");
if (bssSectionRaw != null)
{
var matchers = new List<ContentMatchSet>

View File

@@ -1,8 +1,8 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{
@@ -33,8 +33,9 @@ namespace BurnOutSharp.ProtectionType
// "Asc005.dll" has the Product Name "OrderWizard Dynamic Link Library".
// "Asc006.exe" has the Product Name "AGENT Application".
// Get the .data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -47,7 +48,7 @@ namespace BurnOutSharp.ProtectionType
}, "AegiSoft License Manager"),
};
string match = MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{
@@ -54,8 +54,9 @@ namespace BurnOutSharp.ProtectionType
if (sections == null)
return null;
// Get the .data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -68,13 +69,13 @@ namespace BurnOutSharp.ProtectionType
new ContentMatchSet(new byte?[] { 0x53, 0x45, 0x54, 0x54, 0x45, 0x43, 0x30, 0x30, 0x30, 0x30 }, "Alpha-ROM"),
};
string match = MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}
// Get the .rdata section, if it exists
if (pex.ResourceDataSectionRaw != null)
if (pex.ContainsSection(".rdata"))
{
var matchers = new List<ContentMatchSet>
{
@@ -112,13 +113,13 @@ namespace BurnOutSharp.ProtectionType
}, "Alpha-ROM"),
};
string match = MatchUtil.GetFirstMatch(file, pex.ResourceDataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, pex.GetFirstSectionData(".rdata"), matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}
// Get the overlay data, if it exists
if (pex.OverlayRaw != null)
if (pex.Overlay != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -127,7 +128,7 @@ namespace BurnOutSharp.ProtectionType
new ContentMatchSet(new byte?[] { 0x53, 0x45, 0x54, 0x54, 0x45, 0x43, 0x30, 0x30, 0x30, 0x30 }, "Alpha-ROM"),
};
string match = MatchUtil.GetFirstMatch(file, pex.OverlayRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, pex.Overlay, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{
@@ -16,7 +16,7 @@ namespace BurnOutSharp.ProtectionType
return null;
// Get the .rdata section, if it exists
if (pex.ResourceDataSectionRaw != null)
if (pex.ContainsSection(".rdata"))
{
var matchers = new List<ContentMatchSet>
{
@@ -28,7 +28,7 @@ namespace BurnOutSharp.ProtectionType
}, "Microsoft Game Studios CD Check"),
};
string match = MatchUtil.GetFirstMatch(file, pex.ResourceDataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, pex.GetFirstSectionData(".rdata"), matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}

View File

@@ -2,10 +2,9 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using BurnOutSharp.ExecutableType.Microsoft.NE;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{
@@ -45,9 +44,8 @@ namespace BurnOutSharp.ProtectionType
/// <inheritdoc/>
public string CheckNewExecutable(string file, NewExecutable nex, bool includeDebug)
{
// Get the DOS stub from the executable, if possible
var stub = nex?.DOSStubHeader;
if (stub == null)
// Check we have a valid executable
if (nex == null)
return null;
// TODO: Don't read entire file

View File

@@ -1,6 +1,6 @@
using System;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{

View File

@@ -1,8 +1,8 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{
@@ -34,8 +34,9 @@ namespace BurnOutSharp.ProtectionType
if (sections == null)
return null;
// Get the .data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -51,7 +52,7 @@ namespace BurnOutSharp.ProtectionType
}, "CD-Lock"),
};
string match = MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{
@@ -16,7 +16,7 @@ namespace BurnOutSharp.ProtectionType
return null;
// Get the code/CODE section, if it exists
var codeSectionRaw = pex.ReadRawSection("code", first: true) ?? pex.ReadRawSection("CODE", first: true);
var codeSectionRaw = pex.GetFirstSectionData("code") ?? pex.GetFirstSectionData("CODE");
if (codeSectionRaw != null)
{
var matchers = new List<ContentMatchSet>

View File

@@ -4,9 +4,9 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{
@@ -62,8 +62,9 @@ namespace BurnOutSharp.ProtectionType
if (sections == null)
return null;
// Get the .data section, if it exists
if (pex.DataSectionRaw != null)
// Get the .data/DATA section, if it exists
var dataSectionRaw = pex.GetFirstSectionData(".data") ?? pex.GetFirstSectionData("DATA");
if (dataSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
@@ -74,28 +75,17 @@ namespace BurnOutSharp.ProtectionType
new ContentMatchSet(new byte?[] { 0x44, 0x41, 0x54, 0x41, 0x2E, 0x43, 0x44, 0x53 }, "Cactus Data Shield 200"),
};
string match = MatchUtil.GetFirstMatch(file, pex.DataSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, dataSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}
// Get the .rsrc section, if it exists
var rsrcSectionRaw = pex.ReadRawSection(".rsrc", first: false);
if (rsrcSectionRaw != null)
{
var matchers = new List<ContentMatchSet>
{
// CactusPJ
// Found in "Volumia!" by Puur (Barcode 7 43218 63282 2) (Discogs Release Code [r795427]).
// Modified version of the PlayJ Music Player specificaly for CDS, as indicated by the About page present when running the executable.
new ContentMatchSet(new byte?[] { 0x43, 0x61, 0x63, 0x74, 0x75, 0x73, 0x50, 0x4A }, "PlayJ Music Player (Cactus Data Shield 200)"),
};
// Found in "Volumia!" by Puur (Barcode 7 43218 63282 2) (Discogs Release Code [r795427]).
// Modified version of the PlayJ Music Player specificaly for CDS, as indicated by the About page present when running the executable.
var resources = pex.FindGenericResource("CactusPJ");
if (resources.Any())
return "PlayJ Music Player (Cactus Data Shield 200)";
string match = MatchUtil.GetFirstMatch(file, rsrcSectionRaw, matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}
return null;
}

View File

@@ -1,8 +1,8 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using BurnOutSharp.ExecutableType.Microsoft.PE;
using BurnOutSharp.Interfaces;
using BurnOutSharp.Matching;
using BurnOutSharp.Wrappers;
namespace BurnOutSharp.ProtectionType
{
@@ -59,7 +59,7 @@ namespace BurnOutSharp.ProtectionType
return $"ChosenBytes Code-Lock {pex.ProductVersion}";
// Get the .text section, if it exists
if (pex.TextSectionRaw != null)
if (pex.ContainsSection(".text"))
{
var matchers = new List<ContentMatchSet>
{
@@ -72,7 +72,7 @@ namespace BurnOutSharp.ProtectionType
}, "ChosenBytes Code-Lock"),
};
string match = MatchUtil.GetFirstMatch(file, pex.TextSectionRaw, matchers, includeDebug);
string match = MatchUtil.GetFirstMatch(file, pex.GetFirstSectionData(".text"), matchers, includeDebug);
if (!string.IsNullOrWhiteSpace(match))
return match;
}

Some files were not shown because too many files have changed in this diff Show More