-
Notifications
You must be signed in to change notification settings - Fork 9
/
MemoryReader.cs
462 lines (424 loc) · 20.4 KB
/
MemoryReader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace LiveSplit.Celeste {
public static class MemoryReader {
private static Dictionary<int, Module64[]> ModuleCache = new Dictionary<int, Module64[]>();
public static bool is64Bit;
public static void Update64Bit(Process program) {
is64Bit = program.Is64Bit();
}
public static T Read<T>(this Process targetProcess, IntPtr address, params int[] offsets) where T : unmanaged {
if (targetProcess == null || address == IntPtr.Zero) { return default(T); }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return default(T); }
unsafe {
int size = sizeof(T);
if (typeof(T) == typeof(IntPtr)) { size = is64Bit ? 8 : 4; }
byte[] buffer = Read(targetProcess, address + last, size);
fixed (byte* ptr = buffer) {
return *(T*)ptr;
}
}
}
public static byte[] Read(this Process targetProcess, IntPtr address, int numBytes) {
byte[] buffer = new byte[numBytes];
if (targetProcess == null || address == IntPtr.Zero) { return buffer; }
int bytesRead;
WinAPI.ReadProcessMemory(targetProcess.Handle, address, buffer, numBytes, out bytesRead);
return buffer;
}
public static byte[] Read(this Process targetProcess, IntPtr address, int numBytes, params int[] offsets) {
byte[] buffer = new byte[numBytes];
if (targetProcess == null || address == IntPtr.Zero) { return buffer; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return buffer; }
int bytesRead;
WinAPI.ReadProcessMemory(targetProcess.Handle, address + last, buffer, numBytes, out bytesRead);
return buffer;
}
public static string ReadString(this Process targetProcess, IntPtr address) {
if (targetProcess == null || address == IntPtr.Zero) { return string.Empty; }
int length = Read<int>(targetProcess, address, 0x4);
if (length < 0 || length > 2048) { return string.Empty; }
return Encoding.Unicode.GetString(Read(targetProcess, address + 0x8, 2 * length));
}
public static string ReadString(this Process targetProcess, IntPtr address, params int[] offsets) {
if (targetProcess == null || address == IntPtr.Zero) { return string.Empty; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return string.Empty; }
return ReadString(targetProcess, address + last);
}
public static string ReadAscii(this Process targetProcess, IntPtr address) {
if (targetProcess == null || address == IntPtr.Zero) { return string.Empty; }
StringBuilder sb = new StringBuilder();
byte[] data = new byte[128];
int bytesRead;
int offset = 0;
bool invalid = false;
do {
WinAPI.ReadProcessMemory(targetProcess.Handle, address + offset, data, 128, out bytesRead);
int i = 0;
while (i < bytesRead) {
byte d = data[i++];
if (d == 0) {
i--;
break;
} else if (d > 127) {
invalid = true;
break;
}
}
if (i > 0) {
sb.Append(Encoding.ASCII.GetString(data, 0, i));
}
if (i < bytesRead || invalid) {
break;
}
offset += 128;
} while (bytesRead > 0);
return invalid ? string.Empty : sb.ToString();
}
public static string ReadAscii(this Process targetProcess, IntPtr address, params int[] offsets) {
if (targetProcess == null || address == IntPtr.Zero) { return string.Empty; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return string.Empty; }
return ReadAscii(targetProcess, address + last);
}
public static void Write<T>(this Process targetProcess, IntPtr address, T value, params int[] offsets) where T : unmanaged {
if (targetProcess == null) { return; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return; }
byte[] buffer;
unsafe {
buffer = new byte[sizeof(T)];
fixed (byte* bufferPtr = buffer) {
Buffer.MemoryCopy(&value, bufferPtr, sizeof(T), sizeof(T));
}
}
int bytesWritten;
WinAPI.WriteProcessMemory(targetProcess.Handle, address + last, buffer, buffer.Length, out bytesWritten);
}
public static void Write(this Process targetProcess, IntPtr address, byte[] value, params int[] offsets) {
if (targetProcess == null) { return; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return; }
int bytesWritten;
WinAPI.WriteProcessMemory(targetProcess.Handle, address + last, value, value.Length, out bytesWritten);
}
private static int OffsetAddress(this Process targetProcess, ref IntPtr address, params int[] offsets) {
byte[] buffer = new byte[is64Bit ? 8 : 4];
int bytesRead;
for (int i = 0; i < offsets.Length - 1; i++) {
WinAPI.ReadProcessMemory(targetProcess.Handle, address + offsets[i], buffer, buffer.Length, out bytesRead);
if (is64Bit) {
address = (IntPtr)BitConverter.ToUInt64(buffer, 0);
} else {
address = (IntPtr)BitConverter.ToUInt32(buffer, 0);
}
if (address == IntPtr.Zero) { break; }
}
return offsets.Length > 0 ? offsets[offsets.Length - 1] : 0;
}
public static bool Is64Bit(this Process process) {
if (process == null) { return false; }
bool flag;
WinAPI.IsWow64Process(process.Handle, out flag);
return Environment.Is64BitOperatingSystem && !flag;
}
public static Module64 MainModule64(this Process p) {
Module64[] modules = p.Modules64();
return modules == null || modules.Length == 0 ? null : modules[0];
}
public static Module64 Module64(this Process p, string moduleName) {
Module64[] modules = p.Modules64();
if (modules != null) {
for (int i = 0; i < modules.Length; i++) {
Module64 module = modules[i];
if (module.Name.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) {
return module;
}
}
}
return null;
}
public static Module64[] Modules64(this Process p) {
lock (ModuleCache) {
if (ModuleCache.Count > 100) { ModuleCache.Clear(); }
IntPtr[] buffer = new IntPtr[1024];
uint cb = (uint)(IntPtr.Size * buffer.Length);
uint totalModules;
if (!WinAPI.EnumProcessModulesEx(p.Handle, buffer, cb, out totalModules, 3u)) {
return null;
}
uint moduleSize = totalModules / (uint)IntPtr.Size;
int key = p.StartTime.GetHashCode() + p.Id + (int)moduleSize;
if (ModuleCache.ContainsKey(key)) { return ModuleCache[key]; }
List<Module64> list = new List<Module64>();
StringBuilder stringBuilder = new StringBuilder(260);
int count = 0;
while ((long)count < (long)((ulong)moduleSize)) {
stringBuilder.Clear();
if (WinAPI.GetModuleFileNameEx(p.Handle, buffer[count], stringBuilder, (uint)stringBuilder.Capacity) == 0u) {
return list.ToArray();
}
string fileName = stringBuilder.ToString();
stringBuilder.Clear();
if (WinAPI.GetModuleBaseName(p.Handle, buffer[count], stringBuilder, (uint)stringBuilder.Capacity) == 0u) {
return list.ToArray();
}
string moduleName = stringBuilder.ToString();
ModuleInfo modInfo = default(ModuleInfo);
if (!WinAPI.GetModuleInformation(p.Handle, buffer[count], out modInfo, (uint)Marshal.SizeOf(modInfo))) {
return list.ToArray();
}
list.Add(new Module64 {
FileName = fileName,
BaseAddress = modInfo.BaseAddress,
MemorySize = (int)modInfo.ModuleSize,
EntryPointAddress = modInfo.EntryPoint,
Name = moduleName
});
count++;
}
ModuleCache.Add(key, list.ToArray());
return list.ToArray();
}
}
public static IEnumerable<MemInfo> MemRegions(this Process p) {
MemInfo info;
IntPtr curAddr = IntPtr.Zero;
while (true) {
if (WinAPI.VirtualQueryEx(p.Handle, curAddr, out info, Marshal.SizeOf<MemInfo>()) == 0) {
// Check for ERR_INVALID_PARAMETER which means we reached the end of the address space
if (Marshal.GetLastWin32Error() == 0x00000057) yield break;
}
yield return info;
curAddr = (IntPtr) ((long) info.BaseAddress + (long) info.RegionSize);
}
}
}
internal static class WinAPI {
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out int lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process(IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool wow64Process);
[DllImport("psapi.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumProcessModulesEx(IntPtr hProcess, [Out] IntPtr[] lphModule, uint cb, out uint lpcbNeeded, uint dwFilterFlag);
[DllImport("psapi.dll", SetLastError = true)]
public static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, uint nSize);
[DllImport("psapi.dll")]
public static extern uint GetModuleBaseName(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, uint nSize);
[DllImport("psapi.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out ModuleInfo lpmodinfo, uint cb);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MemInfo lpBuffer, int dwLength);
}
public class Module64 {
public IntPtr BaseAddress { get; set; }
public IntPtr EntryPointAddress { get; set; }
public string FileName { get; set; }
public int MemorySize { get; set; }
public string Name { get; set; }
public FileVersionInfo FileVersionInfo { get { return FileVersionInfo.GetVersionInfo(FileName); } }
public override string ToString() {
return Name ?? base.ToString();
}
}
[StructLayout(LayoutKind.Sequential)]
public struct ModuleInfo {
public IntPtr BaseAddress;
public uint ModuleSize;
public IntPtr EntryPoint;
}
[StructLayout(LayoutKind.Sequential)]
public struct MemInfo {
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public uint AllocationProtect;
public IntPtr RegionSize;
public uint State;
public uint Protect;
public uint Type;
public bool IsCommited => (State & 0x1000) != 0;
public bool IsGuardPage => (Protect & 0x100) != 0;
public override string ToString() {
return BaseAddress.ToString("X") + " " + Protect.ToString("X") + " " + State.ToString("X") + " " + Type.ToString("X") + " " + RegionSize.ToString("X");
}
}
public class MemorySearcher {
private const int BUFFER_SIZE = 2097152;
private List<MemInfo> memoryInfo = new List<MemInfo>();
private byte[] buffer = new byte[BUFFER_SIZE];
public Func<MemInfo, bool> MemoryFilter = info => info.IsCommited && !info.IsGuardPage;
public int ReadMemory(Process process, int index, int startIndex, out int bytesRead) {
MemInfo info = memoryInfo[index];
int returnIndex = -1;
int amountToRead = (int)((uint)info.RegionSize - (uint)startIndex);
if (amountToRead > BUFFER_SIZE) {
returnIndex = startIndex + BUFFER_SIZE;
amountToRead = BUFFER_SIZE;
}
WinAPI.ReadProcessMemory(process.Handle, info.BaseAddress + startIndex, buffer, amountToRead, out bytesRead);
return returnIndex;
}
public IntPtr FindSignature(Process process, string signature) {
byte[] pattern;
bool[] mask;
GetSignature(signature, out pattern, out mask);
GetMemoryInfo(process.Handle);
int[] offsets = GetCharacterOffsets(pattern, mask);
for (int i = 0; i < memoryInfo.Count; i++) {
MemInfo info = memoryInfo[i];
int index = 0;
do {
int previousIndex = index;
int bytesRead;
index = ReadMemory(process, i, index, out bytesRead);
int result = ScanMemory(buffer, bytesRead, pattern, mask, offsets);
if (result != int.MinValue) {
return info.BaseAddress + result + previousIndex;
}
if (index > 0) { index -= pattern.Length - 1; }
} while (index > 0);
}
return IntPtr.Zero;
}
public List<IntPtr> FindSignatures(Process process, string signature) {
byte[] pattern;
bool[] mask;
GetSignature(signature, out pattern, out mask);
GetMemoryInfo(process.Handle);
int[] offsets = GetCharacterOffsets(pattern, mask);
List<IntPtr> pointers = new List<IntPtr>();
for (int i = 0; i < memoryInfo.Count; i++) {
MemInfo info = memoryInfo[i];
int index = 0;
do {
int previousIndex = index;
int bytesRead;
index = ReadMemory(process, i, index, out bytesRead);
info.BaseAddress += previousIndex;
ScanMemory(pointers, info, buffer, bytesRead, pattern, mask, offsets);
info.BaseAddress -= previousIndex;
if (index > 0) { index -= pattern.Length - 1; }
} while (index > 0);
}
return pointers;
}
public bool VerifySignature(Process process, IntPtr pointer, string signature) {
byte[] pattern;
bool[] mask;
GetSignature(signature, out pattern, out mask);
int[] offsets = GetCharacterOffsets(pattern, mask);
MemInfo memInfoStart = default(MemInfo);
MemInfo memInfoEnd = default(MemInfo);
if (WinAPI.VirtualQueryEx(process.Handle, pointer, out memInfoStart, Marshal.SizeOf(memInfoStart)) == 0 ||
WinAPI.VirtualQueryEx(process.Handle, pointer + pattern.Length, out memInfoEnd, Marshal.SizeOf(memInfoStart)) == 0 ||
memInfoStart.BaseAddress != memInfoEnd.BaseAddress || !MemoryFilter(memInfoStart)) {
return false;
}
byte[] buff = new byte[pattern.Length];
int bytesRead;
WinAPI.ReadProcessMemory(process.Handle, pointer, buff, buff.Length, out bytesRead);
return ScanMemory(buff, buff.Length, pattern, mask, offsets) == 0;
}
public void GetMemoryInfo(IntPtr pHandle) {
memoryInfo.Clear();
IntPtr current = (IntPtr)65536;
while (true) {
MemInfo memInfo = new MemInfo();
int dump = WinAPI.VirtualQueryEx(pHandle, current, out memInfo, Marshal.SizeOf(memInfo));
if (dump == 0) { break; }
long regionSize = (long)memInfo.RegionSize;
if (regionSize <= 0 || (int)regionSize != regionSize) {
if (MemoryReader.is64Bit) {
current = (IntPtr)((ulong)memInfo.BaseAddress + (ulong)memInfo.RegionSize);
continue;
}
break;
}
if (MemoryFilter(memInfo)) {
memoryInfo.Add(memInfo);
}
current = memInfo.BaseAddress + (int)regionSize;
}
}
private int ScanMemory(byte[] data, int dataLength, byte[] search, bool[] mask, int[] offsets) {
int current = 0;
int end = search.Length - 1;
while (current <= dataLength - search.Length) {
for (int i = end; data[current + i] == search[i] || mask[i]; i--) {
if (i == 0) {
return current;
}
}
int offset = offsets[data[current + end]];
current += offset;
}
return int.MinValue;
}
private void ScanMemory(List<IntPtr> pointers, MemInfo info, byte[] data, int dataLength, byte[] search, bool[] mask, int[] offsets) {
int current = 0;
int end = search.Length - 1;
while (current <= dataLength - search.Length) {
for (int i = end; data[current + i] == search[i] || mask[i]; i--) {
if (i == 0) {
pointers.Add(info.BaseAddress + current);
break;
}
}
int offset = offsets[data[current + end]];
current += offset;
}
}
private int[] GetCharacterOffsets(byte[] search, bool[] mask) {
int[] offsets = new int[256];
int unknown = 0;
int end = search.Length - 1;
for (int i = 0; i < end; i++) {
if (!mask[i]) {
offsets[search[i]] = end - i;
} else {
unknown = end - i;
}
}
if (unknown == 0) {
unknown = search.Length;
}
for (int i = 0; i < 256; i++) {
int offset = offsets[i];
if (unknown < offset || offset == 0) {
offsets[i] = unknown;
}
}
return offsets;
}
private void GetSignature(string searchString, out byte[] pattern, out bool[] mask) {
int length = searchString.Length >> 1;
pattern = new byte[length];
mask = new bool[length];
length <<= 1;
for (int i = 0, j = 0; i < length; i++) {
byte temp = (byte)(((int)searchString[i] - 0x30) & 0x1F);
pattern[j] |= temp > 0x09 ? (byte)(temp - 7) : temp;
if (searchString[i] == '?') {
mask[j] = true;
pattern[j] = 0;
}
if ((i & 1) == 1) {
j++;
} else {
pattern[j] <<= 4;
}
}
}
}
}