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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

--- trunk/Win32/Sojaner.MemoryScanner/MemoryScanner.cs	2012/05/28 07:49:48	164
+++ trunk/Win32/Sojaner.MemoryScanner/MemoryScanner.cs	2012/06/03 14:50:09	245
@@ -5,8 +5,8 @@
 using System.Threading;
 using System.Runtime.InteropServices;
 using RomCheater.Logging;
-using RomCheater.Core;
 using System.IO;
+using Sojaner.MemoryScanner.MemoryProviers;
 
 namespace Sojaner.MemoryScanner
 {
@@ -14,7 +14,7 @@
     #region ProcessMemoryReader class
     //Thanks goes to Arik Poznanski for P/Invokes and methods needed to read and write the Memory
     //For more information refer to "Minesweeper, Behind the scenes" article by Arik Poznanski at Codeproject.com
-    public class ProcessMemoryReader
+    internal class ProcessMemoryReader : IMemoryReader, IMemoryWriter, IFileWriter
     {
 
         public ProcessMemoryReader()
@@ -38,7 +38,7 @@
 
         private Process m_ReadProcess = null;
 
-        private IntPtr m_hProcess = IntPtr.Zero;
+        private static IntPtr m_hProcess = IntPtr.Zero;
 
         public void OpenProcess()
         {
@@ -61,106 +61,20 @@
                     throw new Exception("CloseHandle failed");
                 }
             }
-            catch (Exception ex)
+            catch (SEHException ex)
             {
-                //System.Windows.Forms.MessageBox.Show(ex.Message, "error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                 throw ex;
             }
-        }
-
-
-        public bool DumpMemory(string filename, uint MemoryAddress, uint bytesToRead, out int bytesRead)
-        {
-            bytesRead = 0;
-            uint byte_alignment = 16; // 16 byte alignment
-            uint address = MemoryAddress;
-            try
-            {
-                using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
-                {
-                    BinaryWriter bw = new BinaryWriter(fs);
-                    //foreach (byte b in data) { bw.Write(b); }
-
-                    for (uint i = 0; i <= bytesToRead; i += byte_alignment)
-                    {
-                        byte[] buffer = new byte[byte_alignment];
-                        uint bytes_to_read = byte_alignment;
-                        IntPtr ptrBytesRead;
-                        ProcessMemoryReaderApi.ReadProcessMemory(m_hProcess, (UIntPtr)address, buffer, bytes_to_read, out ptrBytesRead);
-                        bytesRead = ptrBytesRead.ToInt32();
-                        bw.Write(buffer);
-                        bw.Flush();
-                        address += byte_alignment;
-                    }
-                    bw.Close();
-                }
-                return true;
-            }
-            catch (OutOfMemoryException ex)
-            {
-                logger.Error.WriteLine("DumpMemory(): OutOfMemoryException");
-                logger.Error.WriteLine(ex.ToString());
-            }
             catch (Exception ex)
             {
-                logger.Error.WriteLine("DumpMemory(): Exception");
-                logger.Error.WriteLine(ex.ToString());
-            }
-            return false;
-        }
-
-        public byte[] ReadProcessMemory(uint MemoryAddress, uint bytesToRead, out int bytesRead)
-        {
-            bytesRead = 0;
-            uint address = MemoryAddress;
-            List<byte[]> aligned_array_list = new List<byte[]>();
-            try
-            {
-                uint byte_alignment = 512; // 4mb alignment
-               
-
-                for (uint i = 0; i <= bytesToRead; i += byte_alignment)
-                {
-                    byte[] buffer = new byte[byte_alignment];
-                    uint bytes_to_read = byte_alignment;
-                    IntPtr ptrBytesRead;
-                    ProcessMemoryReaderApi.ReadProcessMemory(m_hProcess, (UIntPtr)address, buffer, bytes_to_read, out ptrBytesRead);
-                    bytesRead = ptrBytesRead.ToInt32();
-                    aligned_array_list.Add(buffer);                    
-                    address += byte_alignment;
-                }
-
-                //List<byte> big_array = new List<byte>();
-                //foreach (byte[] aligned_array in aligned_array_list) { foreach (byte b in aligned_array) { big_array.Add(b); } }
-
-                return new byte[] { };
-            }
-            catch (OutOfMemoryException ex)
-            {
-                logger.Error.WriteLine("ReadProcessMemory(): OutOfMemoryException");
-                logger.Error.WriteLine(ex.ToString());
-            }
-            catch (Exception ex)
-            {
-                logger.Error.WriteLine("ReadProcessMemory(): Exception");
-                logger.Error.WriteLine(ex.ToString());
+                //System.Windows.Forms.MessageBox.Show(ex.Message, "error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
+                throw ex;
             }
-            return new byte[] { };
         }
