/[RomCheater]/trunk/Win32/Sojaner.MemoryScanner/PEData.cs
ViewVC logotype

Annotation of /trunk/Win32/Sojaner.MemoryScanner/PEData.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 612 - (hide annotations) (download)
Sat Jun 8 03:55:09 2013 UTC (7 years, 1 month ago) by william
File size: 39503 byte(s)

1 william 607 #region Logging Defines
2     // include this any class or method that required logging, and comment-out what is not needed
3    
4     #region Enabled logging levels
5     #define LOGGING_ENABLE_INFO
6     #define LOGGING_ENABLE_WARN
7     #define LOGGING_ENABLE_DEBUG
8     //#define LOGGING_ENABLE_VERBOSEDEBUG
9     #define LOGGING_ENABLE_ERROR
10     #define LOGGING_ENABLE_VERBOSEERROR
11     #define LOGGING_ENABLE_PROFILER
12     #endregion
13     #endregion
14    
15     using System;
16     using System.Collections.Generic;
17     using System.Runtime.InteropServices;
18     using System.IO;
19     using System.Diagnostics;
20     using RomCheater.PluginFramework.Interfaces;
21 william 608 using System.ComponentModel;
22 william 609 using System.Text;
23 william 607
24     namespace Sojaner.MemoryScanner
25     {
26     public interface IPEDData
27     {
28     IMAGE_DOS_HEADER DosHeader { get; }
29 william 610 string NTSignature { get; }
30 william 607 IMAGE_FILE_HEADER FileHeader { get; }
31     IMAGE_OPTIONAL_HEADER32 OptionalHeader32 { get; }
32     IMAGE_OPTIONAL_HEADER64 OptionalHeader64 { get; }
33     //IMAGE_SECTION_HEADER[] SectionHeaders { get; }
34     bool Is32bitAssembly();
35     }
36    
37     public class PEData : IPEDData
38     {
39     #region IPEDData Members
40     public IMAGE_DOS_HEADER DosHeader { get { if (reader == null) { return new IMAGE_DOS_HEADER(); } else { return reader.DosHeader; } } }
41 william 610 public string NTSignature { get { if (reader == null) { return "0"; } else { return reader.NTSignature; } } }
42 william 607 public IMAGE_FILE_HEADER FileHeader { get { if (reader == null) { return new IMAGE_FILE_HEADER(); } else { return reader.FileHeader; } } }
43     public IMAGE_OPTIONAL_HEADER32 OptionalHeader32 { get { if (reader == null) { return new IMAGE_OPTIONAL_HEADER32(); } else { return reader.OptionalHeader32; } } }
44     public IMAGE_OPTIONAL_HEADER64 OptionalHeader64 { get { if (reader == null) { return new IMAGE_OPTIONAL_HEADER64(); } else { return reader.OptionalHeader64; } } }
45     public Boolean Is32bitAssembly() { if (reader == null) { return true; } else { return reader.Is32BitHeader; } }
46     #endregion
47    
48     private PeHeaderReader reader = null;
49    
50     public static readonly IPEDData Empty = new PEData();
51    
52     protected PEData() { }
53     public PEData(IAcceptsProcess iap)
54     {
55     if (iap == null) { throw new ArgumentNullException("iap", "The selected process cannot be null"); }
56     Process p = iap.AcceptedProcess;
57     string filename = p.MainModule.FileName;
58     reader = new PeHeaderReader(filename);
59     }
60     public PEData(IAcceptsProcessAndConfig iapc) : this((IAcceptsProcess)iapc) { }
61     }
62    
63     #region File Header Structures
64 william 608 [TypeConverter(typeof(ExpandableObjectConverter))]
65 william 607 public struct IMAGE_DOS_HEADER
66     { // DOS .EXE header
67 william 609 public UInt16 _e_magic; // Magic number
68     public UInt16 _e_cblp; // Bytes on last page of file
69     public UInt16 _e_cp; // Pages in file
70     public UInt16 _e_crlc; // Relocations
71     public UInt16 _e_cparhdr; // Size of header in paragraphs
72     public UInt16 _e_minalloc; // Minimum extra paragraphs needed
73     public UInt16 _e_maxalloc; // Maximum extra paragraphs needed
74     public UInt16 _e_ss; // Initial (relative) SS value
75     public UInt16 _e_sp; // Initial SP value
76     public UInt16 _e_csum; // Checksum
77     public UInt16 _e_ip; // Initial IP value
78     public UInt16 _e_cs; // Initial (relative) CS value
79     public UInt16 _e_lfarlc; // File address of relocation table
80     public UInt16 _e_ovno; // Overlay number
81     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
82     public UInt16[] _e_res1;
83     public UInt16 _e_oemid; // OEM identifier (for e_oeminfo)
84     public UInt16 _e_oeminfo; // OEM information; e_oemid specific
85     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
86     public UInt16[] _e_res2;
87     public UInt32 _e_lfanew; // File address of new exe header
88    
89     public string e_magic { get { return string.Format("0x{0:x4}", _e_magic); } }
90     public string e_cblp { get { return string.Format("0x{0:x4}", _e_cblp); } }
91     public string e_cp { get { return string.Format("0x{0:x4}", _e_cp); } }
92     public string e_crlc { get { return string.Format("0x{0:x4}", _e_crlc); } }
93     public string e_cparhdr { get { return string.Format("0x{0:x4}", _e_cparhdr); } }
94     public string e_minalloc { get { return string.Format("0x{0:x4}", _e_minalloc); } }
95     public string e_maxalloc { get { return string.Format("0x{0:x4}", _e_maxalloc); } }
96     public string e_ss { get { return string.Format("0x{0:x4}", _e_ss); } }
97     public string e_sp { get { return string.Format("0x{0:x4}", _e_sp); } }
98     public string e_csum { get { return string.Format("0x{0:x4}", _e_csum); } }
99     public string e_ip { get { return string.Format("0x{0:x4}", _e_ip); } }
100     public string e_cs { get { return string.Format("0x{0:x4}", _e_cs); } }
101     public string e_lfarlc { get { return string.Format("0x{0:x4}", _e_lfarlc); } }
102     public string e_ovno { get { return string.Format("0x{0:x4}", _e_ovno); } }
103     public ushort[] e_res1 { get { return _e_res1; } }
104     public string e_oemid { get { return string.Format("0x{0:x4}", _e_oemid); } }
105     public string e_oeminfo { get { return string.Format("0x{0:x4}", _e_oeminfo); } }
106     public ushort[] e_res2 { get { return _e_res2; } }
107     public string e_lfanew { get { return string.Format("0x{0:x8}", _e_lfanew); } }
108    
109     public override string ToString()
110     {
111     return Encoding.UTF8.GetString(BitConverter.GetBytes(_e_magic));
112     }
113 william 607 }
114 william 608 [TypeConverter(typeof(ExpandableObjectConverter))]
115 william 607 [StructLayout(LayoutKind.Sequential)]
116     public struct IMAGE_DATA_DIRECTORY
117     {
118     public UInt32 VirtualAddress;
119     public UInt32 Size;
120     }
121 william 608 [TypeConverter(typeof(ExpandableObjectConverter))]
122 william 607 [StructLayout(LayoutKind.Sequential, Pack = 1)]
123     public struct IMAGE_OPTIONAL_HEADER32
124     {
125 william 612 public UInt16 _Magic;
126     public Byte _MajorLinkerVersion;
127     public Byte _MinorLinkerVersion;
128     public UInt32 _SizeOfCode;
129     public UInt32 _SizeOfInitializedData;
130     public UInt32 _SizeOfUninitializedData;
131     public UInt32 _AddressOfEntryPoint;
132     public UInt32 _BaseOfCode;
133     public UInt32 _BaseOfData;
134     public UInt32 _ImageBase;
135     public UInt32 _SectionAlignment;
136     public UInt32 _FileAlignment;
137     public UInt16 _MajorOperatingSystemVersion;
138     public UInt16 _MinorOperatingSystemVersion;
139     public UInt16 _MajorImageVersion;
140     public UInt16 _MinorImageVersion;
141     public UInt16 _MajorSubsystemVersion;
142     public UInt16 _MinorSubsystemVersion;
143     public UInt32 _Win32VersionValue;
144     public UInt32 _SizeOfImage;
145     public UInt32 _SizeOfHeaders;
146     public UInt32 _CheckSum;
147     public SubSystemType _Subsystem;
148     public DllCharacteristicsType _DllCharacteristics;
149     public UInt32 _SizeOfStackReserve;
150     public UInt32 _SizeOfStackCommit;
151     public UInt32 _SizeOfHeapReserve;
152     public UInt32 _SizeOfHeapCommit;
153     public UInt32 _LoaderFlags;
154     public UInt32 _NumberOfRvaAndSizes;
155 william 607
156 william 612 public IMAGE_DATA_DIRECTORY _ExportTable;
157     public IMAGE_DATA_DIRECTORY _ImportTable;
158     public IMAGE_DATA_DIRECTORY _ResourceTable;
159     public IMAGE_DATA_DIRECTORY _ExceptionTable;
160     public IMAGE_DATA_DIRECTORY _CertificateTable;
161     public IMAGE_DATA_DIRECTORY _BaseRelocationTable;
162     public IMAGE_DATA_DIRECTORY _Debug;
163     public IMAGE_DATA_DIRECTORY _Architecture;
164     public IMAGE_DATA_DIRECTORY _GlobalPtr;
165     public IMAGE_DATA_DIRECTORY _TLSTable;
166     public IMAGE_DATA_DIRECTORY _LoadConfigTable;
167     public IMAGE_DATA_DIRECTORY _BoundImport;
168     public IMAGE_DATA_DIRECTORY _IAT;
169     public IMAGE_DATA_DIRECTORY _DelayImportDescriptor;
170     public IMAGE_DATA_DIRECTORY _CLRRuntimeHeader;
171     public IMAGE_DATA_DIRECTORY _Reserved;
172    
173     public string Magic { get { return ((MagicType)_Magic).ToString(); } }
174     public string MajorLinkerVersion { get { return string.Format("0x{0:x2}", _MajorLinkerVersion); } }
175     public string MinorLinkerVersion { get { return string.Format("0x{0:x2}", _MajorLinkerVersion); } }
176    
177     public string SizeOfCode { get { return string.Format("0x{0:x2}", _SizeOfCode); } }
178     public string SizeOfInitializedData { get { return string.Format("0x{0:x8}", _SizeOfInitializedData); } }
179     public string SizeOfUninitializedData { get { return string.Format("0x{0:x8}", _SizeOfUninitializedData); } }
180     public string AddressOfEntryPoint { get { return string.Format("0x{0:x8}", _AddressOfEntryPoint); } }
181     public string BaseOfCode { get { return string.Format("0x{0:x8}", _BaseOfCode); } }
182     public string BaseOfData { get { return string.Format("0x{0:x8}", _BaseOfData); } }
183     public string ImageBase { get { return string.Format("0x{0:x8}", _ImageBase); } }
184    
185     public string SectionAlignment { get { return string.Format("0x{0:x8}", _SectionAlignment); } }
186     public string FileAlignment { get { return string.Format("0x{0:x8}", _FileAlignment); } }
187    
188     public string MajorOperatingSystemVersion { get { return string.Format("0x{0:x4}", _MajorOperatingSystemVersion); } }
189     public string MinorOperatingSystemVersion { get { return string.Format("0x{0:x4}", _MinorOperatingSystemVersion); } }
190     public string MajorImageVersion { get { return string.Format("0x{0:x4}", _MajorImageVersion); } }
191     public string MinorImageVersion { get { return string.Format("0x{0:x4}", _MinorImageVersion); } }
192     public string MajorSubsystemVersion { get { return string.Format("0x{0:x4}", _MajorSubsystemVersion); } }
193     public string MinorSubsystemVersion { get { return string.Format("0x{0:x4}", _MinorSubsystemVersion); } }
194    
195     public string Win32VersionValue { get { return string.Format("0x{0:x8}", _Win32VersionValue); } }
196     public string SizeOfImage { get { return string.Format("0x{0:x8}", _SizeOfImage); } }
197     public string SizeOfHeaders { get { return string.Format("0x{0:x8}", _SizeOfHeaders); } }
198     public string CheckSum { get { return string.Format("0x{0:x8}", _CheckSum); } }
199    
200     public string Subsystem { get { return ((SubSystemType)_Subsystem).ToString(); } }
201     public string DllCharacteristics { get { return string.Format("0x{0:x4}", _DllCharacteristics); } }
202    
203     public string SizeOfStackReserve { get { return string.Format("0x{0:x8}", _SizeOfStackReserve); } }
204     public string SizeOfStackCommit { get { return string.Format("0x{0:x8}", _SizeOfStackCommit); } }
205     public string SizeOfHeapReserve { get { return string.Format("0x{0:x8}", _SizeOfHeapReserve); } }
206     public string SizeOfHeapCommit { get { return string.Format("0x{0:x8}", _SizeOfHeapCommit); } }
207    
208     public string LoaderFlags { get { return string.Format("0x{0:x8}", _LoaderFlags); } }
209     public string NumberOfRvaAndSizes { get { return string.Format("0x{0:x8}", _NumberOfRvaAndSizes); } }
210    
211    
212     // data directories
213     public IMAGE_DATA_DIRECTORY ExportTable { get { return _ExportTable; } }
214     public IMAGE_DATA_DIRECTORY ImportTable { get { return _ImportTable; } }
215     public IMAGE_DATA_DIRECTORY ResourceTable { get { return _ResourceTable; } }
216     public IMAGE_DATA_DIRECTORY ExceptionTable { get { return _ExceptionTable; } }
217     public IMAGE_DATA_DIRECTORY CertificateTable { get { return _CertificateTable; } }
218     public IMAGE_DATA_DIRECTORY BaseRelocationTable { get { return _BaseRelocationTable; } }
219     public IMAGE_DATA_DIRECTORY Debug { get { return _Debug; } }
220     public IMAGE_DATA_DIRECTORY Architecture { get { return _Architecture; } }
221     public IMAGE_DATA_DIRECTORY GlobalPtr { get { return _GlobalPtr; } }
222     public IMAGE_DATA_DIRECTORY TLSTable { get { return _TLSTable; } }
223     public IMAGE_DATA_DIRECTORY LoadConfigTable { get { return _LoadConfigTable; } }
224     public IMAGE_DATA_DIRECTORY BoundImport { get { return _BoundImport; } }
225     public IMAGE_DATA_DIRECTORY IAT { get { return _IAT; } }
226     public IMAGE_DATA_DIRECTORY DelayImportDescriptor { get { return _DelayImportDescriptor; } }
227     public IMAGE_DATA_DIRECTORY CLRRuntimeHeader { get { return _CLRRuntimeHeader; } }
228     public IMAGE_DATA_DIRECTORY Reserved { get { return _Reserved; } }
229    
230     public override string ToString()
231     {
232     return Magic;
233     }
234 william 607 }
235    
236     [StructLayout(LayoutKind.Sequential, Pack = 1)]
237 william 608 [TypeConverter(typeof(ExpandableObjectConverter))]
238 william 607 public struct IMAGE_OPTIONAL_HEADER64
239     {
240 william 612 public UInt16 _Magic;
241     public Byte _MajorLinkerVersion;
242     public Byte _MinorLinkerVersion;
243     public UInt32 _SizeOfCode;
244     public UInt32 _SizeOfInitializedData;
245     public UInt32 _SizeOfUninitializedData;
246     public UInt32 _AddressOfEntryPoint;
247     public UInt32 _BaseOfCode;
248     public UInt64 _ImageBase;
249     public UInt32 _SectionAlignment;
250     public UInt32 _FileAlignment;
251     public UInt16 _MajorOperatingSystemVersion;
252     public UInt16 _MinorOperatingSystemVersion;
253     public UInt16 _MajorImageVersion;
254     public UInt16 _MinorImageVersion;
255     public UInt16 _MajorSubsystemVersion;
256     public UInt16 _MinorSubsystemVersion;
257     public UInt32 _Win32VersionValue;
258     public UInt32 _SizeOfImage;
259     public UInt32 _SizeOfHeaders;
260     public UInt32 _CheckSum;
261     public UInt16 _Subsystem;
262     public DllCharacteristicsType _DllCharacteristics;
263     public UInt64 _SizeOfStackReserve;
264     public UInt64 _SizeOfStackCommit;
265     public UInt64 _SizeOfHeapReserve;
266     public UInt64 _SizeOfHeapCommit;
267     public UInt32 _LoaderFlags;
268     public UInt32 _NumberOfRvaAndSizes;
269 william 607
270 william 612 public IMAGE_DATA_DIRECTORY _ExportTable;
271     public IMAGE_DATA_DIRECTORY _ImportTable;
272     public IMAGE_DATA_DIRECTORY _ResourceTable;
273     public IMAGE_DATA_DIRECTORY _ExceptionTable;
274     public IMAGE_DATA_DIRECTORY _CertificateTable;
275     public IMAGE_DATA_DIRECTORY _BaseRelocationTable;
276     public IMAGE_DATA_DIRECTORY _Debug;
277     public IMAGE_DATA_DIRECTORY _Architecture;
278     public IMAGE_DATA_DIRECTORY _GlobalPtr;
279     public IMAGE_DATA_DIRECTORY _TLSTable;
280     public IMAGE_DATA_DIRECTORY _LoadConfigTable;
281     public IMAGE_DATA_DIRECTORY _BoundImport;
282     public IMAGE_DATA_DIRECTORY _IAT;
283     public IMAGE_DATA_DIRECTORY _DelayImportDescriptor;
284     public IMAGE_DATA_DIRECTORY _CLRRuntimeHeader;
285     public IMAGE_DATA_DIRECTORY _Reserved;
286    
287    
288     public string Magic { get { return ((MagicType)_Magic).ToString(); } }
289     public string MajorLinkerVersion { get { return string.Format("0x{0:x2}", _MajorLinkerVersion); } }
290     public string MinorLinkerVersion { get { return string.Format("0x{0:x2}", _MajorLinkerVersion); } }
291    
292     public string SizeOfCode { get { return string.Format("0x{0:x2}", _SizeOfCode); } }
293     public string SizeOfInitializedData { get { return string.Format("0x{0:x8}", _SizeOfInitializedData); } }
294     public string SizeOfUninitializedData { get { return string.Format("0x{0:x8}", _SizeOfUninitializedData); } }
295     public string AddressOfEntryPoint { get { return string.Format("0x{0:x8}", _AddressOfEntryPoint); } }
296     public string BaseOfCode { get { return string.Format("0x{0:x8}", _BaseOfCode); } }
297    
298     public string ImageBase { get { return string.Format("0x{0:x16}", _ImageBase); } }
299    
300     public string SectionAlignment { get { return string.Format("0x{0:x8}", _SectionAlignment); } }
301     public string FileAlignment { get { return string.Format("0x{0:x8}", _FileAlignment); } }
302    
303     public string MajorOperatingSystemVersion { get { return string.Format("0x{0:x4}", _MajorOperatingSystemVersion); } }
304     public string MinorOperatingSystemVersion { get { return string.Format("0x{0:x4}", _MinorOperatingSystemVersion); } }
305     public string MajorImageVersion { get { return string.Format("0x{0:x4}", _MajorImageVersion); } }
306     public string MinorImageVersion { get { return string.Format("0x{0:x4}", _MinorImageVersion); } }
307     public string MajorSubsystemVersion { get { return string.Format("0x{0:x4}", _MajorSubsystemVersion); } }
308     public string MinorSubsystemVersion { get { return string.Format("0x{0:x4}", _MinorSubsystemVersion); } }
309    
310     public string Win32VersionValue { get { return string.Format("0x{0:x8}", _Win32VersionValue); } }
311     public string SizeOfImage { get { return string.Format("0x{0:x8}", _SizeOfImage); } }
312     public string SizeOfHeaders { get { return string.Format("0x{0:x8}", _SizeOfHeaders); } }
313     public string CheckSum { get { return string.Format("0x{0:x8}", _CheckSum); } }
314    
315     public string Subsystem { get { return ((SubSystemType)_Subsystem).ToString(); } }
316     public string DllCharacteristics { get { return string.Format("0x{0:x4}", _DllCharacteristics); } }
317    
318     public string SizeOfStackReserve { get { return string.Format("0x{0:x16}", _SizeOfStackReserve); } }
319     public string SizeOfStackCommit { get { return string.Format("0x{0:x16}", _SizeOfStackCommit); } }
320     public string SizeOfHeapReserve { get { return string.Format("0x{0:x16}", _SizeOfHeapReserve); } }
321     public string SizeOfHeapCommit { get { return string.Format("0x{0:x16}", _SizeOfHeapCommit); } }
322    
323     public string LoaderFlags { get { return string.Format("0x{0:x8}", _LoaderFlags); } }
324     public string NumberOfRvaAndSizes { get { return string.Format("0x{0:x8}", _NumberOfRvaAndSizes); } }
325    
326     // data directories
327     public IMAGE_DATA_DIRECTORY ExportTable { get { return _ExportTable; } }
328     public IMAGE_DATA_DIRECTORY ImportTable { get { return _ImportTable; } }
329     public IMAGE_DATA_DIRECTORY ResourceTable { get { return _ResourceTable; } }
330     public IMAGE_DATA_DIRECTORY ExceptionTable { get { return _ExceptionTable; } }
331     public IMAGE_DATA_DIRECTORY CertificateTable { get { return _CertificateTable; } }
332     public IMAGE_DATA_DIRECTORY BaseRelocationTable { get { return _BaseRelocationTable; } }
333     public IMAGE_DATA_DIRECTORY Debug { get { return _Debug; } }
334     public IMAGE_DATA_DIRECTORY Architecture { get { return _Architecture; } }
335     public IMAGE_DATA_DIRECTORY GlobalPtr { get { return _GlobalPtr; } }
336     public IMAGE_DATA_DIRECTORY TLSTable { get { return _TLSTable; } }
337     public IMAGE_DATA_DIRECTORY LoadConfigTable { get { return _LoadConfigTable; } }
338     public IMAGE_DATA_DIRECTORY BoundImport { get { return _BoundImport; } }
339     public IMAGE_DATA_DIRECTORY IAT { get { return _IAT; } }
340     public IMAGE_DATA_DIRECTORY DelayImportDescriptor { get { return _DelayImportDescriptor; } }
341     public IMAGE_DATA_DIRECTORY CLRRuntimeHeader { get { return _CLRRuntimeHeader; } }
342     public IMAGE_DATA_DIRECTORY Reserved { get { return _Reserved; } }
343    
344     public override string ToString()
345     {
346     return Magic;
347     }
348    
349 william 607 }
350    
351     [StructLayout(LayoutKind.Sequential, Pack = 1)]
352 william 608 [TypeConverter(typeof(ExpandableObjectConverter))]
353 william 607 public struct IMAGE_FILE_HEADER
354     {
355 william 611 public MachineTypeFlags _Machine;
356     public UInt16 _NumberOfSections;
357     public UInt32 _TimeDateStamp;
358     public UInt32 _PointerToSymbolTable;
359     public UInt32 _NumberOfSymbols;
360     public UInt16 _SizeOfOptionalHeader;
361     public FileCharacteristicType _Characteristics;
362    
363     public MachineTypeFlags MachineType { get { return _Machine; } }
364     public string NumberOfSections { get { return string.Format("0x{0:x4}", _NumberOfSections); } }
365     public string TimeDateStamp { get { return string.Format("{0} (0x{1:x8})", GetDateTimeFromLinkerTime(_TimeDateStamp).ToString(), _TimeDateStamp); } }
366     public string PointerToSymbolTable { get { return string.Format("0x{0:x8}", _PointerToSymbolTable); } }
367     public string NumberOfSymbols { get { return string.Format("0x{0:x8}", _NumberOfSymbols); } }
368     public string SizeOfOptionalHeader { get { return string.Format("0x{0:x4}", _SizeOfOptionalHeader); } }
369     public FileCharacteristicType Characteristics { get { return _Characteristics; } }
370     public override string ToString()
371     {
372     return MachineType.ToString();
373     }
374    
375     private DateTime GetDateTimeFromLinkerTime(UInt32 linker_timer)
376     {
377     // http://msdn.microsoft.com/en-us/library/ms809762.aspx
378     // This field holds the number of seconds since December 31st, 1969, at 4:00 P.M.
379     DateTime t = new DateTime(1969, 12, 31, 16, 0, 0);
380     t = t.AddSeconds(linker_timer);
381     t += TimeZone.CurrentTimeZone.GetUtcOffset(t);
382     return t;
383     }
384 william 607 }
385    
386     // Grabbed the following 2 definitions from http://www.pinvoke.net/default.aspx/Structures/IMAGE_SECTION_HEADER.html
387    
388 william 608 [TypeConverter(typeof(ExpandableObjectConverter))]
389 william 607 [StructLayout(LayoutKind.Explicit)]
390     public struct IMAGE_SECTION_HEADER
391     {
392     [FieldOffset(0)]
393     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
394     public char[] Name;
395     [FieldOffset(8)]
396     public UInt32 VirtualSize;
397     [FieldOffset(12)]
398     public UInt32 VirtualAddress;
399     [FieldOffset(16)]
400     public UInt32 SizeOfRawData;
401     [FieldOffset(20)]
402     public UInt32 PointerToRawData;
403     [FieldOffset(24)]
404     public UInt32 PointerToRelocations;
405     [FieldOffset(28)]
406     public UInt32 PointerToLinenumbers;
407     [FieldOffset(32)]
408     public UInt16 NumberOfRelocations;
409     [FieldOffset(34)]
410     public UInt16 NumberOfLinenumbers;
411     [FieldOffset(36)]
412     public DataSectionFlags Characteristics;
413    
414     public string Section
415     {
416     get { return new string(Name); }
417     }
418     }
419     #endregion File Header Structures
420    
421    
422     #region code
423     #region helpers
424     [Flags]
425 william 611 public enum MachineTypeFlags : ushort
426 william 607 {
427     x86 = 0x14C,
428     Alpha = 0x184,
429     ARM = 0x1C0,
430     MIPS16R3000 = 0x162,
431     MIPS16R4000 = 0x166,
432     MIPS16R10000 = 0x168,
433     PowerPCLE = 0x1F0,
434     PowerPCBE = 0x1F2,
435     Itanium = 0x200,
436     MIPS16 = 0x266,
437     Alpha64 = 0x284,
438     MIPSFPU = 0x366,
439     MIPSFPU16 = 0x466,
440     x64 = 0x8664,
441     }
442     public enum MagicType : ushort
443     {
444     NT_OPTIONAL_HEADER_NOT_PRESENT, // 0
445     NT_OPTIONAL_HEADER_32 = 0x10b,
446     NT_OPTIONAL_HEADER_64 = 0x20b
447     }
448     public enum SubSystemType : ushort
449     {
450     IMAGE_SUBSYSTEM_UNKNOWN = 0,
451     IMAGE_SUBSYSTEM_NATIVE = 1,
452     IMAGE_SUBSYSTEM_WINDOWS_GUI = 2,
453     IMAGE_SUBSYSTEM_WINDOWS_CUI = 3,
454     IMAGE_SUBSYSTEM_POSIX_CUI = 7,
455     IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9,
456     IMAGE_SUBSYSTEM_EFI_APPLICATION = 10,
457     IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11,
458     IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12,
459     IMAGE_SUBSYSTEM_EFI_ROM = 13,
460     IMAGE_SUBSYSTEM_XBOX = 14
461    
462     }
463     public enum DllCharacteristicsType : ushort
464     {
465     RES_0 = 0x0001,
466     RES_1 = 0x0002,
467     RES_2 = 0x0004,
468     RES_3 = 0x0008,
469     IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040,
470     IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY = 0x0080,
471     IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100,
472     IMAGE_DLLCHARACTERISTICS_NO_ISOLATION = 0x0200,
473     IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400,
474     IMAGE_DLLCHARACTERISTICS_NO_BIND = 0x0800,
475     RES_4 = 0x1000,
476     IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 0x2000,
477     IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000
478     }
479     [Flags]
480     public enum FileCharacteristicType : ushort
481     {
482     RelocationInformationStrippedFromFile = 0x1,
483     Executable = 0x2,
484     LineNumbersStripped = 0x4,
485     SymbolTableStripped = 0x8,
486     AggresiveTrimWorkingSet = 0x10,
487     LargeAddressAware = 0x20,
488     Supports16Bit = 0x40,
489     ReservedBytesWo = 0x80,
490     Supports32Bit = 0x100,
491     DebugInfoStripped = 0x200,
492     RunFromSwapIfInRemovableMedia = 0x400,
493     RunFromSwapIfInNetworkMedia = 0x800,
494     IsSytemFile = 0x1000,
495     IsDLL = 0x2000,
496     IsOnlyForSingleCoreProcessor = 0x4000,
497     BytesOfWordReserved = 0x8000,
498     }
499     #region DataSectionFlags
500     [Flags]
501     public enum DataSectionFlags : uint
502     {
503     /// <summary>
504     /// Reserved for future use.
505     /// </summary>
506     TypeReg = 0x00000000,
507     /// <summary>
508     /// Reserved for future use.
509     /// </summary>
510     TypeDsect = 0x00000001,
511     /// <summary>
512     /// Reserved for future use.
513     /// </summary>
514     TypeNoLoad = 0x00000002,
515     /// <summary>
516     /// Reserved for future use.
517     /// </summary>
518     TypeGroup = 0x00000004,
519     /// <summary>
520     /// The section should not be padded to the next boundary. This flag is obsolete and is replaced by IMAGE_SCN_ALIGN_1BYTES. This is valid only for object files.
521     /// </summary>
522     TypeNoPadded = 0x00000008,
523     /// <summary>
524     /// Reserved for future use.
525     /// </summary>
526     TypeCopy = 0x00000010,
527     /// <summary>
528     /// The section contains executable code.
529     /// </summary>
530     ContentCode = 0x00000020,
531     /// <summary>
532     /// The section contains initialized data.
533     /// </summary>
534     ContentInitializedData = 0x00000040,
535     /// <summary>
536     /// The section contains uninitialized data.
537     /// </summary>
538     ContentUninitializedData = 0x00000080,
539     /// <summary>
540     /// Reserved for future use.
541     /// </summary>
542     LinkOther = 0x00000100,
543     /// <summary>
544     /// The section contains comments or other information. The .drectve section has this type. This is valid for object files only.
545     /// </summary>
546     LinkInfo = 0x00000200,
547     /// <summary>
548     /// Reserved for future use.
549     /// </summary>
550     TypeOver = 0x00000400,
551     /// <summary>
552     /// The section will not become part of the image. This is valid only for object files.
553     /// </summary>
554     LinkRemove = 0x00000800,
555     /// <summary>
556     /// The section contains COMDAT data. For more information, see section 5.5.6, COMDAT Sections (Object Only). This is valid only for object files.
557     /// </summary>
558     LinkComDat = 0x00001000,
559     /// <summary>
560     /// Reset speculative exceptions handling bits in the TLB entries for this section.
561     /// </summary>
562     NoDeferSpecExceptions = 0x00004000,
563     /// <summary>
564     /// The section contains data referenced through the global pointer (GP).
565     /// </summary>
566     RelativeGP = 0x00008000,
567     /// <summary>
568     /// Reserved for future use.
569     /// </summary>
570     MemPurgeable = 0x00020000,
571     /// <summary>
572     /// Reserved for future use.
573     /// </summary>
574     Memory16Bit = 0x00020000,
575     /// <summary>
576     /// Reserved for future use.
577     /// </summary>
578     MemoryLocked = 0x00040000,
579     /// <summary>
580     /// Reserved for future use.
581     /// </summary>
582     MemoryPreload = 0x00080000,
583     /// <summary>
584     /// Align data on a 1-byte boundary. Valid only for object files.
585     /// </summary>
586     Align1Bytes = 0x00100000,
587     /// <summary>
588     /// Align data on a 2-byte boundary. Valid only for object files.
589     /// </summary>
590     Align2Bytes = 0x00200000,
591     /// <summary>
592     /// Align data on a 4-byte boundary. Valid only for object files.
593     /// </summary>
594     Align4Bytes = 0x00300000,
595     /// <summary>
596     /// Align data on an 8-byte boundary. Valid only for object files.
597     /// </summary>
598     Align8Bytes = 0x00400000,
599     /// <summary>
600     /// Align data on a 16-byte boundary. Valid only for object files.
601     /// </summary>
602     Align16Bytes = 0x00500000,
603     /// <summary>
604     /// Align data on a 32-byte boundary. Valid only for object files.
605     /// </summary>
606     Align32Bytes = 0x00600000,
607     /// <summary>
608     /// Align data on a 64-byte boundary. Valid only for object files.
609     /// </summary>
610     Align64Bytes = 0x00700000,
611     /// <summary>
612     /// Align data on a 128-byte boundary. Valid only for object files.
613     /// </summary>
614     Align128Bytes = 0x00800000,
615     /// <summary>
616     /// Align data on a 256-byte boundary. Valid only for object files.
617     /// </summary>
618     Align256Bytes = 0x00900000,
619     /// <summary>
620     /// Align data on a 512-byte boundary. Valid only for object files.
621     /// </summary>
622     Align512Bytes = 0x00A00000,
623     /// <summary>
624     /// Align data on a 1024-byte boundary. Valid only for object files.
625     /// </summary>
626     Align1024Bytes = 0x00B00000,
627     /// <summary>
628     /// Align data on a 2048-byte boundary. Valid only for object files.
629     /// </summary>
630     Align2048Bytes = 0x00C00000,
631     /// <summary>
632     /// Align data on a 4096-byte boundary. Valid only for object files.
633     /// </summary>
634     Align4096Bytes = 0x00D00000,
635     /// <summary>
636     /// Align data on an 8192-byte boundary. Valid only for object files.
637     /// </summary>
638     Align8192Bytes = 0x00E00000,
639     /// <summary>
640     /// The section contains extended relocations.
641     /// </summary>
642     LinkExtendedRelocationOverflow = 0x01000000,
643     /// <summary>
644     /// The section can be discarded as needed.
645     /// </summary>
646     MemoryDiscardable = 0x02000000,
647     /// <summary>
648     /// The section cannot be cached.
649     /// </summary>
650     MemoryNotCached = 0x04000000,
651     /// <summary>
652     /// The section is not pageable.
653     /// </summary>
654     MemoryNotPaged = 0x08000000,
655     /// <summary>
656     /// The section can be shared in memory.
657     /// </summary>
658     MemoryShared = 0x10000000,
659     /// <summary>
660     /// The section can be executed as code.
661     /// </summary>
662     MemoryExecute = 0x20000000,
663     /// <summary>
664     /// The section can be read.
665     /// </summary>
666     MemoryRead = 0x40000000,
667     /// <summary>
668     /// The section can be written to.
669     /// </summary>
670     MemoryWrite = 0x80000000
671     }
672     #endregion
673     #endregion
674     /// <summary>
675     /// Reads in the header information of the Portable Executable format.
676     /// Provides information such as the date the assembly was compiled.
677     /// </summary>
678     public class PeHeaderReader
679     {
680    
681    
682     #region Private Fields
683    
684     private UInt32 ntSignature;
685     /// <summary>
686     /// The DOS header
687     /// </summary>
688     private IMAGE_DOS_HEADER dosHeader;
689     /// <summary>
690     /// The file header
691     /// </summary>
692     private IMAGE_FILE_HEADER fileHeader;
693     /// <summary>
694     /// Optional 32 bit file header
695     /// </summary>
696     private IMAGE_OPTIONAL_HEADER32 optionalHeader32;
697     /// <summary>
698     /// Optional 64 bit file header
699     /// </summary>
700     private IMAGE_OPTIONAL_HEADER64 optionalHeader64;
701     /// <summary>
702     /// Image Section headers. Number of sections is in the file header.
703     /// </summary>
704     private IMAGE_SECTION_HEADER[] imageSectionHeaders;
705    
706     #endregion Private Fields
707    
708     #region Public Methods
709    
710     public PeHeaderReader(string filePath)
711     {
712     // Read in the DLL or EXE and get the timestamp
713     using (FileStream stream = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
714     {
715     BinaryReader reader = new BinaryReader(stream);
716     dosHeader = FromBinaryReader<IMAGE_DOS_HEADER>(reader);
717    
718     // Add 4 bytes to the offset
719 william 609 stream.Seek(dosHeader._e_lfanew, SeekOrigin.Begin);
720 william 607
721     UInt32 ntHeadersSignature = reader.ReadUInt32();
722     ntSignature = ntHeadersSignature;
723     fileHeader = FromBinaryReader<IMAGE_FILE_HEADER>(reader);
724     if (this.Is32BitHeader)
725     {
726     optionalHeader32 = FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader);
727     }
728     else
729     {
730     optionalHeader64 = FromBinaryReader<IMAGE_OPTIONAL_HEADER64>(reader);
731     }
732    
733 william 611 imageSectionHeaders = new IMAGE_SECTION_HEADER[fileHeader._NumberOfSections];
734 william 607 for (int headerNo = 0; headerNo < imageSectionHeaders.Length; ++headerNo)
735     {
736     imageSectionHeaders[headerNo] = FromBinaryReader<IMAGE_SECTION_HEADER>(reader);
737     }
738    
739     }
740     }
741    
742     /// <summary>
743     /// Gets the header of the .NET assembly that called this function
744     /// </summary>
745     /// <returns></returns>
746     public static PeHeaderReader GetCallingAssemblyHeader()
747     {
748     // Get the path to the calling assembly, which is the path to the
749     // DLL or EXE that we want the time of
750     string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
751    
752     // Get and return the timestamp
753     return new PeHeaderReader(filePath);
754     }
755    
756     /// <summary>
757     /// Gets the header of the .NET assembly that called this function
758     /// </summary>
759     /// <returns></returns>
760     public static PeHeaderReader GetAssemblyHeader()
761     {
762     // Get the path to the calling assembly, which is the path to the
763     // DLL or EXE that we want the time of
764     string filePath = System.Reflection.Assembly.GetAssembly(typeof(PeHeaderReader)).Location;
765    
766     // Get and return the timestamp
767     return new PeHeaderReader(filePath);
768     }
769    
770     /// <summary>
771     /// Reads in a block from a file and converts it to the struct
772     /// type specified by the template parameter
773     /// </summary>
774     /// <typeparam name="T"></typeparam>
775     /// <param name="reader"></param>
776     /// <returns></returns>
777     public static T FromBinaryReader<T>(BinaryReader reader)
778     {
779     // Read in a byte array
780     byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
781    
782     // Pin the managed memory while, copy it out the data, then unpin it
783     GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
784     T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
785     handle.Free();
786    
787     return theStructure;
788     }
789    
790     #endregion Public Methods
791    
792     #region Properties
793    
794     /// <summary>
795     /// Gets if the file header is 32 bit or not
796     /// </summary>
797     public bool Is32BitHeader
798     {
799     get
800     {
801     return FileHeader.Characteristics.HasFlag(FileCharacteristicType.Supports32Bit);
802     }
803     }
804    
805     /// <summary>
806     /// Gets the file header
807     /// </summary>
808     public IMAGE_FILE_HEADER FileHeader
809     {
810     get
811     {
812     return fileHeader;
813     }
814     }
815     /// <summary>
816     /// Gets the file header
817     /// </summary>
818 william 610 public string NTSignature
819 william 607 {
820     get
821     {
822 william 610 ushort sig = (ushort)ntSignature;
823     return string.Format("0x{0:x4} [{1}]", sig, Encoding.ASCII.GetString(BitConverter.GetBytes(sig)));
824 william 607 }
825     }
826     /// <summary>
827     /// Gets the file header
828     /// </summary>
829     public IMAGE_DOS_HEADER DosHeader
830     {
831     get
832     {
833     return dosHeader;
834     }
835     }
836     /// <summary>
837     /// Gets the optional header
838     /// </summary>
839     public IMAGE_OPTIONAL_HEADER32 OptionalHeader32
840     {
841     get
842     {
843     return optionalHeader32;
844     }
845     }
846    
847     /// <summary>
848     /// Gets the optional header
849     /// </summary>
850     public IMAGE_OPTIONAL_HEADER64 OptionalHeader64
851     {
852     get
853     {
854     return optionalHeader64;
855     }
856     }
857    
858     public IMAGE_SECTION_HEADER[] ImageSectionHeaders
859     {
860     get
861     {
862     return imageSectionHeaders;
863     }
864     }
865    
866 william 611 ///// <summary>
867     ///// Gets the timestamp from the file header
868     ///// </summary>
869     //public DateTime TimeStamp
870     //{
871     // get
872     // {
873     // // Timestamp is a date offset from 1970
874     // DateTime returnValue = new DateTime(1970, 1, 1, 0, 0, 0);
875 william 607
876 william 611 // // Add in the number of seconds since 1970/1/1
877     // returnValue = returnValue.AddSeconds(fileHeader.TimeDateStamp);
878     // // Adjust to local timezone
879     // returnValue += TimeZone.CurrentTimeZone.GetUtcOffset(returnValue);
880 william 607
881 william 611 // return returnValue;
882     // }
883     //}
884 william 607
885     #endregion Properties
886     }
887     #endregion
888     }

  ViewVC Help
Powered by ViewVC 1.1.22