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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 614 - (show annotations) (download)
Sat Jun 8 04:15:41 2013 UTC (7 years, 5 months ago) by william
File size: 38719 byte(s)

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

  ViewVC Help
Powered by ViewVC 1.1.22