/
memory.cs
2119 lines (1802 loc) · 81.8 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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.IO.Pipes;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Globalization;
using System.Windows.Forms;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace Memory
{
/// <summary>
/// Memory.dll class. Full documentation at https://github.com/erfg12/memory.dll/wiki
/// </summary>
public class Mem
{
#region DllImports
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(
UInt32 dwDesiredAccess,
bool bInheritHandle,
Int32 dwProcessId
);
#if WINXP
#else
[DllImport("kernel32.dll", EntryPoint = "VirtualQueryEx")]
public static extern UIntPtr Native_VirtualQueryEx(IntPtr hProcess, UIntPtr lpAddress,
out MEMORY_BASIC_INFORMATION32 lpBuffer, UIntPtr dwLength);
[DllImport("kernel32.dll", EntryPoint = "VirtualQueryEx")]
public static extern UIntPtr Native_VirtualQueryEx(IntPtr hProcess, UIntPtr lpAddress,
out MEMORY_BASIC_INFORMATION64 lpBuffer, UIntPtr dwLength);
[DllImport("kernel32.dll")]
static extern uint GetLastError();
public UIntPtr VirtualQueryEx(IntPtr hProcess, UIntPtr lpAddress,
out MEMORY_BASIC_INFORMATION lpBuffer)
{
UIntPtr retVal;
// TODO: Need to change this to only check once.
if (Is64Bit || IntPtr.Size == 8)
{
// 64 bit
MEMORY_BASIC_INFORMATION64 tmp64 = new MEMORY_BASIC_INFORMATION64();
retVal = Native_VirtualQueryEx(hProcess, lpAddress, out tmp64, new UIntPtr((uint)Marshal.SizeOf(tmp64)));
lpBuffer.BaseAddress = tmp64.BaseAddress;
lpBuffer.AllocationBase = tmp64.AllocationBase;
lpBuffer.AllocationProtect = tmp64.AllocationProtect;
lpBuffer.RegionSize = (long)tmp64.RegionSize;
lpBuffer.State = tmp64.State;
lpBuffer.Protect = tmp64.Protect;
lpBuffer.Type = tmp64.Type;
return retVal;
}
MEMORY_BASIC_INFORMATION32 tmp32 = new MEMORY_BASIC_INFORMATION32();
retVal = Native_VirtualQueryEx(hProcess, lpAddress, out tmp32, new UIntPtr((uint)Marshal.SizeOf(tmp32)));
lpBuffer.BaseAddress = tmp32.BaseAddress;
lpBuffer.AllocationBase = tmp32.AllocationBase;
lpBuffer.AllocationProtect = tmp32.AllocationProtect;
lpBuffer.RegionSize = tmp32.RegionSize;
lpBuffer.State = tmp32.State;
lpBuffer.Protect = tmp32.Protect;
lpBuffer.Type = tmp32.Type;
return retVal;
}
[DllImport("kernel32.dll")]
static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
#endif
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
static extern int ResumeThread(IntPtr hThread);
[DllImport("dbghelp.dll")]
static extern bool MiniDumpWriteDump(
IntPtr hProcess,
Int32 ProcessId,
IntPtr hFile,
MINIDUMP_TYPE DumpType,
IntPtr ExceptionParam,
IntPtr UserStreamParam,
IntPtr CallackParam);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr w, IntPtr l);
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(
IntPtr hProcess,
UIntPtr lpBaseAddress,
string lpBuffer,
UIntPtr nSize,
out IntPtr lpNumberOfBytesWritten
);
[DllImport("kernel32.dll")]
static extern int GetProcessId(IntPtr handle);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern uint GetPrivateProfileString(
string lpAppName,
string lpKeyName,
string lpDefault,
StringBuilder lpReturnedString,
uint nSize,
string lpFileName);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool VirtualFreeEx(
IntPtr hProcess,
UIntPtr lpAddress,
UIntPtr dwSize,
uint dwFreeType
);
[DllImport("kernel32.dll")]
private static extern bool ReadProcessMemory(IntPtr hProcess, UIntPtr lpBaseAddress, [Out] byte[] lpBuffer, UIntPtr nSize, IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll")]
private static extern bool ReadProcessMemory(IntPtr hProcess, UIntPtr lpBaseAddress, [Out] byte[] lpBuffer, UIntPtr nSize, out ulong lpNumberOfBytesRead);
[DllImport("kernel32.dll")]
private static extern bool ReadProcessMemory(IntPtr hProcess, UIntPtr lpBaseAddress, [Out] IntPtr lpBuffer, UIntPtr nSize, out ulong lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern UIntPtr VirtualAllocEx(
IntPtr hProcess,
UIntPtr lpAddress,
uint dwSize,
uint flAllocationType,
uint flProtect
);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern UIntPtr GetProcAddress(
IntPtr hModule,
string procName
);
[DllImport("kernel32.dll", EntryPoint = "CloseHandle")]
private static extern bool _CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
public static extern Int32 CloseHandle(
IntPtr hObject
);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetModuleHandle(
string lpModuleName
);
[DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
internal static extern Int32 WaitForSingleObject(
IntPtr handle,
Int32 milliseconds
);
[DllImport("kernel32.dll")]
private static extern bool WriteProcessMemory(IntPtr hProcess, UIntPtr lpBaseAddress, byte[] lpBuffer, UIntPtr nSize, IntPtr lpNumberOfBytesWritten);
// Added to avoid casting to UIntPtr
[DllImport("kernel32.dll")]
private static extern bool WriteProcessMemory(IntPtr hProcess, UIntPtr lpBaseAddress, byte[] lpBuffer, UIntPtr nSize, out IntPtr lpNumberOfBytesWritten);
[DllImport("kernel32")]
public static extern IntPtr CreateRemoteThread(
IntPtr hProcess,
IntPtr lpThreadAttributes,
uint dwStackSize,
UIntPtr lpStartAddress, // raw Pointer into remote process
UIntPtr lpParameter,
uint dwCreationFlags,
out IntPtr lpThreadId
);
[DllImport("kernel32")]
public static extern bool IsWow64Process(IntPtr hProcess, out bool lpSystemInfo);
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
// privileges
const int PROCESS_CREATE_THREAD = 0x0002;
const int PROCESS_QUERY_INFORMATION = 0x0400;
const int PROCESS_VM_OPERATION = 0x0008;
const int PROCESS_VM_WRITE = 0x0020;
const int PROCESS_VM_READ = 0x0010;
// used for memory allocation
const uint MEM_FREE = 0x10000;
const uint MEM_COMMIT = 0x00001000;
const uint MEM_RESERVE = 0x00002000;
private const uint PAGE_READONLY = 0x02;
const uint PAGE_READWRITE = 0x04;
const uint PAGE_WRITECOPY = 0x08;
private const uint PAGE_EXECUTE_READWRITE = 0x40;
private const uint PAGE_EXECUTE_WRITECOPY = 0x80;
private const uint PAGE_EXECUTE = 0x10;
private const uint PAGE_EXECUTE_READ = 0x20;
private const uint PAGE_GUARD = 0x100;
private const uint PAGE_NOACCESS = 0x01;
private uint MEM_PRIVATE = 0x20000;
private uint MEM_IMAGE = 0x1000000;
#endregion
/// <summary>
/// The process handle that was opened. (Use OpenProcess function to populate this variable)
/// </summary>
public IntPtr pHandle;
Dictionary<string, CancellationTokenSource> FreezeTokenSrcs = new Dictionary<string, CancellationTokenSource>();
public Process theProc = null;
internal enum MINIDUMP_TYPE
{
MiniDumpNormal = 0x00000000,
MiniDumpWithDataSegs = 0x00000001,
MiniDumpWithFullMemory = 0x00000002,
MiniDumpWithHandleData = 0x00000004,
MiniDumpFilterMemory = 0x00000008,
MiniDumpScanMemory = 0x00000010,
MiniDumpWithUnloadedModules = 0x00000020,
MiniDumpWithIndirectlyReferencedMemory = 0x00000040,
MiniDumpFilterModulePaths = 0x00000080,
MiniDumpWithProcessThreadData = 0x00000100,
MiniDumpWithPrivateReadWriteMemory = 0x00000200,
MiniDumpWithoutOptionalData = 0x00000400,
MiniDumpWithFullMemoryInfo = 0x00000800,
MiniDumpWithThreadInfo = 0x00001000,
MiniDumpWithCodeSegs = 0x00002000
}
bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
/// <summary>
/// Freeze a value to an address.
/// </summary>
/// <param name="address">Your address</param>
/// <param name="type">byte, 2bytes, bytes, float, int, string, double or long.</param>
/// <param name="value">Value to freeze</param>
/// <param name="file">ini file to read address from (OPTIONAL)</param>
public void FreezeValue(string address, string type, string value, string file = "")
{
CancellationTokenSource cts = new CancellationTokenSource();
if (FreezeTokenSrcs.ContainsKey(address))
{
Debug.WriteLine("Changing Freezing Address " + address + " Value " + value);
try
{
FreezeTokenSrcs[address].Cancel();
FreezeTokenSrcs.Remove(address);
}
catch
{
Debug.WriteLine("ERROR: Avoided a crash. Address " + address + " was not frozen.");
}
}
else
Debug.WriteLine("Adding Freezing Address " + address + " Value " + value);
FreezeTokenSrcs.Add(address, cts);
Task.Factory.StartNew(() =>
{
while (!cts.Token.IsCancellationRequested)
{
WriteMemory(address, type, value, file);
Thread.Sleep(25);
}
},
cts.Token);
}
/// <summary>
/// Unfreeze a frozen value at an address
/// </summary>
/// <param name="address">address where frozen value is stored</param>
public void UnfreezeValue(string address)
{
Debug.WriteLine("Un-Freezing Address " + address);
try
{
FreezeTokenSrcs[address].Cancel();
FreezeTokenSrcs.Remove(address);
}
catch
{
Debug.WriteLine("ERROR: Address " + address + " was not frozen.");
}
}
/// <summary>
/// Open the PC game process with all security and access rights.
/// </summary>
/// <param name="proc">Use process name or process ID here.</param>
/// <returns></returns>
public bool OpenProcess(int pid)
{
if (!IsAdmin())
{
Debug.WriteLine("WARNING: You are NOT running this program as admin! Visit https://github.com/erfg12/memory.dll/wiki/Administrative-Privileges");
MessageBox.Show("WARNING: You are NOT running this program as admin!");
}
try
{
if (theProc != null && theProc.Id == pid)
return true;
if (pid <= 0)
{
Debug.WriteLine("ERROR: OpenProcess given proc ID 0.");
return false;
}
theProc = Process.GetProcessById(pid);
if (theProc != null && !theProc.Responding)
{
Debug.WriteLine("ERROR: OpenProcess: Process is not responding or null.");
return false;
}
pHandle = OpenProcess(0x1F0FFF, true, pid);
Process.EnterDebugMode();
if (pHandle == IntPtr.Zero)
{
var eCode = Marshal.GetLastWin32Error();
}
mainModule = theProc.MainModule;
GetModules();
// Lets set the process to 64bit or not here (cuts down on api calls)
Is64Bit = Environment.Is64BitOperatingSystem && (IsWow64Process(pHandle, out bool retVal) && !retVal);
Debug.WriteLine("Program is operating at Administrative level. Process #" + theProc + " is open and modules are stored.");
return true;
}
catch {
Debug.WriteLine("ERROR: OpenProcess has crashed. Are you trying to hack a x64 game? https://github.com/erfg12/memory.dll/wiki/64bit-Games");
return false;
}
}
/// <summary>
/// Open the PC game process with all security and access rights.
/// </summary>
/// <param name="proc">Use process name or process ID here.</param>
/// <returns></returns>
public bool OpenProcess(string proc)
{
return OpenProcess(GetProcIdFromName(proc));
}
/// <summary>
/// Check if program is running with administrative privileges. Read about it here: https://github.com/erfg12/memory.dll/wiki/Administrative-Privileges
/// </summary>
/// <returns></returns>
public bool IsAdmin()
{
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
/// <summary>
/// Check if opened process is 64bit. Used primarily for getCode().
/// </summary>
/// <returns>True if 64bit false if 32bit.</returns>
private bool _is64Bit;
public bool Is64Bit
{
get { return _is64Bit; }
private set { _is64Bit = value; }
}
/// <summary>
/// Builds the process modules dictionary (names with addresses).
/// </summary>
public void GetModules()
{
if (theProc == null)
return;
modules.Clear();
foreach (ProcessModule Module in theProc.Modules)
{
if (!string.IsNullOrEmpty(Module.ModuleName) && !modules.ContainsKey(Module.ModuleName))
modules.Add(Module.ModuleName, Module.BaseAddress);
}
}
public void SetFocus()
{
//int style = GetWindowLong(procs.MainWindowHandle, -16);
//if ((style & 0x20000000) == 0x20000000) //minimized
// SendMessage(procs.Handle, 0x0112, (IntPtr)0xF120, IntPtr.Zero);
SetForegroundWindow(theProc.MainWindowHandle);
}
/// <summary>
/// Get the process ID number by process name.
/// </summary>
/// <param name="name">Example: "eqgame". Use task manager to find the name. Do not include .exe</param>
/// <returns></returns>
public int GetProcIdFromName(string name) //new 1.0.2 function
{
Process[] processlist = Process.GetProcesses();
if (name.Contains(".exe"))
name = name.Replace(".exe", "");
foreach (Process theprocess in processlist)
{
if (theprocess.ProcessName.Equals(name, StringComparison.CurrentCultureIgnoreCase)) //find (name).exe in the process list (use task manager to find the name)
return theprocess.Id;
}
return 0; //if we fail to find it
}
/// <summary>
/// Get code from ini file.
/// </summary>
/// <param name="name">label for address or code</param>
/// <param name="file">path and name of ini file</param>
/// <returns></returns>
public string LoadCode(string name, string file)
{
StringBuilder returnCode = new StringBuilder(1024);
uint read_ini_result;
if (file != "")
read_ini_result = GetPrivateProfileString("codes", name, "", returnCode, (uint)returnCode.Capacity, file);
else
returnCode.Append(name);
return returnCode.ToString();
}
private int LoadIntCode(string name, string path)
{
try
{
int intValue = Convert.ToInt32(LoadCode(name, path), 16);
if (intValue >= 0)
return intValue;
else
return 0;
} catch
{
Debug.WriteLine("ERROR: LoadIntCode function crashed!");
return 0;
}
}
/// <summary>
/// Dictionary with our opened process module names with addresses.
/// </summary>
public Dictionary<string, IntPtr> modules = new Dictionary<string, IntPtr>();
/// <summary>
/// Make a named pipe (if not already made) and call to a remote function.
/// </summary>
/// <param name="func">remote function to call</param>
/// <param name="name">name of the thread</param>
public void ThreadStartClient(string func, string name)
{
//ManualResetEvent SyncClientServer = (ManualResetEvent)obj;
using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(name))
{
if (!pipeStream.IsConnected)
pipeStream.Connect();
//MessageBox.Show("[Client] Pipe connection established");
using (StreamWriter sw = new StreamWriter(pipeStream))
{
if (!sw.AutoFlush)
sw.AutoFlush = true;
sw.WriteLine(func);
}
}
}
private ProcessModule mainModule;
/// <summary>
/// Cut a string that goes on for too long or one that is possibly merged with another string.
/// </summary>
/// <param name="str">The string you want to cut.</param>
/// <returns></returns>
public string CutString(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
if (c >= ' ' && c <= '~')
sb.Append(c);
else
break;
}
return sb.ToString();
}
/// <summary>
/// Clean up a string that has bad characters in it.
/// </summary>
/// <param name="str">The string you want to sanitize.</param>
/// <returns></returns>
public string SanitizeString(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
if (c >= ' ' && c <= '~')
sb.Append(c);
}
return sb.ToString();
}
#region readMemory
/// <summary>
/// Reads up to `length ` bytes from an address.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="length">The maximum bytes to read.</param>
/// <param name="file">path and name of ini file.</param>
/// <returns>The bytes read or null</returns>
public byte[] ReadBytes(string code, long length, string file = "")
{
byte[] memory = new byte[length];
UIntPtr theCode = GetCode(code, file);
if (!ReadProcessMemory(pHandle, theCode, memory, (UIntPtr)length, IntPtr.Zero))
return null;
return memory;
}
/// <summary>
/// Read a float value from an address.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="file">path and name of ini file. (OPTIONAL)</param>
/// <param name="round">Round the value to 2 decimal places</param>
/// <returns></returns>
public float ReadFloat(string code, string file = "", bool round = true)
{
byte[] memory = new byte[4];
UIntPtr theCode;
theCode = GetCode(code, file);
try
{
if (ReadProcessMemory(pHandle, theCode, memory, (UIntPtr)4, IntPtr.Zero))
{
float address = BitConverter.ToSingle(memory, 0);
float returnValue = (float)address;
if (round)
returnValue = (float)Math.Round(address, 2);
return returnValue;
}
else
return 0;
}
catch
{
return 0;
}
}
/// <summary>
/// Read a string value from an address.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="file">path and name of ini file. (OPTIONAL)</param>
/// <param name="length">length of bytes to read (OPTIONAL)</param>
/// <param name="zeroTerminated">terminate string at null char</param>
/// <returns></returns>
public string ReadString(string code, string file = "", int length = 32, bool zeroTerminated = true)
{
byte[] memoryNormal = new byte[length];
UIntPtr theCode;
theCode = GetCode(code, file);
if (ReadProcessMemory(pHandle, theCode, memoryNormal, (UIntPtr)length, IntPtr.Zero))
return (zeroTerminated) ? Encoding.UTF8.GetString(memoryNormal).Split('\0')[0] : Encoding.UTF8.GetString(memoryNormal);
else
return "";
}
/// <summary>
/// Read a double value
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="file">path and name of ini file. (OPTIONAL)</param>
/// <param name="round">Round the value to 2 decimal places</param>
/// <returns></returns>
public double ReadDouble(string code, string file = "", bool round = true)
{
byte[] memory = new byte[8];
UIntPtr theCode;
theCode = GetCode(code, file);
try
{
if (ReadProcessMemory(pHandle, theCode, memory, (UIntPtr)8, IntPtr.Zero))
{
double address = BitConverter.ToDouble(memory, 0);
double returnValue = (double)address;
if (round)
returnValue = (double)Math.Round(address, 2);
return returnValue;
}
else
return 0;
}
catch
{
return 0;
}
}
public int ReadUIntPtr(UIntPtr code)
{
byte[] memory = new byte[4];
if (ReadProcessMemory(pHandle, code, memory, (UIntPtr)4, IntPtr.Zero))
return BitConverter.ToInt32(memory, 0);
else
return 0;
}
/// <summary>
/// Read an integer from an address.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="file">path and name of ini file. (OPTIONAL)</param>
/// <returns></returns>
public int ReadInt(string code, string file = "")
{
byte[] memory = new byte[4];
UIntPtr theCode;
theCode = GetCode(code, file);
if (ReadProcessMemory(pHandle, theCode, memory, (UIntPtr)4, IntPtr.Zero))
return BitConverter.ToInt32(memory, 0);
else
return 0;
}
/// <summary>
/// Read a long value from an address.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="file">path and name of ini file. (OPTIONAL)</param>
/// <returns></returns>
public long ReadLong(string code, string file = "")
{
byte[] memory = new byte[16];
UIntPtr theCode;
theCode = GetCode(code, file);
if (ReadProcessMemory(pHandle, theCode, memory, (UIntPtr)16, IntPtr.Zero))
return BitConverter.ToInt64(memory, 0);
else
return 0;
}
/// <summary>
/// Read a UInt value from address.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="file">path and name of ini file. (OPTIONAL)</param>
/// <returns></returns>
public UInt64 ReadUInt(string code, string file = "")
{
byte[] memory = new byte[4];
UIntPtr theCode;
theCode = GetCode(code, file);
if (ReadProcessMemory(pHandle, theCode, memory, (UIntPtr)4, IntPtr.Zero))
return BitConverter.ToUInt64(memory, 0);
else
return 0;
}
/// <summary>
/// Reads a 2 byte value from an address and moves the address.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="moveQty">Quantity to move.</param>
/// <param name="file">path and name of ini file (OPTIONAL)</param>
/// <returns></returns>
public int Read2ByteMove(string code, int moveQty, string file = "")
{
byte[] memory = new byte[4];
UIntPtr theCode;
theCode = GetCode(code, file);
UIntPtr newCode = UIntPtr.Add(theCode, moveQty);
if (ReadProcessMemory(pHandle, newCode, memory, (UIntPtr)2, IntPtr.Zero))
return BitConverter.ToInt32(memory, 0);
else
return 0;
}
/// <summary>
/// Reads an integer value from address and moves the address.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="moveQty">Quantity to move.</param>
/// <param name="file">path and name of ini file (OPTIONAL)</param>
/// <returns></returns>
public int ReadIntMove(string code, int moveQty, string file = "")
{
byte[] memory = new byte[4];
UIntPtr theCode;
theCode = GetCode(code, file);
UIntPtr newCode = UIntPtr.Add(theCode, moveQty);
if (ReadProcessMemory(pHandle, newCode, memory, (UIntPtr)4, IntPtr.Zero))
return BitConverter.ToInt32(memory, 0);
else
return 0;
}
/// <summary>
/// Get UInt and move to another address by moveQty. Use in a for loop.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="moveQty">Quantity to move.</param>
/// <param name="file">path and name of ini file (OPTIONAL)</param>
/// <returns></returns>
public ulong ReadUIntMove(string code, int moveQty, string file = "")
{
byte[] memory = new byte[8];
UIntPtr theCode;
theCode = GetCode(code, file, 8);
UIntPtr newCode = UIntPtr.Add(theCode, moveQty);
if (ReadProcessMemory(pHandle, newCode, memory, (UIntPtr)8, IntPtr.Zero))
return BitConverter.ToUInt64(memory, 0);
else
return 0;
}
/// <summary>
/// Read a 2 byte value from an address. Returns an integer.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="file">path and file name to ini file. (OPTIONAL)</param>
/// <returns></returns>
public int Read2Byte(string code, string file = "")
{
byte[] memoryTiny = new byte[4];
UIntPtr theCode;
theCode = GetCode(code, file);
if (ReadProcessMemory(pHandle, theCode, memoryTiny, (UIntPtr)2, IntPtr.Zero))
return BitConverter.ToInt32(memoryTiny, 0);
else
return 0;
}
/// <summary>
/// Read 1 byte from address.
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="file">path and file name of ini file. (OPTIONAL)</param>
/// <returns></returns>
public int ReadByte(string code, string file = "")
{
byte[] memoryTiny = new byte[1];
UIntPtr theCode = GetCode(code, file);
if (ReadProcessMemory(pHandle, theCode, memoryTiny, (UIntPtr) 1, IntPtr.Zero))
return memoryTiny[0];
return 0;
}
/// <summary>
/// Reads a byte from memory and splits it into bits
/// </summary>
/// <param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
/// <param name="file">path and file name of ini file. (OPTIONAL)</param>
/// <returns>Array of 8 booleans representing each bit of the byte read</returns>
public bool[] ReadBits(string code, string file = "")
{
byte[] buf = new byte[1];
UIntPtr theCode = GetCode(code, file);
bool[] ret = new bool[8];
if (!ReadProcessMemory(pHandle, theCode, buf, (UIntPtr) 1, IntPtr.Zero))
return ret;
if (!BitConverter.IsLittleEndian)
throw new Exception("Should be little endian");
for (var i = 0; i < 8; i++)
ret[i] = Convert.ToBoolean(buf[0] & (1 << i));
return ret;
}
public int ReadPByte(UIntPtr address, string code, string file = "")
{
byte[] memory = new byte[4];
if (ReadProcessMemory(pHandle, address + LoadIntCode(code, file), memory, (UIntPtr)1, IntPtr.Zero))
return BitConverter.ToInt32(memory, 0);
else
return 0;
}
public float ReadPFloat(UIntPtr address, string code, string file = "")
{
byte[] memory = new byte[4];
if (ReadProcessMemory(pHandle, address + LoadIntCode(code, file), memory, (UIntPtr)4, IntPtr.Zero))
{
float spawn = BitConverter.ToSingle(memory, 0);
return (float)Math.Round(spawn, 2);
}
else
return 0;
}
public int ReadPInt(UIntPtr address, string code, string file = "")
{
byte[] memory = new byte[4];
if (ReadProcessMemory(pHandle, address + LoadIntCode(code, file), memory, (UIntPtr)4, IntPtr.Zero))
return BitConverter.ToInt32(memory, 0);
else
return 0;
}
public string ReadPString(UIntPtr address, string code, string file = "")
{
byte[] memoryNormal = new byte[32];
if (ReadProcessMemory(pHandle, address + LoadIntCode(code, file), memoryNormal, (UIntPtr)32, IntPtr.Zero))
return CutString(System.Text.Encoding.ASCII.GetString(memoryNormal));
else
return "";
}
#endregion
#region writeMemory
///<summary>
///Write to memory address. See https://github.com/erfg12/memory.dll/wiki/writeMemory() for more information.
///</summary>
///<param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
///<param name="type">byte, 2bytes, bytes, float, int, string, double or long.</param>
///<param name="write">value to write to address.</param>
///<param name="file">path and name of .ini file (OPTIONAL)</param>
///<param name="stringEncoding">System.Text.Encoding.UTF8 (DEFAULT). Other options: ascii, unicode, utf32, utf7</param>
public bool WriteMemory(string code, string type, string write, string file = "", System.Text.Encoding stringEncoding = null)
{
byte[] memory = new byte[4];
int size = 4;
UIntPtr theCode;
theCode = GetCode(code, file);
if (type.ToLower() == "float")
{
memory = BitConverter.GetBytes(Convert.ToSingle(write));
size = 4;
}
else if (type.ToLower() == "int")
{
memory = BitConverter.GetBytes(Convert.ToInt32(write));
size = 4;
}
else if (type.ToLower() == "byte")
{
memory = new byte[1];
memory[0] = Convert.ToByte(write, 16);
size = 1;
}
else if (type.ToLower() == "2bytes")
{
memory = new byte[2];
memory[0] = (byte)(Convert.ToInt32(write) % 256);
memory[1] = (byte)(Convert.ToInt32(write) / 256);
size = 2;
}
else if (type.ToLower() == "bytes")
{
if (write.Contains(",") || write.Contains(" ")) //check if it's a proper array
{
string[] stringBytes;
if (write.Contains(","))
stringBytes = write.Split(',');
else
stringBytes = write.Split(' ');
//Debug.WriteLine("write:" + write + " stringBytes:" + stringBytes);
int c = stringBytes.Count();
memory = new byte[c];
for (int i = 0; i < c; i++)
{
memory[i] = Convert.ToByte(stringBytes[i], 16);
}
size = stringBytes.Count();
}
else //wasnt array, only 1 byte
{
memory = new byte[1];
memory[0] = Convert.ToByte(write, 16);
size = 1;
}
}
else if (type.ToLower() == "double")
{
memory = BitConverter.GetBytes(Convert.ToDouble(write));
size = 8;
}
else if (type.ToLower() == "long")
{
memory = BitConverter.GetBytes(Convert.ToInt64(write));
size = 8;
}
else if (type.ToLower() == "string")
{
if (stringEncoding == null)
memory = System.Text.Encoding.UTF8.GetBytes(write);
else
memory = stringEncoding.GetBytes(write);
size = memory.Length;
}
//Debug.Write("DEBUG: Writing bytes [TYPE:" + type + " ADDR:" + theCode + "] " + String.Join(",", memory) + Environment.NewLine);
return WriteProcessMemory(pHandle, theCode, memory, (UIntPtr)size, IntPtr.Zero);
}
/// <summary>
/// Write to address and move by moveQty. Good for byte arrays. See https://github.com/erfg12/memory.dll/wiki/Writing-a-Byte-Array for more information.
/// </summary>
///<param name="code">address, module + pointer + offset, module + offset OR label in .ini file.</param>
///<param name="type">byte, bytes, float, int, string or long.</param>
/// <param name="write">byte to write</param>
/// <param name="moveQty">quantity to move</param>
/// <param name="file">path and name of .ini file (OPTIONAL)</param>
/// <returns></returns>
public bool WriteMove(string code, string type, string write, int moveQty, string file = "")
{
byte[] memory = new byte[4];
int size = 4;