-
-        public void WriteProcessMemory(UIntPtr MemoryAddress, byte[] bytesToWrite, out int bytesWritten)
-        {
-            IntPtr ptrBytesWritten;
-            ProcessMemoryReaderApi.WriteProcessMemory(m_hProcess, MemoryAddress, bytesToWrite, (uint)bytesToWrite.Length, out ptrBytesWritten);
-
-            bytesWritten = ptrBytesWritten.ToInt32();
-        }
-
-
         /// <summary>
         /// ProcessMemoryReader is a class that enables direct reading a process memory
         /// </summary>
-        class ProcessMemoryReaderApi
+        private class ProcessMemoryReaderApi
         {
             // constants information can be found in <winnt.h>
             [Flags]
@@ -203,7 +117,7 @@
             //			SIZE_T * lpNumberOfBytesRead  // number of bytes read
             //			);
             [DllImport("kernel32.dll")]
-            public static extern Int32 ReadProcessMemory(IntPtr hProcess, UIntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesRead);
+            public static extern Int32 ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesRead);
 
             //		BOOL WriteProcessMemory(
             //			HANDLE hProcess,                // handle to process
@@ -213,10 +127,181 @@
             //			SIZE_T * lpNumberOfBytesWritten // count of bytes written
             //			);
             [DllImport("kernel32.dll")]
-            public static extern Int32 WriteProcessMemory(IntPtr hProcess, UIntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesWritten);
+            public static extern Int32 WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesWritten);
 
 
         }
