Advertisement
Mijyuoon

Crap Memory Reader

Jul 12th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.16 KB | None | 0 0
  1.     public static class Win32API {
  2.         public const int PROCESS_WM_READ = 0x0010;
  3.  
  4.         [DllImport("kernel32.dll", SetLastError = true)]
  5.         public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
  6.  
  7.         [DllImport("kernel32.dll", SetLastError = true)]
  8.         public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumRead);
  9.     }
  10.  
  11.     public class ProcessReader {
  12.         private IntPtr hProcess;
  13.         private uint lpBaseAddress;
  14.  
  15.         public ProcessReader(Process process) {
  16.             hProcess = Win32API.OpenProcess(Win32API.PROCESS_WM_READ, false, process.Id);
  17.             lpBaseAddress = (uint)process.MainModule.BaseAddress;
  18.  
  19.             if(hProcess == IntPtr.Zero) {
  20.                 throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to open process");
  21.             }
  22.         }
  23.  
  24.         private void ReadBytes(byte[] buffer, IntPtr address) {
  25.             int numRead = 0;
  26.             bool ok = Win32API.ReadProcessMemory(hProcess, address, buffer, buffer.Length, ref numRead);
  27.  
  28.             if(!ok || numRead != buffer.Length) {
  29.                 throw new Win32Exception(Marshal.GetLastWin32Error(), $"Failed to read {buffer.Length} bytes");
  30.             }
  31.         }
  32.  
  33.         private void ReadBytesPtrChain(byte[] buffer, uint[] offsets) {
  34.             if(offsets.Length < 1) {
  35.                 throw new ArgumentException("No offsets provided", nameof(offsets));
  36.             }
  37.  
  38.             byte[] ptrBuffer = new byte[4];
  39.             uint curPtr = lpBaseAddress;
  40.  
  41.             for(int i = 0; i < offsets.Length - 1; i++) {
  42.                 ReadBytes(ptrBuffer, (IntPtr)(curPtr + offsets[i]));
  43.                 curPtr = BitConverter.ToUInt32(ptrBuffer, 0);
  44.             }
  45.  
  46.             uint lastOffset = offsets[offsets.Length - 1];
  47.             ReadBytes(buffer, (IntPtr)(curPtr + lastOffset));
  48.         }
  49.  
  50.         public Int32 ReadInt32(params uint[] offsets) {
  51.             byte[] buffer = new byte[4];
  52.             ReadBytesPtrChain(buffer, offsets);
  53.             return BitConverter.ToInt32(buffer, 0);
  54.         }
  55.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement