-
Notifications
You must be signed in to change notification settings - Fork 0
/
Memory.cs
474 lines (400 loc) · 16.9 KB
/
Memory.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
463
464
465
466
467
468
469
470
471
472
473
474
using System;
using System.Linq;
using System.Text;
using System.Security;
using System.Numerics;
using System.Diagnostics;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
namespace Memory
{
public class Memory
{
public static Process TargetProcess = default;
public static string Name = string.Empty;
public static int Id = default;
public static IntPtr Handle = default;
public static int BaseAddress = default;
public static Enums.InitalizeResult Initalize(string ProcessName)
{
Process[] processes = Process.GetProcessesByName(ProcessName);
if(processes.Length != 0)
{
try
{
TargetProcess = processes.FirstOrDefault();
Name = TargetProcess.ProcessName;
Id = TargetProcess.Id;
BaseAddress = (Int32)TargetProcess.MainModule.BaseAddress;
Handle = WinAPI.OpenProcess(Enums.ProcessAccessFlags.VirtualMemoryRead | Enums.ProcessAccessFlags.VirtualMemoryWrite | Enums.ProcessAccessFlags.VirtualMemoryOperation, false, Id);
return Enums.InitalizeResult.OK;
}
catch
{
return Enums.InitalizeResult.ACCES_VIOLATION_ERROR;
}
}
else
{
return Enums.InitalizeResult.PROCESS_NOT_FOUND;
}
}
public static Enums.InitalizeResult Initalize(string ProcessName, Enums.ProcessAccessFlags ExtraFlags)
{
Process[] processes = Process.GetProcessesByName(ProcessName);
if (processes.Length != 0)
{
try
{
TargetProcess = processes.FirstOrDefault();
Name = TargetProcess.ProcessName;
Id = TargetProcess.Id;
BaseAddress = (Int32)TargetProcess.MainModule.BaseAddress;
Handle = WinAPI.OpenProcess(Enums.ProcessAccessFlags.VirtualMemoryRead | Enums.ProcessAccessFlags.VirtualMemoryWrite | Enums.ProcessAccessFlags.VirtualMemoryOperation | ExtraFlags, false, Id);
return Enums.InitalizeResult.OK;
}
catch
{
return Enums.InitalizeResult.ACCES_VIOLATION_ERROR;
}
}
else
{
return Enums.InitalizeResult.PROCESS_NOT_FOUND;
}
}
public static void Restore()
{
try
{
TargetProcess = default;
Name = string.Empty;
Id = default;
if (Handle != default || Handle != IntPtr.Zero || Handle != null)
WinAPI.CloseHandle(Handle);
} catch { }
}
#region Read/Write
private static IntPtr BytesRead = IntPtr.Zero;
private static IntPtr BytesWritten = IntPtr.Zero;
public static byte[] ReadMemory(int address, int size)
{
byte[] buffer = new byte[size];
WinAPI.ReadProcessMemory(Handle, address, buffer, buffer.Length, out BytesRead);
return buffer;
}
public static bool ReadBytes(int address, ref byte[] buffer)
{
return WinAPI.ReadProcessMemory(Handle, address, buffer, buffer.Length, out BytesRead) ? true : false;
}
public static byte[] ReadBytes(int address, int size)
{
byte[] buffer = new byte[size];
WinAPI.ReadProcessMemory(Handle, address, buffer, buffer.Length, out BytesRead);
return buffer;
}
public static T Read<T>(int address) where T : struct
{
byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
WinAPI.ReadProcessMemory(Handle, address, buffer, buffer.Length, out BytesRead);
return Transformation.ByteArrayToStructure<T>(buffer);
}
public static T Read<T>(int address, int[] offsets) where T : struct
{
return Read<T>((int)FindDMAAddy(new IntPtr(address), offsets));
}
public static void Write<T>(int address, object value) where T : struct
{
byte[] buffer = Transformation.StructureToByteArray(value);
WinAPI.WriteProcessMemory(Handle, address, buffer, buffer.Length, out BytesWritten);
}
public static void Write<T>(int address, int[] offsets, object value) where T : struct
{
Write<T>((int)FindDMAAddy(new IntPtr(address), offsets), value);
}
public static IntPtr FindDMAAddy(IntPtr ptr, int[] offsets)
{
var buffer = new byte[IntPtr.Size];
foreach (int i in offsets)
{
WinAPI.ReadProcessMemory(Handle, (int)ptr, buffer, buffer.Length, out BytesRead);
ptr = (IntPtr.Size == 4)
? IntPtr.Add(new IntPtr(BitConverter.ToInt32(buffer, 0)), i)
: ptr = IntPtr.Add(new IntPtr(BitConverter.ToInt64(buffer, 0)), i);
}
return ptr;
}
public static float[] ReadMatrix<T>(int address, int matrixSize) where T : struct
{
byte[] buffer = new byte[Marshal.SizeOf(typeof(T)) * matrixSize];
WinAPI.ReadProcessMemory(Handle, address, buffer, buffer.Length, out BytesRead);
return Transformation.ConvertToFloatArray(buffer);
}
public static string ReadString(int address, int size, Encoding encoding = default)
{
return Transformation.CutString(encoding.GetString(ReadMemory(address, size)));
}
#endregion
#region Features
public static int GetModuleAddress(string module_name)
{
foreach (ProcessModule module in TargetProcess.Modules)
{
if (module.ModuleName == module_name)
{
return (Int32)module.BaseAddress;
}
}
return -1;
}
public static bool WorldToScreen(Vector3 target, out Vector2 pos, float[] viewmatrix, int width, int height, Enums.GraphicAPI graphicApi = Enums.GraphicAPI.DirectX)
{
//Matrix-vector Product, multiplying world(eye) coordinates by projection matrix = clipCoords
pos = new Vector2(0, 0);
Vector4 clipCoords = new Vector4()
{
X = target.X * viewmatrix[0] + target.Y * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 1 : 4] + target.Z * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 2 : 8] + viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 3 : 12],
Y = target.X * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 4 : 1] + target.Y * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 5 : 5] + target.Z * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 6 : 9] + viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 7 : 13],
Z = target.X * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 8 : 2] + target.Y * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 9 : 6] + target.Z * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 10 : 10] + viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 11 : 14],
W = target.X * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 12 : 3] + target.Y * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 13 : 7] + target.Z * viewmatrix[(graphicApi == Enums.GraphicAPI.DirectX) ? 14 : 11] + viewmatrix[15]
};
if (clipCoords.W < 0.1f)
return false;
//perspective division, dividing by clip.W = Normalized Device Coordinates
Vector3 NDC;
NDC.X = clipCoords.X / clipCoords.W;
NDC.Y = clipCoords.Y / clipCoords.W;
NDC.Z = clipCoords.Z / clipCoords.W;
pos.X = (width / 2 * NDC.X) + (NDC.X + width / 2);
pos.Y = -(height / 2 * NDC.Y) + (NDC.Y + height / 2);
return true;
}
public static int ScanPattern(string module_name, string signature)
{
byte[] ModuleBuffer = null;
int ModuleAddress = -1;
foreach (ProcessModule process_module in TargetProcess.Modules)
{
if (process_module.ModuleName == module_name)
{
ModuleBuffer = new byte[process_module.ModuleMemorySize];
ModuleAddress = (Int32)process_module.BaseAddress;
}
}
if (ModuleAddress == -1 || ModuleBuffer == null)
return -1; // MODULE NOT FOUND
byte[] pattern = Transformation.SignatureToPattern(signature);
string mask = Transformation.GetSignatureMask(signature);
if (ReadBytes(ModuleAddress, ref ModuleBuffer))
{
for (int i = 0; i < ModuleBuffer.Length; i++)
{
bool IsFounded = false;
for (int a = 0; a < pattern.Length; a++)
{
if (mask[a] == '?')
continue;
if (pattern[a] == ModuleBuffer[i + a])
IsFounded = true;
}
if (!IsFounded) continue;
return i;
}
}
return -1;
}
public static int ScanPattern(string module_name, string signature, int offset, int extra, bool relative)
{
byte[] ModuleBuffer = null;
int ModuleAddress = -1;
foreach (ProcessModule process_module in TargetProcess.Modules)
{
if(process_module.ModuleName == module_name)
{
ModuleBuffer = new byte[process_module.ModuleMemorySize];
ModuleAddress = (Int32)process_module.BaseAddress;
}
}
if (ModuleAddress == -1 || ModuleBuffer == null)
return -1; // MODULE NOT FOUND
byte[] pattern = Transformation.SignatureToPattern(signature);
string mask = Transformation.GetSignatureMask(signature);
if(ReadBytes(ModuleAddress, ref ModuleBuffer))
{
int Address = -1;
for(int i = 0; i < ModuleBuffer.Length; i++)
{
bool IsFounded = false;
for(int a = 0; a < pattern.Length; a++)
{
if (mask[a] == '?')
continue;
if (pattern[a] == ModuleBuffer[i + a])
IsFounded = true;
}
if (!IsFounded) continue;
if (relative)
Address = BitConverter.ToInt32(ReadBytes(i + offset, 4), 0) + extra;
else
Address = BitConverter.ToInt32(ReadBytes(ModuleAddress + i + offset, 4), 0) + extra;
return Address;
}
}
return -1;
}
#endregion
class Transformation
{
public static byte[] SignatureToPattern(string sig)
{
string[] parts = sig.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
byte[] patternArray = new byte[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
if (parts[i] == "?")
{
patternArray[i] = 0;
continue;
}
if (!byte.TryParse(parts[i], System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.DefaultThreadCurrentCulture, out patternArray[i]))
{
throw new Exception();
}
}
return patternArray;
}
public static string GetSignatureMask(string sig)
{
string[] parts = sig.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string mask = "";
for (int i = 0; i < parts.Length; i++)
{
if (parts[i] == "?")
{
mask += "?";
}
else
{
mask += "x";
}
}
return mask;
}
public static string CutString(string mystring)
{
char[] chArray = mystring.ToCharArray();
string str = "";
for (int i = 0; i < mystring.Length; i++)
{
if ((chArray[i] == ' ') && (chArray[i + 1] == ' '))
{
return str;
}
if (chArray[i] == '\0')
{
return str;
}
str = str + chArray[i].ToString();
}
return mystring.TrimEnd(new char[] { '0' });
}
public static float[] ConvertToFloatArray(byte[] bytes)
{
if (bytes.Length % 4 != 0) throw new ArgumentException();
float[] floats = new float[bytes.Length / 4];
for (int i = 0; i < floats.Length; i++) floats[i] = BitConverter.ToSingle(bytes, i * 4);
return floats;
}
public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
}
finally
{
handle.Free();
}
}
public static byte[] StructureToByteArray(object obj)
{
int length = Marshal.SizeOf(obj);
byte[] array = new byte[length];
IntPtr pointer = Marshal.AllocHGlobal(length);
Marshal.StructureToPtr(obj, pointer, true);
Marshal.Copy(pointer, array, 0, length);
Marshal.FreeHGlobal(pointer);
return array;
}
}
public class Enums
{
public enum InitalizeResult
{
OK,
PROCESS_NOT_FOUND,
ACCES_VIOLATION_ERROR
}
public enum GraphicAPI
{
DirectX,
OpenGL
}
// ABOUT PROCESS MEMORY READING
[Flags]
public enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VirtualMemoryOperation = 0x00000008,
VirtualMemoryRead = 0x00000010,
VirtualMemoryWrite = 0x00000020,
DuplicateHandle = 0x00000040,
CreateProcess = 0x000000080,
SetQuota = 0x00000100,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
QueryLimitedInformation = 0x00001000,
Synchronize = 0x00100000
}
}
class WinAPI
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(
uint processAccess,
bool bInheritHandle,
int processId
);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(
Enums.ProcessAccessFlags processAccess,
bool bInheritHandle,
int processId
);
[DllImport("kernel32.dll", SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadProcessMemory(
IntPtr hProcess,
int lpBaseAddress,
[Out] byte[] lpBuffer,
int dwSize,
out IntPtr lpNumberOfBytesRead
);
[DllImport("kernel32.dll")]
public static extern bool WriteProcessMemory(
IntPtr hProcess,
int lpBaseAddress,
byte[] lpBuffer,
int dwSize,
out IntPtr lpNumberOfBytesWritten
);
}
}
}