+
+        #region IMemoryReader Members
+        public bool ReadFirstNonZeroByte(uint MemoryAddress, uint bytesToRead, out uint address)
+        {
+            //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));
+            address = 0;
+            uint byte_alignment = 1;
+            // get common init parameters
+            //InitMemoryDump(out byte_alignment);
+            uint mem_address = MemoryAddress;
+            uint _bytesToRead = bytesToRead;
+            byte[] buffer = new byte[] { };
+            try
+            {
+                //using (MemoryStream ms = new MemoryStream())
+                //{
+                //    //BinaryWriter bw = new BinaryWriter(ms);
+                //    //foreach (byte b in data) { bw.Write(b); }
+                for (uint i = 0; i <= bytesToRead; )
+                {
+                    if (_bytesToRead < byte_alignment)
+                    {
+                        _bytesToRead = bytesToRead;
+                        buffer = new byte[_bytesToRead];
+                    }
+                    else
+                    {
+                        _bytesToRead = byte_alignment;
+                        buffer = new byte[byte_alignment];
+                    }
+                    int bytesRead = 0;
+                    ReadProcessMemory(mem_address, _bytesToRead, out bytesRead, out buffer);
+                    if (buffer.Length == 0 && bytesRead == 0)
+                    {
+                        throw new Exception(string.Format("Failed to read memory from process: {0}", ReadProcess.ToString()));
+                    }
+                    //bw.Write(buffer);
+                    //bw.Flush();
+                    if (_bytesToRead < byte_alignment)
+                    {
+                        i += _bytesToRead;
+                        mem_address += (uint)_bytesToRead;
+                    }
+                    else
+                    {
+                        i += byte_alignment;
+                        mem_address += (uint)byte_alignment;
+                    }
+                    for (uint j = 0; j < buffer.Length; j++)
+                    {
+                        if (buffer[j] != 0)
+                        {
+                            address = mem_address;
+                            break;
+                        }
+                    }
+                    if (address != 0)
+                        break;
+                }
+                //    bw.Close();
+                //}
+                //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));
+                return true;
+            }
+            catch (OutOfMemoryException ex)
+            {
+                logger.Error.WriteLine("Failed to dump memory (0x{0:x8}-0x{1:x8}) from pid=({2})", MemoryAddress, MemoryAddress + bytesToRead, string.Format("0x{0:x4} {1}.exe", ReadProcess.Id, ReadProcess.ProcessName));
+                logger.Error.WriteLine("DumpMemory(): OutOfMemoryException");
+                logger.Error.WriteLine(ex.ToString());
+            }
+            catch (Exception ex)
+            {
+                logger.Error.WriteLine("Failed to dump memory (0x{0:x8}-0x{1:x8}) from pid=({2})", MemoryAddress, MemoryAddress + bytesToRead, string.Format("0x{0:x4} {1}.exe", ReadProcess.Id, ReadProcess.ProcessName));
+                logger.Error.WriteLine("DumpMemory(): Exception");
+                logger.Error.WriteLine(ex.ToString());
+            }
+            return false;
+        }
+        public void ReadProcessMemory(uint MemoryAddress, uint bytesToRead, out int bytesRead, out byte[] data)
+        {
+            byte[] buffer = new byte[] { };
+            IntPtr ptrBytesRead;
+            ProcessMemoryReader.ProcessMemoryReaderApi.ReadProcessMemory(m_hProcess, (IntPtr)MemoryAddress, buffer, bytesToRead, out ptrBytesRead);
+            bytesRead = ptrBytesRead.ToInt32();
+            data = buffer;
+        }
+        #endregion
+
+        #region IMemoryWriter Members
+        public void WriteProcessMemory(uint MemoryAddress, byte byteToWrite, out int bytesWritten)
+        {
+            WriteProcessMemory(MemoryAddress, new byte[] { byteToWrite }, out bytesWritten);
+        }
+        public void WriteProcessMemory(uint MemoryAddress, byte[] bytesToWrite, out int bytesWritten)
+        {
+            IntPtr ptrBytesWritten;
+            ProcessMemoryReaderApi.WriteProcessMemory(m_hProcess, (IntPtr)MemoryAddress, bytesToWrite, (uint)bytesToWrite.Length, out ptrBytesWritten);
+            bytesWritten = ptrBytesWritten.ToInt32();
+        }
+        #endregion
+
+        #region IFileWriter Members
+
+        public bool WriteProcessMemoryToFile(string filename, uint MemoryAddress, uint bytesToRead, out int bytesRead)
+        {
+            //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));
+            bytesRead = 0;
+            uint byte_alignment = 102400;
+            uint address = MemoryAddress;
+            uint _bytesToRead = bytesToRead;
+            byte[] buffer = new byte[] { };
+            try
+            {
+                FileInfo fi = new FileInfo(filename);
+                if (fi.Exists)
+                    fi.Delete();
+                using (FileStream fs = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
+                {
+                    BinaryWriter bw = new BinaryWriter(fs);
+                    //foreach (byte b in data) { bw.Write(b); }
+
+                    for (uint i = 0; i <= bytesToRead; )
+                    {
+                        if (_bytesToRead < byte_alignment)
+                        {
+                            _bytesToRead = bytesToRead;
+                            buffer = new byte[_bytesToRead];
+                        }
+                        else
+                        {
+                            _bytesToRead = byte_alignment;
+                            buffer = new byte[byte_alignment];
+                        }
+                        ReadProcessMemory(address, _bytesToRead, out bytesRead, out buffer);
+                        bw.Write(buffer);
+                        bw.Flush();
+
+                        if (_bytesToRead < byte_alignment)
+                        {
+                            i += _bytesToRead;
+                            address += (uint)_bytesToRead;
+                        }
+                        else
+                        {
+                            i += byte_alignment;
+                            address += (uint)byte_alignment;
+                        }
+
+
+                    }
+                    bw.Close();
+                }
+                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));
+                return true;
+            }
+            catch (OutOfMemoryException ex)
+            {
+                logger.Error.WriteLine("Failed to dump 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));
+                logger.Error.WriteLine("DumpMemory(): OutOfMemoryException");
+                logger.Error.WriteLine(ex.ToString());
+            }
+            catch (Exception ex)
+            {
+                logger.Error.WriteLine("Failed to dump 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));
+                logger.Error.WriteLine("DumpMemory(): Exception");
+                logger.Error.WriteLine(ex.ToString());
+            }
+            return false;
+        }
+
+        #endregion
     }
     #endregion
 }

 

  ViewVC Help
Powered by ViewVC 1.1.22