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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 600 - (hide annotations) (download)
Fri Jun 7 10:27:53 2013 UTC (8 years, 11 months ago) by william
File size: 38851 byte(s)

1 william 414 #region Logging Defines
2     // include this any class or method that required logging, and comment-out what is not needed
3 william 415
4 william 414 #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 william 427 //#define LOGGING_ENABLE_PROFILER
12 william 414 #endregion
13     #endregion
14     using System;
15 william 88 using System.Collections.Generic;
16     using System.Text;
17     using System.Diagnostics;
18     using System.Threading;
19     using System.Runtime.InteropServices;
20 william 156 using RomCheater.Logging;
21 william 162 using System.IO;
22 william 231 using Sojaner.MemoryScanner.MemoryProviers;
23 william 284 using Microsoft.Win32.SafeHandles;
24 william 351 using Microsoft.Win32.Interop;
25     using System.ComponentModel;
26 william 404 using ManagedWinapi;
27 william 408 using RomCheater.PluginFramework.Events;
28 william 88
29     namespace Sojaner.MemoryScanner
30     {
31     // code borrowed from: http://www.codeproject.com/KB/cs/sojaner_memory_scanner.aspx
32     #region ProcessMemoryReader class
33     //Thanks goes to Arik Poznanski for P/Invokes and methods needed to read and write the Memory
34     //For more information refer to "Minesweeper, Behind the scenes" article by Arik Poznanski at Codeproject.com
35 william 408 internal class ProcessMemoryReader : IMemoryReader, IMemoryWriter, IFileWriter, IPatchMemory,IReadMemory, IAcceptsBytesReadEvent
36 william 88 {
37 william 404 // constants information can be found in <winnt.h>
38     [Flags]
39 william 411 enum ProcessAccessFlags : uint
40 william 404 {
41 william 411 All = 0x001F0FFF,
42     Terminate = 0x00000001,
43     CreateThread = 0x00000002,
44     VMOperation = 0x00000008,
45     VMRead = 0x00000010,
46     VMWrite = 0x00000020,
47     DupHandle = 0x00000040,
48     SetInformation = 0x00000200,
49     QueryInformation = 0x00000400,
50     Synchronize = 0x00100000
51 william 404 }
52     [Flags]
53     public enum AllocationProtect : uint
54     {
55     // http://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx
56     NONE = 0,
57     PAGE_NOACCESS = 0x00000001,
58     PAGE_READONLY = 0x00000002,
59     PAGE_READWRITE = 0x00000004,
60     PAGE_WRITECOPY = 0x00000008,
61     PAGE_EXECUTE = 0x00000010,
62     PAGE_EXECUTE_READ = 0x00000020,
63     PAGE_EXECUTE_READWRITE = 0x00000040,
64     PAGE_EXECUTE_WRITECOPY = 0x00000080,
65     PAGE_GUARD = 0x00000100,
66     PAGE_NOCACHE = 0x00000200,
67     PAGE_WRITECOMBINE = 0x00000400
68     }
69     [StructLayout(LayoutKind.Sequential)]
70     public struct MEMORY_BASIC_INFORMATION
71     {
72     public IntPtr BaseAddress;
73     public IntPtr AllocationBase;
74     public AllocationProtect AllocationProtect;
75     public IntPtr RegionSize;
76     public uint State;
77     public uint Protect;
78     public uint Type;
79     }
80 william 88
81     public ProcessMemoryReader()
82     {
83     }
84 william 408 public event BaseEventHandler<OnBytesReadEventArgs> OnBytesRead;
85 william 88 /// <summary>
86     /// Process from which to read
87     /// </summary>
88 william 477 public Process ReadProcess
89 william 88 {
90     get
91     {
92 william 477 return m_ReadProcess;
93 william 88 }
94     set
95     {
96 william 477 m_ReadProcess = value;
97 william 88 }
98     }
99    
100 william 477 private Process m_ReadProcess = null;
101 william 286
102     //SafeWaitHandle handle;
103 william 428 //private IntPtr handle = IntPtr.Zero;
104 william 419 //SafeWaitHandle m_hProcess; /* unused */
105 william 428 //public void OpenProcess()
106     //{
107     // try
108     // {
109     // // m_hProcess = ProcessMemoryReaderApi.OpenProcess(ProcessMemoryReaderApi.PROCESS_VM_READ, 1, (uint)m_ReadProcess.Id);
110     // //if (!TokenAdjuster.AdjustProcessTokenPrivileges("SeDebugPrivilege"))
111     // //{
112     // // logger.Warn.WriteLine("Failed to set SeDebugPrivilege on current process");
113     // //}
114     // ProcessAccessFlags access;
115     // access = ProcessAccessFlags.VMRead
116     // | ProcessAccessFlags.VMWrite
117     // | ProcessAccessFlags.VMOperation;
118     // //m_hProcess = ProcessMemoryReaderApi.OpenProcess((uint)access, 1, (uint)m_ReadProcess.Id);
119     // handle = ProcessMemoryReaderApi.OpenProcess(access, true, m_ReadProcess.Id);
120     // //m_hProcess = new SafeWaitHandle(handle, false);
121     // }
122     // catch (SEHException ex)
123     // {
124     // logger.Error.WriteLine("WriteProcessMemoryToFile() SEHException was thrown: (0x{0:x8}) - {1}", ex.ErrorCode, ex.Message);
125     // logger.Error.WriteLine(ex.ToString());
126     // throw ex;
127     // }
128     // catch (Exception ex)
129     // {
130     // logger.Error.WriteLine(ex.ToString());
131     // throw ex;
132     // }
133     //}
134 william 88
135 william 428 //public void CloseHandle()
136     //{
137     // try
138     // {
139     // ////if (handle.IsInvalid) { return; }
140     // ////if (handle.IsClosed) { return; }
141     // //m_hProcess.Close();
142     // //m_hProcess.Dispose();
143     // //m_hProcess = null;
144     // //handle = IntPtr.Zero;
145     // //m_ReadProcess = null;
146     // //string stack_trace = System.Environment.StackTrace;
147     // int iRetValue;
148     // iRetValue = ProcessMemoryReaderApi.CloseHandle(handle);
149     // handle = IntPtr.Zero;
150     // ReadProcess = null;
151     // if (iRetValue == 0)
152     // {
153     // throw new Exception("CloseHandle failed");
154     // }
155     // }
156     // catch (SEHException ex)
157     // {
158     // logger.Error.WriteLine("WriteProcessMemoryToFile() SEHException was thrown: (0x{0:x8}) - {1}", ex.ErrorCode, ex.Message);
159     // logger.Error.WriteLine(ex.ToString());
160     // throw ex;
161     // }
162     // catch (Exception ex)
163     // {
164     // logger.Error.WriteLine(ex.ToString());
165     // throw ex;
166     // }
167     //}
168 william 598 ///// <summary>
169     ///// ProcessMemoryReader is a class that enables direct reading a process memory
170     ///// </summary>
171     //private class ProcessMemoryReaderApi
172 william 599 ////{
173     //[DllImport("kernel32.dll")]
174     //public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);
175 william 88
176 william 598 // // function declarations are found in the MSDN and in <winbase.h>
177 william 88
178 william 598 // // HANDLE OpenProcess(
179     // // DWORD dwDesiredAccess, // access flag
180     // // BOOL bInheritHandle, // handle inheritance option
181     // // DWORD dwProcessId // process identifier
182     // // );
183     // [DllImport("kernel32.dll")]
184     // public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
185 william 88
186 william 598 // // BOOL CloseHandle(
187     // // HANDLE hObject // handle to object
188     // // );
189     // [DllImport("kernel32.dll")]
190     // public static extern Int32 CloseHandle(IntPtr hObject);
191 william 88
192 william 598 // // BOOL ReadProcessMemory(
193     // // HANDLE hProcess, // handle to the process
194     // // LPCVOID lpBaseAddress, // base of memory area
195     // // LPVOID lpBuffer, // data buffer
196     // // SIZE_T nSize, // number of bytes to read
197     // // SIZE_T * lpNumberOfBytesRead // number of bytes read
198     // // );
199     // [DllImport("kernel32.dll", SetLastError = true)]
200     // public static extern bool ReadProcessMemory(
201     // IntPtr hProcess,
202     // IntPtr lpBaseAddress,
203     // [Out] byte[] lpBuffer,
204     // uint dwSize,
205     // out int lpNumberOfBytesRead
206     // );
207 william 88
208 william 598 // // BOOL WriteProcessMemory(
209     // // HANDLE hProcess, // handle to process
210     // // LPVOID lpBaseAddress, // base of memory area
211     // // LPCVOID lpBuffer, // data buffer
212     // // SIZE_T nSize, // count of bytes to write
213     // // SIZE_T * lpNumberOfBytesWritten // count of bytes written
214     // // );
215     // [DllImport("kernel32.dll", SetLastError = true)]
216     // public static extern bool WriteProcessMemory(
217     // IntPtr hProcess,
218     // IntPtr lpBaseAddress,
219     // byte[] lpBuffer,
220     // uint nSize,
221     // out UIntPtr lpNumberOfBytesWritten);
222 william 88
223    
224 william 598 //}
225 william 231
226     #region IMemoryReader Members
227 william 249 #region public bool ReadFirstNonZeroByte(uint MemoryAddress, uint bytesToRead, out int address)
228 william 578 public bool ReadFirstNonZeroByte(ulong MemoryAddress, ulong bytesToRead, out ulong address)
229 william 231 {
230     //logger.Info.WriteLine("Dumping memory (0x{0:x8}-0x{1:x8}) from pid=({2})", MemoryAddress, MemoryAddress + bytesToRead, string.Format("0x{0:x4} {1}.exe", ppid.Id, ppid.ProcessName));
231     address = 0;
232 william 235 uint byte_alignment = 1;
233 william 231 // get common init parameters
234     //InitMemoryDump(out byte_alignment);
235 william 576 ulong mem_address = MemoryAddress;
236 william 578 ulong _bytesToRead = bytesToRead;
237 william 231 byte[] buffer = new byte[] { };
238     try
239     {
240     //using (MemoryStream ms = new MemoryStream())
241     //{
242     // //BinaryWriter bw = new BinaryWriter(ms);
243     // //foreach (byte b in data) { bw.Write(b); }
244 william 578 for (ulong i = 0; i <= bytesToRead; )
245 william 231 {
246     if (_bytesToRead < byte_alignment)
247     {
248     _bytesToRead = bytesToRead;
249     buffer = new byte[_bytesToRead];
250     }
251     else
252     {
253     _bytesToRead = byte_alignment;
254     buffer = new byte[byte_alignment];
255     }
256 william 578 ulong bytesRead = 0;
257 william 231 ReadProcessMemory(mem_address, _bytesToRead, out bytesRead, out buffer);
258 william 245 if (buffer.Length == 0 && bytesRead == 0)
259     {
260 william 477 throw new Exception(string.Format("Failed to read memory from process: {0}", ReadProcess.ToString()));
261 william 245 }
262 william 231 //bw.Write(buffer);
263     //bw.Flush();
264     if (_bytesToRead < byte_alignment)
265     {
266     i += _bytesToRead;
267 william 576 mem_address += (ulong)_bytesToRead;
268 william 231 }
269     else
270     {
271     i += byte_alignment;
272 william 576 mem_address += (ulong)byte_alignment;
273 william 231 }
274     for (uint j = 0; j < buffer.Length; j++)
275     {
276     if (buffer[j] != 0)
277     {
278     address = mem_address;
279     break;
280     }
281     }
282     if (address != 0)
283     break;
284     }
285     // bw.Close();
286     //}
287     //logger.Info.WriteLine("Succefully dumped memory (0x{0:x8}-0x{1:x8}) from pid=({2})", MemoryAddress, MemoryAddress + bytesToRead, string.Format("0x{0:x4} {1}.exe", ppid.Id, ppid.ProcessName));
288     return true;
289     }
290 william 247 catch (SEHException ex)
291     {
292     logger.Error.WriteLine("ReadFirstNonZeroByte() SEHException was thrown: (0x{0:x8}) - {1}", ex.ErrorCode, ex.Message);
293     logger.Error.WriteLine(ex.ToString());
294     throw ex;
295     }
296 william 231 catch (OutOfMemoryException ex)
297     {
298 william 247 logger.Error.WriteLine("ReadFirstNonZeroByte(): OutOfMemoryException");
299 william 231 logger.Error.WriteLine(ex.ToString());
300     }
301     catch (Exception ex)
302     {
303 william 247 logger.Error.WriteLine("ReadFirstNonZeroByte(): Exception");
304 william 231 logger.Error.WriteLine(ex.ToString());
305 william 247 throw ex;
306 william 231 }
307     return false;
308     }
309 william 249 #endregion
310 william 404
311 william 543
312 william 600 public List<MEMORY_REGION_INFORMATION> QueryMemoryRegions(ulong start, ulong size)
313 william 599 {
314 william 600 List<MEMORY_REGION_INFORMATION> regions = new List<MEMORY_REGION_INFORMATION>();
315     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)0, 0))
316 william 599 {
317 william 600 regions = mem.QueryMemoryRegions(start, size);
318 william 599 }
319 william 600 return regions;
320 william 599 }
321    
322 william 578 public void UpdateAddressArray(ulong[] addresses, ulong size, out byte[][] values)
323 william 543 {
324     // size = size of data to read at each address
325     values = new byte[addresses.Length][];
326     for (int x = 0; x < values.Length; x++) { values[x] = new byte[size]; }
327 william 578
328     for (ulong i = 0; i < (ulong)addresses.Length; i++)
329 william 543 {
330     byte[] data = new byte[size];
331 william 578 ulong bytesRead = 0;
332 william 543 var address = addresses[i];
333     this.ReadProcessMemory(address, size, out bytesRead, out data);
334     values[i] = data;
335     }
336     }
337    
338    
339 william 578 public void ReadProcessMemoryAtOnce(ulong MemoryAddress, ulong bytesToRead, object UserState)
340 william 408 {
341 william 521 uint size = 128;
342 william 518 //int count = 0;
343 william 575 for (ulong j = MemoryAddress; j < (MemoryAddress + bytesToRead); j += size)
344 william 408 {
345 william 477 using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)j, (int)size))
346 william 409 {
347 william 477 byte[] bigMem = mem.Read();
348 william 518 //count += bigMem.Length;
349 william 477 if (this.OnBytesRead != null)
350 william 446 {
351 william 477 OnBytesReadEventArgs t = new OnBytesReadEventArgs(this, UserState, bigMem, j, bytesToRead);
352     this.OnBytesRead.Invoke(t);
353     if (t.Canceled)
354 william 446 {
355 william 477 bigMem = null;
356     break;
357 william 446 }
358 william 477
359 william 446 }
360 william 477 bigMem = null;
361 william 409 }
362 william 408 }
363     }
364 william 578 public void ReadProcessMemoryAtOnce(ulong MemoryAddress, ulong bytesToRead, out ulong bytesRead, out byte[] data)
365 william 354 {
366 william 477 Stopwatch st = new Stopwatch();
367     st.Start();
368     List<byte> buffer_list = new List<byte>();
369     //for (uint j = MemoryAddress; j < (MemoryAddress+bytesToRead); j += size)
370     //{
371     // using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)j, (int)bytesToRead))
372     // {
373     // byte[] bigMem = mem.Read();
374     // foreach (byte b in bigMem) { buffer_list.Add(b); }
375     // bigMem = null;
376     // }
377     //}
378    
379     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)MemoryAddress, (int)bytesToRead))
380 william 471 {
381 william 477 byte[] bigMem = mem.Read();
382     foreach (byte b in bigMem) { buffer_list.Add(b); }
383     bigMem = null;
384     }
385 william 425
386 william 578 bytesRead = (ulong)buffer_list.Count;
387 william 477 data = new byte[bytesToRead];
388     data.Initialize();
389     Buffer.BlockCopy(buffer_list.ToArray(), 0, data, 0, (int)bytesToRead);
390     st.Stop();
391     logger.Profiler.WriteLine("ReadProcessMemoryAtOnce(): start=0x{0:x8} end=0x{1:x8} took {2:0.0000} seconds", MemoryAddress, MemoryAddress + bytesToRead, st.Elapsed.TotalSeconds);
392 william 354 }
393 william 404 #region public void ReadProcessMemory(int MemoryAddress, uint bytesToRead, out int bytesRead, out byte[] data)
394 william 578 public void ReadProcessMemory(long MemoryAddress, long bytesToRead, out ulong bytesRead, out byte[] data)
395 william 231 {
396 william 578 ReadProcessMemory((ulong)MemoryAddress, (ulong)bytesToRead, out bytesRead, out data);
397 william 350 }
398 william 578 public void ReadProcessMemory(ulong MemoryAddress, ulong bytesToRead, out ulong bytesRead, out byte[] data)
399 william 350 {
400 william 247 try
401     {
402 william 425 ReadProcessMemoryAtOnce(MemoryAddress, bytesToRead, out bytesRead, out data);
403     //bytesRead = 0;
404     //data = new byte[bytesToRead];
405     //const int alignment = 1;
406     //List<byte> buffer_list = new List<byte>();
407     //uint _MemoryAddress = MemoryAddress;
408     //for (int i = 0; i < bytesToRead; i++)
409     //{
410     // byte[] buffer = new byte[alignment];
411     // int _bytesRead = 0;
412     // MEMORY_BASIC_INFORMATION m;
413     // ProcessMemoryReaderApi.VirtualQueryEx(m_ReadProcess.Handle, (IntPtr)_MemoryAddress, out m, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)));
414 william 404
415 william 425 // if (m.AllocationProtect.HasFlag(AllocationProtect.PAGE_NOACCESS) ||
416     // m.AllocationProtect == 0)
417     // {
418     // uint OrignalAddress = _MemoryAddress;
419     // while (m.AllocationProtect.HasFlag(AllocationProtect.PAGE_NOACCESS) || m.AllocationProtect == 0)
420     // {
421     // ProcessMemoryReaderApi.VirtualQueryEx(m_ReadProcess.Handle, (IntPtr)_MemoryAddress, out m, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)));
422     // _MemoryAddress++;
423     // buffer_list.Add(0);
424     // }
425     // _MemoryAddress--;
426     // uint diff = _MemoryAddress - OrignalAddress;
427     // i += (int)diff;
428     // buffer_list.RemoveAt(buffer_list.Count-1);
429     // }
430 william 404
431 william 425 // ProcessMemoryReader.ProcessMemoryReaderApi.ReadProcessMemory(handle, (IntPtr)_MemoryAddress, buffer, alignment, out _bytesRead);
432     // int LastError = Marshal.GetLastWin32Error();
433     // if (LastError != ResultWin32.ERROR_SUCCESS)
434     // {
435     // string ErrorName = ResultWin32.GetErrorName(LastError);
436     // }
437     // if (_bytesRead > 0)
438     // {
439     // foreach (byte b in buffer)
440     // {
441     // buffer_list.Add(b);
442     // }
443     // _MemoryAddress += (uint)buffer.Length;
444     // }
445     //}
446     //bytesRead = buffer_list.Count;
447     //Buffer.BlockCopy(buffer_list.ToArray(), 0, data, 0, (int)bytesToRead);
448 william 247 }
449     catch (SEHException ex)
450     {
451     logger.Error.WriteLine("ReadProcessMemory() SEHException was thrown: (0x{0:x8}) - {1}", ex.ErrorCode, ex.Message);
452     logger.Error.WriteLine(ex.ToString());
453     throw ex;
454     }
455     catch (Exception ex)
456     {
457     logger.Error.WriteLine("ReadProcessMemory(): Exception");
458     logger.Error.WriteLine(ex.ToString());
459     throw ex;
460     }
461 william 231 }
462     #endregion
463 william 249 #endregion
464 william 231
465     #region IMemoryWriter Members
466 william 249 #region public void WriteProcessMemory(uint MemoryAddress, byte[] bytesToWrite, out int bytesWritten)
467 william 578 public void WriteProcessMemory(long MemoryAddress, byte[] bytesToWrite, out ulong bytesWritten)
468 william 231 {
469 william 578 ulong _bytesWritten = 0;
470 william 575 WriteProcessMemory((ulong)MemoryAddress, bytesToWrite, out _bytesWritten);
471 william 578 bytesWritten = (ulong)_bytesWritten;
472 william 350 }
473 william 578 public void WriteProcessMemory(ulong MemoryAddress, byte[] bytesToWrite, out ulong bytesWritten)
474 william 350 {
475 william 247 try
476     {
477 william 477 //uint _bytesWritten = 0;
478 william 575 ulong _MemoryAddress = MemoryAddress;
479 william 477
480     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)MemoryAddress, bytesToWrite.Length))
481 william 471 {
482 william 477 mem.Write(0, bytesToWrite);
483     }
484 william 428
485 william 477 //for (int i = 0; i < bytesToWrite.Length; i++)
486     //{
487     // UIntPtr _ptrBytesWritten = UIntPtr.Zero;
488     // byte[] buffer = new byte[] { bytesToWrite[i] };
489     // ProcessMemoryReaderApi.WriteProcessMemory(handle, (IntPtr)_MemoryAddress, buffer, (uint)buffer.Length, out _ptrBytesWritten);
490     // _MemoryAddress++;
491     // _bytesWritten++;
492     //}
493     //bytesWritten = _bytesWritten;
494     bytesWritten = (uint)bytesToWrite.Length;
495 william 247 }
496     catch (SEHException ex)
497     {
498     logger.Error.WriteLine("WriteProcessMemory() SEHException was thrown: (0x{0:x8}) - {1}", ex.ErrorCode, ex.Message);
499     logger.Error.WriteLine(ex.ToString());
500     throw ex;
501     }
502     catch (Exception ex)
503     {
504    
505     logger.Error.WriteLine("WriteProcessMemory() Exception");
506     logger.Error.WriteLine(ex.ToString());
507     bytesWritten = 0;
508     throw ex;
509     }
510 william 231 }
511 william 249 #endregion
512 william 231 #endregion
513    
514     #region IFileWriter Members
515 william 249 #region public bool WriteProcessMemoryToFile(string filename, uint MemoryAddress, uint bytesToRead, out int bytesRead)
516 william 578 public bool WriteProcessMemoryToFile(string filename, ulong MemoryAddress, ulong bytesToRead, out ulong bytesRead)
517 william 231 {
518     //logger.Info.WriteLine("Dumping memory (0x{0:x8}-0x{1:x8}) from pid=({3}) to file {2}", MemoryAddress, MemoryAddress + bytesToRead, filename, string.Format("0x{0:x4} {1}.exe", ppid.Id, ppid.ProcessName));
519     bytesRead = 0;
520 william 235 uint byte_alignment = 102400;
521 william 575 ulong address = MemoryAddress;
522 william 578 ulong _bytesToRead = bytesToRead;
523 william 231 byte[] buffer = new byte[] { };
524     try
525     {
526     FileInfo fi = new FileInfo(filename);
527     if (fi.Exists)
528     fi.Delete();
529     using (FileStream fs = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
530     {
531     BinaryWriter bw = new BinaryWriter(fs);
532     //foreach (byte b in data) { bw.Write(b); }
533    
534 william 578 for (ulong i = 0; i <= bytesToRead; )
535 william 231 {
536     if (_bytesToRead < byte_alignment)
537     {
538     _bytesToRead = bytesToRead;
539     buffer = new byte[_bytesToRead];
540     }
541     else
542     {
543     _bytesToRead = byte_alignment;
544     buffer = new byte[byte_alignment];
545     }
546 william 404 ReadProcessMemory(address, _bytesToRead, out bytesRead, out buffer);
547 william 231 bw.Write(buffer);
548     bw.Flush();
549    
550     if (_bytesToRead < byte_alignment)
551     {
552     i += _bytesToRead;
553 william 575 address += (ulong)_bytesToRead;
554 william 231 }
555     else
556     {
557     i += byte_alignment;
558 william 575 address += (ulong)byte_alignment;
559 william 231 }
560    
561    
562     }
563     bw.Close();
564     }
565 william 477 logger.Info.WriteLine("Succefully dumped memory (0x{0:x8}-0x{1:x8}) from pid=({3}) to file {2}", MemoryAddress, MemoryAddress + bytesToRead, filename, string.Format("0x{0:x4} {1}.exe", ReadProcess.Id, ReadProcess.ProcessName));
566 william 231 return true;
567     }
568 william 247 catch (SEHException ex)
569     {
570     logger.Error.WriteLine("WriteProcessMemoryToFile() SEHException was thrown: (0x{0:x8}) - {1}", ex.ErrorCode, ex.Message);
571     logger.Error.WriteLine(ex.ToString());
572     throw ex;
573     }
574 william 231 catch (OutOfMemoryException ex)
575     {
576 william 247 logger.Error.WriteLine("WriteProcessMemoryToFile(): Exception");
577 william 231 logger.Error.WriteLine(ex.ToString());
578     }
579     catch (Exception ex)
580     {
581 william 247 logger.Error.WriteLine("WriteProcessMemoryToFile(): Exception");
582 william 231 logger.Error.WriteLine(ex.ToString());
583 william 247 throw ex;
584 william 231 }
585     return false;
586     }
587     #endregion
588 william 249 #endregion
589 william 370
590     #region IPatchMemory members
591 william 378 #region public virtual bool PatchMemory(uint address, byte value)
592 william 575 public virtual bool PatchMemory(ulong address, byte value)
593 william 370 {
594 william 477 byte[] bitData = BitConverter.GetBytes(value);
595     //UIntPtr ptrBytesWritten;
596     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, bitData.Length))
597 william 428 {
598 william 477 mem.Write(0, bitData);
599 william 428 }
600     //ProcessMemoryReaderApi.WriteProcessMemory(handle, (IntPtr)address, bitData, (uint)bitData.Length, out ptrBytesWritten);
601     //if (ptrBytesWritten.ToUInt32() == 0)
602     // return false;
603 william 370 byte check = 0;
604     ReadMemory(address, out check);
605     if (check == value) return true;
606     return false;
607     }
608     #endregion
609 william 378 #region public virtual bool PatchMemory(uint address, sbyte value)
610 william 575 public virtual bool PatchMemory(ulong address, sbyte value)
611 william 370 {
612 william 477 byte[] bitData = BitConverter.GetBytes(value);
613     //UIntPtr ptrBytesWritten;
614     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, bitData.Length))
615 william 428 {
616 william 477 mem.Write(0, bitData);
617 william 428 }
618     //ProcessMemoryReaderApi.WriteProcessMemory(handle, (IntPtr)address, bitData, (uint)bitData.Length, out ptrBytesWritten);
619     //if (ptrBytesWritten.ToUInt32() == 0)
620     // return false;
621 william 370 sbyte check = 0;
622     ReadMemory(address, out check);
623     if (check == value) return true;
624     return false;
625     }
626     #endregion
627 william 378 #region public virtual bool PatchMemory(uint address, ushort value)
628 william 575 public virtual bool PatchMemory(ulong address, ushort value)
629 william 370 {
630 william 477 byte[] bitData = BitConverter.GetBytes(value);
631     //UIntPtr ptrBytesWritten;
632     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, bitData.Length))
633 william 428 {
634 william 477 mem.Write(0, bitData);
635 william 428 }
636     //if (ptrBytesWritten.ToUInt32() == 0)
637     // return false;
638 william 370 ushort check = 0;
639     ReadMemory(address, out check);
640     if (check == value) return true;
641     return false;
642     }
643     #endregion
644 william 378 #region public virtual bool PatchMemory(uint address, short value)
645 william 575 public virtual bool PatchMemory(ulong address, short value)
646 william 477 {
647     byte[] bitData = BitConverter.GetBytes(value);
648     //UIntPtr ptrBytesWritten;
649     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, bitData.Length))
650 william 428 {
651 william 477 mem.Write(0, bitData);
652 william 428 }
653     //if (ptrBytesWritten.ToUInt32() == 0)
654     // return false;
655 william 370 short check = 0;
656     ReadMemory(address, out check);
657     if (check == value) return true;
658     return false;
659     }
660     #endregion
661 william 378 #region public virtual bool PatchMemory(uint address, uint value)
662 william 575 public virtual bool PatchMemory(ulong address, uint value)
663 william 370 {
664 william 477 byte[] bitData = BitConverter.GetBytes(value);
665     //UIntPtr ptrBytesWritten;
666     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, bitData.Length))
667 william 428 {
668 william 477 mem.Write(0, bitData);
669 william 428 }
670     //if (ptrBytesWritten.ToUInt32() == 0)
671     // return false;
672 william 370 uint check = 0;
673     ReadMemory(address, out check);
674     if (check == value) return true;
675     return false;
676     }
677     #endregion
678 william 378 #region public virtual bool PatchMemory(uint address, int value)
679 william 575 public virtual bool PatchMemory(ulong address, int value)
680 william 370 {
681 william 477 byte[] bitData = BitConverter.GetBytes(value);
682     //UIntPtr ptrBytesWritten;
683     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, bitData.Length))
684 william 428 {
685 william 477 mem.Write(0, bitData);
686 william 428 }
687     //if (ptrBytesWritten.ToUInt32() == 0)
688     // return false;
689 william 370 int check = 0;
690     ReadMemory(address, out check);
691     if (check == value) return true;
692     return false;
693     }
694     #endregion
695 william 378 #region public virtual bool PatchMemory(uint address, ulong value)
696 william 575 public virtual bool PatchMemory(ulong address, ulong value)
697 william 370 {
698 william 477 byte[] bitData = BitConverter.GetBytes(value);
699     //UIntPtr ptrBytesWritten;
700     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, bitData.Length))
701 william 428 {
702 william 477 mem.Write(0, bitData);
703 william 428 }
704     //if (ptrBytesWritten.ToUInt32() == 0)
705     // return false;
706 william 370 ulong check = 0;
707     ReadMemory(address, out check);
708     if (check == value) return true;
709     return false;
710     }
711     #endregion
712 william 378 #region public virtual bool PatchMemory(uint address, long value)
713 william 575 public virtual bool PatchMemory(ulong address, long value)
714 william 370 {
715 william 477 byte[] bitData = BitConverter.GetBytes(value);
716     //UIntPtr ptrBytesWritten;
717     using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, bitData.Length))
718 william 428 {
719 william 477 mem.Write(0, bitData);
720 william 428 }
721     //if (ptrBytesWritten.ToUInt32() == 0)
722     // return false;
723 william 370 long check = 0;
724     ReadMemory(address, out check);
725     if (check == value) return true;
726     return false;
727     }
728     #endregion
729     #endregion
730    
731     #region IReadMemory members
732 william 378 #region public virtual bool ReadMemory(uint address, out byte value)
733 william 575 public virtual bool ReadMemory(ulong address, out byte value)
734 william 370 {
735     value = 0;
736     try
737     {
738 william 428 //int bytesRead;
739 william 370 uint size = sizeof(byte);
740     byte[] bitData = new byte[size];
741 william 477 using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, (int)size))
742 william 428 {
743 william 493 bitData = mem.Read(0, (int)size);
744 william 477 }
745 william 428 //if (bytesRead == 0)
746     // return false;
747 william 370 value = bitData[0];
748     return true;
749     }
750     catch
751     {
752     value = 0x00;
753     return false;
754     }
755     }
756     #endregion
757 william 378 #region public virtual bool ReadMemory(uint address, out sbyte value)
758 william 575 public virtual bool ReadMemory(ulong address, out sbyte value)
759 william 370 {
760     value = 0;
761     try
762     {
763 william 428 //int bytesRead;
764 william 370 uint size = sizeof(sbyte);
765     byte[] bitData = new byte[size];
766 william 477 using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, (int)size))
767 william 428 {
768 william 493 bitData = mem.Read(0, (int)size);
769 william 477 }
770 william 428 //if (bytesRead == 0)
771     // return false;
772 william 370 value = Convert.ToSByte(bitData[0]);
773     return true;
774     }
775     catch
776     {
777     value = 0x00;
778     return false;
779     }
780     }
781     #endregion
782 william 378 #region public virtual bool ReadMemory(uint address, out ushort value)
783 william 575 public virtual bool ReadMemory(ulong address, out ushort value)
784 william 370 {
785     value = 0;
786     try
787     {
788 william 428 //int bytesRead;
789 william 370 uint size = sizeof(ushort);
790     byte[] bitData = new byte[size];
791 william 477 using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, (int)size))
792 william 428 {
793 william 493 bitData = mem.Read(0, (int)size);
794 william 477 }
795 william 428 //if (bytesRead == 0)
796     // return false;
797 william 370 value = BitConverter.ToUInt16(bitData, 0);
798     return true;
799     }
800     catch
801     {
802     value = 0x00;
803     return false;
804     }
805     }
806     #endregion
807 william 378 #region public virtual bool ReadMemory(uint address, out short value)
808 william 575 public virtual bool ReadMemory(ulong address, out short value)
809 william 370 {
810     value = 0;
811     try
812     {
813 william 428 //int bytesRead;
814 william 370 uint size = sizeof(short);
815     byte[] bitData = new byte[size];
816 william 477 using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, (int)size))
817 william 428 {
818 william 493 bitData = mem.Read(0, (int)size);
819 william 477 }
820 william 428 //if (bytesRead == 0)
821     // return false;
822 william 370 value = BitConverter.ToInt16(bitData, 0);
823     return true;
824     }
825     catch
826     {
827     value = 0x00;
828     return false;
829     }
830     }
831     #endregion
832 william 378 #region public virtual bool ReadMemory(uint address, out uint value)
833 william 575 public virtual bool ReadMemory(ulong address, out uint value)
834 william 370 {
835     value = 0;
836     try
837     {
838 william 428 //int bytesRead;
839 william 370 uint size = sizeof(uint);
840     byte[] bitData = new byte[size];
841 william 477 using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, (int)size))
842 william 428 {
843 william 493 bitData = mem.Read(0, (int)size);
844 william 477 }
845 william 428 //if (bytesRead == 0)
846     // return false;
847 william 370 value = BitConverter.ToUInt32(bitData, 0);
848     return true;
849     }
850     catch
851     {
852     value = 0x00;
853     return false;
854     }
855     }
856     #endregion
857 william 378 #region public virtual bool ReadMemory(uint address, out int value)
858 william 575 public virtual bool ReadMemory(ulong address, out int value)
859 william 370 {
860     value = 0;
861     try
862     {
863 william 428 //int bytesRead;
864 william 370 uint size = sizeof(int);
865     byte[] bitData = new byte[size];
866 william 477 using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, (int)size))
867 william 428 {
868 william 493 bitData = mem.Read(0, (int)size);
869 william 477 }
870 william 428 //if (bytesRead == 0)
871     // return false;
872 william 370 value = BitConverter.ToInt32(bitData, 0);
873     return true;
874     }
875     catch
876     {
877     value = 0x00;
878     return false;
879     }
880     }
881     #endregion
882 william 378 #region public virtual bool ReadMemory(uint address, out ulong value)
883 william 575 public virtual bool ReadMemory(ulong address, out ulong value)
884 william 370 {
885     value = 0;
886     try
887     {
888 william 428 //int bytesRead;
889 william 370 uint size = sizeof(ulong);
890     byte[] bitData = new byte[size];
891 william 477 using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, (int)size))
892 william 428 {
893 william 493 bitData = mem.Read(0, (int)size);
894 william 477 }
895 william 428 //if (bytesRead == 0)
896     // return false;
897 william 370 value = BitConverter.ToUInt64(bitData, 0);
898     return true;
899     }
900     catch
901     {
902     value = 0x00;
903     return false;
904     }
905     }
906     #endregion
907 william 378 #region public virtual bool ReadMemory(uint address, out long value)
908 william 575 public virtual bool ReadMemory(ulong address, out long value)
909 william 370 {
910     value = 0;
911     try
912     {
913 william 428 // int bytesRead;
914 william 370 uint size = sizeof(long);
915     byte[] bitData = new byte[size];
916 william 477 using (ProcessMemoryChunk mem = new ProcessMemoryChunk(m_ReadProcess, (IntPtr)address, (int)size))
917 william 428 {
918 william 493 bitData = mem.Read(0, (int)size);
919 william 477 }
920 william 428 //if (bytesRead == 0)
921     // return false;
922 william 370 value = BitConverter.ToInt64(bitData, 0);
923     return true;
924     }
925     catch
926     {
927     value = 0x00;
928     return false;
929     }
930     }
931     #endregion
932     #endregion
933 william 88 }
934     #endregion
935     }

  ViewVC Help
Powered by ViewVC 1.1.22