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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 290 - (show annotations) (download)
Tue Jun 5 09:30:32 2012 UTC (8 years, 6 months ago) by william
File size: 13405 byte(s)
+ IMAGE_NT_HEADERS->IMAGE_FILE_HEADER set FieldOffset to 8 to not overlapp Signature
+ add exception handling that will bubble up from the using statement

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.IO;
6 using RomCheater.Logging;
7 using System.Runtime.InteropServices;
8 using System.Diagnostics;
9
10 namespace Sojaner.MemoryScanner
11 {
12 public class PEReader
13 {
14 public PEReader(FileInfo fi) : this(fi.FullName) { }
15 public PEReader(string filename)
16 {
17 Exception ErrorInfo = null;
18 try
19 {
20 this.Read(filename, out ErrorInfo);
21 }
22 catch (Exception ex)
23 {
24 logger.Error.WriteLine("PEReader: Failed to read process: {0}", filename);
25 if (ErrorInfo != null)
26 {
27 //logger.Error.WriteLine(ErrorInfo.GetBaseException().ToString());
28 throw ErrorInfo;
29 }
30 else
31 {
32 //logger.Error.WriteLine(ex.GetBaseException().ToString());
33 throw ex;
34 }
35 }
36 }
37
38 #region marshalling
39 private void Read(string filename, out Exception ErrorInfo)
40 {
41 ErrorInfo = null;
42 try
43 {
44 logger.Debug.WriteLine("Reading Exe: {0}", filename);
45
46 using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
47 {
48 try
49 {
50 byte[] data = new byte[] { };
51 GCHandle pinnedPacket = new GCHandle();
52 int size = 0;
53 BinaryReader br = new BinaryReader(fs);
54
55 #region IMAGE_DOS_HEADER
56 size = Marshal.SizeOf(typeof(IMAGE_DOS_HEADER));
57 data = br.ReadBytes(size);
58 pinnedPacket = GCHandle.Alloc(data, GCHandleType.Pinned);
59 IMAGE_DOS_HEADER DOS_HEADER = (IMAGE_DOS_HEADER)Marshal.PtrToStructure(pinnedPacket.AddrOfPinnedObject(), typeof(IMAGE_DOS_HEADER));
60 pinnedPacket.Free();
61 #endregion
62
63 // skip the old dos stub
64 br.BaseStream.Seek(DOS_HEADER.e_lfanew, SeekOrigin.Begin);
65
66 #region IMAGE_NT_HEADERS
67 size = Marshal.SizeOf(typeof(IMAGE_NT_HEADERS));
68 data = br.ReadBytes(size);
69 pinnedPacket = GCHandle.Alloc(data, GCHandleType.Pinned);
70 IMAGE_NT_HEADERS NT_HEADER = (IMAGE_NT_HEADERS)Marshal.PtrToStructure(pinnedPacket.AddrOfPinnedObject(), typeof(IMAGE_NT_HEADERS));
71 pinnedPacket.Free();
72 #endregion
73
74
75 br.Close();
76 }
77 catch (Exception ex)
78 {
79 ErrorInfo = ex;
80 }
81 }
82 }
83 catch (Exception ex)
84 {
85 ErrorInfo = ex;
86 }
87 }
88 #endregion
89
90 #region header support
91 #region IMAGE_DATA_DIRECTORY
92 [StructLayout(LayoutKind.Sequential)]
93 public struct IMAGE_DATA_DIRECTORY
94 {
95 public UInt32 VirtualAddress;
96 public UInt32 Size;
97 public bool HasAddress { get { return (VirtualAddress != 0); } }
98 public bool HasSize { get { return (Size > 0); } }
99 }
100 #endregion
101 #region IMAGE_FILE_HEADER
102 [StructLayout(LayoutKind.Sequential)]
103 public struct IMAGE_FILE_HEADER
104 {
105 public MachineType Machine;
106 public UInt16 NumberOfSections;
107 public UInt32 TimeDateStamp;
108 public UInt32 PointerToSymbolTable;
109 public UInt32 NumberOfSymbols;
110 public UInt16 SizeOfOptionalHeader;
111 public DllCharacteristicsType Characteristics;
112 }
113 #endregion
114 #region IMAGE_DOS_HEADER
115 [StructLayout(LayoutKind.Sequential)]
116 public struct IMAGE_DOS_HEADER
117 {
118 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
119 public char[] e_magic; // Magic number
120 public UInt16 e_cblp; // Bytes on last page of file
121 public UInt16 e_cp; // Pages in file
122 public UInt16 e_crlc; // Relocations
123 public UInt16 e_cparhdr; // Size of header in paragraphs
124 public UInt16 e_minalloc; // Minimum extra paragraphs needed
125 public UInt16 e_maxalloc; // Maximum extra paragraphs needed
126 public UInt16 e_ss; // Initial (relative) SS value
127 public UInt16 e_sp; // Initial SP value
128 public UInt16 e_csum; // Checksum
129 public UInt16 e_ip; // Initial IP value
130 public UInt16 e_cs; // Initial (relative) CS value
131 public UInt16 e_lfarlc; // File address of relocation table
132 public UInt16 e_ovno; // Overlay number
133 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
134 public UInt16[] e_res1; // Reserved words
135 public UInt16 e_oemid; // OEM identifier (for e_oeminfo)
136 public UInt16 e_oeminfo; // OEM information; e_oemid specific
137 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
138 public UInt16[] e_res2; // Reserved words
139 public Int32 e_lfanew; // File address of new exe header
140 private string _e_magic
141 {
142 get { return new string(e_magic); }
143 }
144 public bool isValid
145 {
146 get { return _e_magic == "MZ"; }
147 }
148 }
149 #endregion
150 #region IMAGE_NT_HEADERS
151 [StructLayout(LayoutKind.Explicit)]
152 public struct IMAGE_NT_HEADERS
153 {
154 [FieldOffset(0)]
155 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
156 public char[] Signature;
157
158 [FieldOffset(8)]
159 public IMAGE_FILE_HEADER FileHeader;
160
161 [FieldOffset(24)]
162 public IMAGE_OPTIONAL_HEADER OptionalHeader;
163
164 private string _Signature
165 {
166 get { return new string(Signature); }
167 }
168
169 public bool isValid
170 {
171 get { return _Signature == "PE\0\0" && (OptionalHeader.Magic == MagicType.IMAGE_NT_OPTIONAL_HDR32_MAGIC || OptionalHeader.Magic == MagicType.IMAGE_NT_OPTIONAL_HDR64_MAGIC); }
172 }
173 }
174 #endregion
175 #region MachineType
176 public enum MachineType : ushort
177 {
178 Native = 0,
179 I386 = 0x014c,
180 Itanium = 0x0200,
181 x64 = 0x8664
182 }
183 #endregion
184 #region MagicType
185 public enum MagicType : ushort
186 {
187 IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b,
188 IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b
189 }
190 #endregion
191 #region SubSystemType
192 public enum SubSystemType : ushort
193 {
194 IMAGE_SUBSYSTEM_UNKNOWN = 0,
195 IMAGE_SUBSYSTEM_NATIVE = 1,
196 IMAGE_SUBSYSTEM_WINDOWS_GUI = 2,
197 IMAGE_SUBSYSTEM_WINDOWS_CUI = 3,
198 IMAGE_SUBSYSTEM_POSIX_CUI = 7,
199 IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9,
200 IMAGE_SUBSYSTEM_EFI_APPLICATION = 10,
201 IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11,
202 IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12,
203 IMAGE_SUBSYSTEM_EFI_ROM = 13,
204 IMAGE_SUBSYSTEM_XBOX = 14
205
206 }
207 #endregion
208 #region DllCharacteristicsType
209 [Flags]
210 public enum DllCharacteristicsType : ushort
211 {
212 RES_0 = 0x0001,
213 RES_1 = 0x0002,
214 RES_2 = 0x0004,
215 RES_3 = 0x0008,
216 IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040,
217 IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY = 0x0080,
218 IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100,
219 IMAGE_DLLCHARACTERISTICS_NO_ISOLATION = 0x0200,
220 IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400,
221 IMAGE_DLLCHARACTERISTICS_NO_BIND = 0x0800,
222 RES_4 = 0x1000,
223 IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 0x2000,
224 IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000
225 }
226 #endregion
227 #region IMAGE_OPTIONAL_HEADER
228 [StructLayout(LayoutKind.Explicit)]
229 public struct IMAGE_OPTIONAL_HEADER
230 {
231 [FieldOffset(0)]
232 public MagicType Magic;
233
234 [FieldOffset(2)]
235 public byte MajorLinkerVersion;
236
237 [FieldOffset(3)]
238 public byte MinorLinkerVersion;
239
240 [FieldOffset(4)]
241 public uint SizeOfCode;
242
243 [FieldOffset(8)]
244 public uint SizeOfInitializedData;
245
246 [FieldOffset(12)]
247 public uint SizeOfUninitializedData;
248
249 [FieldOffset(16)]
250 public uint AddressOfEntryPoint;
251
252 [FieldOffset(20)]
253 public uint BaseOfCode;
254
255 // PE32 contains this additional field
256 [FieldOffset(24)]
257 public uint BaseOfData;
258
259 [FieldOffset(28)]
260 public uint ImageBase;
261
262 [FieldOffset(32)]
263 public uint SectionAlignment;
264
265 [FieldOffset(36)]
266 public uint FileAlignment;
267
268 [FieldOffset(40)]
269 public ushort MajorOperatingSystemVersion;
270
271 [FieldOffset(42)]
272 public ushort MinorOperatingSystemVersion;
273
274 [FieldOffset(44)]
275 public ushort MajorImageVersion;
276
277 [FieldOffset(46)]
278 public ushort MinorImageVersion;
279
280 [FieldOffset(48)]
281 public ushort MajorSubsystemVersion;
282
283 [FieldOffset(50)]
284 public ushort MinorSubsystemVersion;
285
286 [FieldOffset(52)]
287 public uint Win32VersionValue;
288
289 [FieldOffset(56)]
290 public uint SizeOfImage;
291
292 [FieldOffset(60)]
293 public uint SizeOfHeaders;
294
295 [FieldOffset(64)]
296 public uint CheckSum;
297
298 [FieldOffset(68)]
299 public SubSystemType Subsystem;
300
301 [FieldOffset(70)]
302 public DllCharacteristicsType DllCharacteristics;
303
304 [FieldOffset(72)]
305 public uint SizeOfStackReserve;
306
307 [FieldOffset(76)]
308 public uint SizeOfStackCommit;
309
310 [FieldOffset(80)]
311 public uint SizeOfHeapReserve;
312
313 [FieldOffset(84)]
314 public uint SizeOfHeapCommit;
315
316 [FieldOffset(88)]
317 public uint LoaderFlags;
318
319 [FieldOffset(92)]
320 public uint NumberOfRvaAndSizes;
321
322 [FieldOffset(96)]
323 public IMAGE_DATA_DIRECTORY ExportTable;
324
325 [FieldOffset(104)]
326 public IMAGE_DATA_DIRECTORY ImportTable;
327
328 [FieldOffset(112)]
329 public IMAGE_DATA_DIRECTORY ResourceTable;
330
331 [FieldOffset(120)]
332 public IMAGE_DATA_DIRECTORY ExceptionTable;
333
334 [FieldOffset(128)]
335 public IMAGE_DATA_DIRECTORY CertificateTable;
336
337 [FieldOffset(136)]
338 public IMAGE_DATA_DIRECTORY BaseRelocationTable;
339
340 [FieldOffset(144)]
341 public IMAGE_DATA_DIRECTORY Debug;
342
343 [FieldOffset(152)]
344 public IMAGE_DATA_DIRECTORY Architecture;
345
346 [FieldOffset(160)]
347 public IMAGE_DATA_DIRECTORY GlobalPtr;
348
349 [FieldOffset(168)]
350 public IMAGE_DATA_DIRECTORY TLSTable;
351
352 [FieldOffset(176)]
353 public IMAGE_DATA_DIRECTORY LoadConfigTable;
354
355 [FieldOffset(184)]
356 public IMAGE_DATA_DIRECTORY BoundImport;
357
358 [FieldOffset(192)]
359 public IMAGE_DATA_DIRECTORY IAT;
360
361 [FieldOffset(200)]
362 public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
363
364 [FieldOffset(208)]
365 public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
366
367 [FieldOffset(216)]
368 public IMAGE_DATA_DIRECTORY Reserved;
369 }
370 #endregion
371 #region IMAGE_EXPORT_DIRECTORY
372 [StructLayout(LayoutKind.Sequential)]
373 public struct IMAGE_EXPORT_DIRECTORY
374 {
375 public UInt32 Characteristics;
376 public UInt32 TimeDateStamp;
377 public UInt16 MajorVersion;
378 public UInt16 MinorVersion;
379 public UInt32 Name;
380 public UInt32 Base;
381 public UInt32 NumberOfFunctions;
382 public UInt32 NumberOfNames;
383 public UInt32 AddressOfFunctions; // RVA from base of image
384 public UInt32 AddressOfNames; // RVA from base of image
385 public UInt32 AddressOfNameOrdinals; // RVA from base of image
386 }
387 #endregion
388 #endregion
389 }
390 }

  ViewVC Help
Powered by ViewVC 1.1.22