Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class Win32API {
- public const int PROCESS_WM_READ = 0x0010;
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumRead);
- }
- public class ProcessReader {
- private IntPtr hProcess;
- private uint lpBaseAddress;
- public ProcessReader(Process process) {
- hProcess = Win32API.OpenProcess(Win32API.PROCESS_WM_READ, false, process.Id);
- lpBaseAddress = (uint)process.MainModule.BaseAddress;
- if(hProcess == IntPtr.Zero) {
- throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to open process");
- }
- }
- private void ReadBytes(byte[] buffer, IntPtr address) {
- int numRead = 0;
- bool ok = Win32API.ReadProcessMemory(hProcess, address, buffer, buffer.Length, ref numRead);
- if(!ok || numRead != buffer.Length) {
- throw new Win32Exception(Marshal.GetLastWin32Error(), $"Failed to read {buffer.Length} bytes");
- }
- }
- private void ReadBytesPtrChain(byte[] buffer, uint[] offsets) {
- if(offsets.Length < 1) {
- throw new ArgumentException("No offsets provided", nameof(offsets));
- }
- byte[] ptrBuffer = new byte[4];
- uint curPtr = lpBaseAddress;
- for(int i = 0; i < offsets.Length - 1; i++) {
- ReadBytes(ptrBuffer, (IntPtr)(curPtr + offsets[i]));
- curPtr = BitConverter.ToUInt32(ptrBuffer, 0);
- }
- uint lastOffset = offsets[offsets.Length - 1];
- ReadBytes(buffer, (IntPtr)(curPtr + lastOffset));
- }
- public Int32 ReadInt32(params uint[] offsets) {
- byte[] buffer = new byte[4];
- ReadBytesPtrChain(buffer, offsets);
- return BitConverter.ToInt32(buffer, 0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement