-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmemflowNET.cs
More file actions
1079 lines (982 loc) · 43.8 KB
/
memflowNET.cs
File metadata and controls
1079 lines (982 loc) · 43.8 KB
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.Text;
using System.Diagnostics;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using memflowNET.Interop;
/// <summary>
/// Version 1.2.1.0 - memflow-ffi > 0.2.1
/// </summary>
namespace memflowNET
{
/// <summary>
/// A memflow connection to a VM.
/// </summary>
public unsafe class MFconnection : IDisposable
{
/// <summary>
/// Determining whether this instance initialized successfully.
/// </summary>
public readonly bool Success;
/// <summary>
/// Internal cache for log level.
/// </summary>
internal readonly int _loglevel;
/// <summary>
/// A settable log function.
/// </summary>
internal Action<string> PrintLog { get; set; }
/// <summary>
/// Internal inventory.
/// </summary>
private readonly Inventory* _inventory;
/// <summary>
/// Internal connector.
/// </summary>
private readonly ConnectorInstance_CBox_c_void_____CArc_c_void* _connector;
/// <summary>
/// Internal OS plugin.
/// </summary>
internal readonly OsInstance_CBox_c_void_____CArc_c_void* _osPlugin;
/// <summary>
/// Internal keyboard.
/// </summary>
private readonly CGlueTraitObj_CBox_c_void_____KeyboardVtbl_CGlueObjContainer_CBox_c_void_____CArc_c_void_____KeyboardRetTmp_CArc_c_void______________CArc_c_void_____KeyboardRetTmp_CArc_c_void* _keyboard;
/// <summary>
/// If device is FPGA, in which case dropping inventory crashes memflow.
/// </summary>
private bool _IsFpga;
/// <summary>
/// Connects to memflow using the provided connector.
/// </summary>
/// <param name="connector">A memflow connector, currently supported are 'kvm', 'qemu' and 'pcileech'.</param>
/// <param name="connectorArgs">Arguments for memflow connector.</param>
/// <param name="monitorKeyboard">If the keyboard inside the VM should be monitored for button presses.</param>
/// <param name="loglevel">The logging level of memflow.</param>
/// <param name="logging">The logging action that takes a single string as parameter.</param>
public unsafe MFconnection(string connector, string connectorArgs = "", bool monitorKeyboard = false, int loglevel = 1, Action<string>? logging = null)
{
if (!Environment.Is64BitProcess || IntPtr.Size != 8)
throw new PlatformNotSupportedException("Only 64 bit systems are supported.");
// check for root/admin privilege
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && ShellHelper.Bash($"id -u {Environment.UserName}") != "0")
throw new UnauthorizedAccessException("Must be started as root.");
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator) != true)
throw new UnauthorizedAccessException("Must be started as administrator.");
// set logger
if (logging != null)
PrintLog = logging;
else
PrintLog = Logger;
// enable debug level logging
Methods.mf_log_init((LevelFilter)loglevel);
this._loglevel = loglevel;
// load all available plugins
this._inventory = Methods.mf_inventory_scan();
if (loglevel > 2)
PrintLog($"### Inventory initialized: 0x{(IntPtr)this._inventory:X}");
// alloc connector struct
this._connector = (ConnectorInstance_CBox_c_void_____CArc_c_void*) Marshal.AllocCoTaskMem(sizeof(ConnectorInstance_CBox_c_void_____CArc_c_void));
if (connector == "pcileech" && connectorArgs.ToUpper().Contains("FPGA"))
this._IsFpga = true;
// initialize the connector
sbyte[] bName = Array.ConvertAll(Encoding.ASCII.GetBytes(connector + "\0"), b => unchecked((sbyte)b));
sbyte[] bArgs = new sbyte[1] { 0x0 }; // empty C string
if (connectorArgs.Length > 0)
bArgs = Array.ConvertAll(Encoding.ASCII.GetBytes(connectorArgs + "\0"), b => unchecked((sbyte)b));
fixed (sbyte* cName = &bName[0], cArgs = &bArgs[0])
{
if (Methods.mf_inventory_create_connector(this._inventory, cName, cArgs, this._connector) != 0)
{
PrintLog($"### Unable to initialize connector '{connector}'");
return;
}
}
if (loglevel > 2)
PrintLog($"### Connector initialized: 0x{(IntPtr)(*this._connector).container.instance.instance:X}");
// alloc OS Plugin struct
this._osPlugin = (OsInstance_CBox_c_void_____CArc_c_void*) Marshal.AllocCoTaskMem(sizeof(OsInstance_CBox_c_void_____CArc_c_void));
// initialize the OS plugin
bName = Array.ConvertAll(Encoding.ASCII.GetBytes("win32\0"), b => unchecked((sbyte)b));
fixed (sbyte* osName = &bName[0], osArgs = &bArgs[0])
{
if (Methods.mf_inventory_create_os(this._inventory, osName, osArgs, this._connector, this._osPlugin) != 0)
{
PrintLog("### Unable to initialize OS plugin 'win32'");
return;
}
}
if (monitorKeyboard)
{
// alloc keyboard struct
this._keyboard = (CGlueTraitObj_CBox_c_void_____KeyboardVtbl_CGlueObjContainer_CBox_c_void_____CArc_c_void_____KeyboardRetTmp_CArc_c_void______________CArc_c_void_____KeyboardRetTmp_CArc_c_void*) Marshal.AllocCoTaskMem(sizeof(CGlueTraitObj_CBox_c_void_____KeyboardVtbl_CGlueObjContainer_CBox_c_void_____CArc_c_void_____KeyboardRetTmp_CArc_c_void______________CArc_c_void_____KeyboardRetTmp_CArc_c_void));
// initialize keyboard
int res = Methods.mf_osinstance_keyboard(this._osPlugin, this._keyboard);
if (res < 0)
{
this._keyboard = null;
PrintLog($"### Failed to initialize keyboard!");
}
}
else
this._keyboard = null;
if (loglevel > 2)
PrintLog($"### OS plugin initialized: 0x{(IntPtr)(*this._osPlugin).container.instance.instance:X}");
this.Success = true;
}
/// <summary>
/// Clean up all objects.
/// </summary>
public void Dispose()
{
if (this._osPlugin != null)
{
// we don't need to drop connector as it was handed into osplugin
Methods.mf_os_drop(this._osPlugin);
Marshal.FreeCoTaskMem((IntPtr)this._keyboard);
Marshal.FreeCoTaskMem((IntPtr)this._osPlugin);
Marshal.FreeCoTaskMem((IntPtr)this._connector);
if (this._loglevel > 2)
PrintLog("### OS plugin/Connector freed");
}
else if (this._connector != null)
{
Methods.mf_connector_drop(this._connector);
Marshal.FreeCoTaskMem((IntPtr)this._connector);
if (this._loglevel > 2)
PrintLog("### Connector freed");
}
// dropping inventory on a FPGA device crashes memflow, so we skip it for now
if (!this._IsFpga)
Methods.mf_inventory_free(this._inventory);
if (this._loglevel > 2)
PrintLog("### Inventory freed");
}
/// <summary>
/// Gets a driver' module imported function by name from a process that uses the driver.
/// </summary>
/// <param name="modulName">The full name of the module.</param>
/// <param name="funtionName">The full name of the function.</param>
/// <param name="procName">The full name of the process that has the driver loaded.</param>
/// <returns>The offset of the imported function, 0 otherwise.</returns>
public ulong GetKernelModuleImport(string modulName, string functionName, string procName)
{
// get kernel module (driver)
ModuleInfo moduleInfo = new();
byte[] bName = Encoding.ASCII.GetBytes(modulName);
fixed (byte* cName = &bName[0])
{
CSliceRef_u8 processSearch = new()
{
data = cName,
len = (uint)modulName.Length
};
if (Interop.Methods.mf_osinstance_module_by_name(this._osPlugin, processSearch, &moduleInfo) != 0)
{
if (this._loglevel > 0)
PrintLog($"### Kernel Module '{modulName}' could not be found!");
return 0;
}
}
// get process that imports the driver
var proc = (ProcessInstance_CBox_c_void_____CArc_c_void*) Marshal.AllocCoTaskMem(sizeof(ProcessInstance_CBox_c_void_____CArc_c_void));
if (!procName.ToLower().EndsWith(".exe"))
procName += ".exe";
bName = Encoding.ASCII.GetBytes(procName);
fixed (byte* cName = &bName[0])
{
CSliceRef_u8 processSearch = new()
{
data = cName,
len = (uint)procName.Length
};
if (Interop.Methods.mf_osinstance_process_by_name(this._osPlugin, processSearch, proc) != 0)
{
Marshal.FreeCoTaskMem((IntPtr)proc);
if (this._loglevel > 0)
PrintLog($"### Process '{procName}' could not be found!");
return 0;
}
}
// get import of said driver from process
ImportInfo importInfo = new();
bName = Encoding.ASCII.GetBytes(functionName);
fixed (byte* cName = &bName[0])
{
CSliceRef_u8 functionSearch = new()
{
data = cName,
len = (uint)functionName.Length
};
if (Interop.Methods.mf_processinstance_module_import_by_name(proc, &moduleInfo, functionSearch, &importInfo) != 0)
{
if (this._loglevel > 0)
PrintLog($"### Function Import '{functionName}' could not be found!");
return 0;
}
}
return importInfo.offset;
}
/// <summary>
/// Checks if a virtual key is being pressed.
/// </summary>
/// <param name="vk">The virtual key code of the key: https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes</param>
/// <returns>True if the key is currently held down.</returns>
public bool IsKeyDown(int vk)
{
if (this._keyboard == null)
throw new NotSupportedException("Keyboard monitoring not initialized!");
return Methods.mf_keyboard_is_down(this._keyboard, vk);
}
/// <summary>
/// Logs a message to console/output.
/// </summary>
/// <param name="msg">The message to log.</param>
private static void Logger(string msg)
{
Console.WriteLine(msg);
Debug.WriteLine(msg);
}
}
/// <summary>
/// A memflow process module info.
/// </summary>
public readonly struct MFprocessmodule
{
/// <summary>
/// The base address of the module.
/// </summary>
public readonly ulong BaseAddress;
/// <summary>
/// The total size of the module.
/// </summary>
public readonly uint Size;
/// <summary>
/// The name of the module.
/// </summary>
public readonly string Name;
public MFprocessmodule(ulong baseAddr, uint size, string name)
{
this.BaseAddress = baseAddr;
this.Size = size;
this.Name = name;
}
}
/// <summary>
/// A memflow process instance.
/// </summary>
public unsafe class MFprocess : IDisposable
{
/// <summary>
/// Determining whether this instance initialized successfully.
/// </summary>
public readonly bool Success;
/// <summary>
/// The base address of the process. On Windows this is the address to [_EPROCESS].
/// </summary>
public readonly ulong Address;
/// <summary>
/// The process' ID.
/// </summary>
public readonly uint PId;
/// <summary>
/// The process' name.
/// </summary>
public readonly string? Name;
/// <summary>
/// The full path to the process' executable.
/// </summary>
public readonly string? Path;
/// <summary>
/// The arguments the process has been started with.
/// </summary>
public readonly string? Commandline;
/// <summary>
/// The main module of the process.
/// </summary>
public readonly MFprocessmodule MainModule;
/// <summary>
/// Internal log action.
/// </summary>
private Action<string> PrintLog { get; set; }
/// <summary>
/// Internal cache for log level.
/// </summary>
private readonly int _loglevel;
/// <summary>
/// Internal process.
/// </summary>
private readonly ProcessInstance_CBox_c_void_____CArc_c_void* _process;
/// <summary>
/// Internal OS plugin from MFconnection.
/// </summary>
private readonly OsInstance_CBox_c_void_____CArc_c_void* _osPlugin;
/// <summary>
/// Pointer to a 4096 bytes allocated unmanaged memory region used to directly cache read/write results.
/// </summary>
private readonly byte* _rwBuffer;
/// <summary>
/// Gets a process inside the VM by name.
/// </summary>
/// <param name="connection">A fully initialized MFconnection.</param>
/// <param name="processName">The processes name.</param>
public unsafe MFprocess(ref MFconnection connection, string processName)
{
this._loglevel = connection._loglevel;
this.PrintLog = connection.PrintLog;
if (!connection.Success)
{
PrintLog("### MFconnection not valid!");
return;
}
// alloc process struct
this._process = (ProcessInstance_CBox_c_void_____CArc_c_void*)Marshal.AllocCoTaskMem(sizeof(ProcessInstance_CBox_c_void_____CArc_c_void));
// define search
string procName = processName;
if (!procName.ToLower().EndsWith(".exe"))
procName += ".exe";
byte[] bName = Encoding.ASCII.GetBytes(procName);
fixed (byte* cName = &bName[0])
{
CSliceRef_u8 processSearch = new()
{
data = cName,
len = (uint)procName.Length
};
// find a specific process based on its name
if (Methods.mf_osinstance_process_by_name(connection._osPlugin, processSearch, this._process) != 0)
{
// in some rare cases dropping a failed process struct through memflow will trigger a memory exception so we we have to manually dispose it here for now
Marshal.FreeCoTaskMem((IntPtr)this._process);
this._process = null;
if (this._loglevel > 0)
PrintLog($"### Process '{procName}' could not be found!");
return;
}
}
// get process infos
ProcessInfo* info = Methods.mf_processinstance_info(this._process);
this.Address = (*info).address;
this.PId = (*info).pid;
this.Name = GetCStringFromPtr((*info).name);
this.Path = GetCStringFromPtr((*info).path);
this.Commandline = GetCStringFromPtr((*info).command_line);
// get main module
ModuleInfo mainModule = new();
if (Methods.mf_processinstance_primary_module(this._process, &mainModule) != 0)
{
if (this._loglevel > 0)
PrintLog("### Process main module could not be found!");
return;
}
this.MainModule = new MFprocessmodule(mainModule.@base, (uint)mainModule.size, this.Name);
if (this._loglevel > 2)
PrintLog($"### Process found: 0x{this.MainModule.BaseAddress:X} | {this.MainModule.Size / 1024} kiB | {this.PId} | {this.Name} | {this.Path}");
// allocate read/write buffer
this._rwBuffer = (byte*)NativeMemory.AllocZeroed(4096);
this._osPlugin = connection._osPlugin;
this.Success = true;
}
/// <summary>
/// Gets a process inside the VM by PId.
/// </summary>
/// <param name="connection">A fully initialized MFconnection.</param>
/// <param name="processId">The processes Id.</param>
public unsafe MFprocess(ref MFconnection connection, int processId)
{
this._loglevel = connection._loglevel;
this.PrintLog = connection.PrintLog;
if (!connection.Success)
{
PrintLog("### MFconnection not valid!");
return;
}
// alloc process struct
this._process = (ProcessInstance_CBox_c_void_____CArc_c_void*) Marshal.AllocCoTaskMem(sizeof(ProcessInstance_CBox_c_void_____CArc_c_void));
// find a specific process based on its Id
if (Methods.mf_osinstance_process_by_pid(connection._osPlugin, (uint)processId, this._process) != 0)
{
// in some rare cases dropping a failed process struct through memflow will trigger a memory exception so we we have to manually dispose it here for now
Marshal.FreeCoTaskMem((IntPtr)this._process);
this._process = null;
if (this._loglevel > 0)
PrintLog($"### Process Id'{processId}' could not be found!");
return;
}
// get process infos
ProcessInfo* info = Methods.mf_processinstance_info(this._process);
this.Address = (*info).address;
this.PId = (*info).pid;
this.Name = GetCStringFromPtr((*info).name);
this.Path = GetCStringFromPtr((*info).path);
this.Commandline = GetCStringFromPtr((*info).command_line);
// get main module
ModuleInfo mainModule = new();
if (Methods.mf_processinstance_primary_module(this._process, &mainModule) != 0)
{
if (this._loglevel > 0)
PrintLog("### Process main module could not be found!");
return;
}
this.MainModule = new MFprocessmodule(mainModule.@base, (uint)mainModule.size, this.Name);
if (this._loglevel > 2)
PrintLog($"### Process found: 0x{this.MainModule.BaseAddress:X} | {this.MainModule.Size / 1024} kiB | {this.PId} | {this.Name} | {this.Path}");
// allocate read/write buffer
this._rwBuffer = (byte*)NativeMemory.AllocZeroed(4096);
this._osPlugin = connection._osPlugin;
this.Success = true;
}
/// <summary>
/// Reads a null-terminated ASCII string from a pointer.
/// </summary>
/// <param name="ptr">The pointer.</param>
/// <returns>The ASCII representation of the string the pointer points to.</returns>
private string GetCStringFromPtr(sbyte* ptr)
{
//return Marshal.PtrToStringAnsi((IntPtr)ptr);
for (int i = 0; i < 256; i++) // sanity
{
// find terminator
if (*(ptr + i) == (byte)0x00)
return Encoding.ASCII.GetString((byte*)ptr, i);
}
return "";
}
/// <summary>
/// Gets a process' module by name.
/// </summary>
/// <param name="name">The full name of the module.</param>
/// <returns>The process' module.</returns>
public MFprocessmodule GetModule(string name)
{
ModuleInfo moduleInfo = new();
byte[] bName = Encoding.ASCII.GetBytes(name);
fixed (byte* cName = &bName[0])
{
CSliceRef_u8 processSearch = new()
{
data = cName,
len = (uint)name.Length
};
if (Methods.mf_processinstance_module_by_name(this._process, processSearch, &moduleInfo) != 0)
{
if (this._loglevel > 0)
PrintLog($"### Module '{name}' could not be found!");
return new MFprocessmodule(0, 0, "INVALID");
}
}
return new MFprocessmodule(moduleInfo.@base, (uint)moduleInfo.size, GetCStringFromPtr(moduleInfo.name));
}
/// <summary>
/// If the process instance is up and running.
/// </summary>
/// <returns>True if process hasn't exited yet.</returns>
public bool IsRunning()
{
ProcessState state = Methods.mf_processinstance_state(this._process);
if (state.tag == ProcessState_Tag.ProcessState_Alive)
return true;
return false;
}
/// <summary>
/// Reads a number of bytes from an address of the process.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <param name="data">The pointer to the raw array that will be filled with the read data.</param>
/// <param name="length">The length of the byte array that should be read.</param>
/// <returns>True if reading was successful.</returns>
public bool ReadBytesDirect(ulong address, byte* data, uint length)
{
CSliceMut_u8 cBytes = new()
{
data = data,
len = (nuint)length
};
if (Methods.mf_processinstance_read_raw_into(this._process, address, cBytes) != 0)
{
if (this._loglevel > 1)
PrintLog($"### Failed to read data from 0x{address:X}!");
return false;
}
return true;
}
/// <summary>
/// Reads a number of bytes from an address of the process and stores them in the internal allocated buffer.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <param name="length">The length of the byte array that should be read.</param>
/// <returns>True if reading was successful.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool ReadBytesCached(ulong address, uint length)
{
CSliceMut_u8 cBytes = new()
{
data = this._rwBuffer,
len = (nuint)length
};
if (Methods.mf_processinstance_read_raw_into(this._process, address, cBytes) != 0)
{
if (this._loglevel > 1)
PrintLog($"### Failed to read data from 0x{address:X}!");
return false;
}
return true;
}
/// <summary>
/// Reads a number of bytes smaller than 4096 bytes from an address of the process.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <param name="length">The length of the byte array that should be read. Maximum size is 4096.</param>
/// <returns>The raw byte array, zero filled if read was not successful.</returns>
/// <remarks>Maximum length of the array is 4096 bytes. Use ReadBytesUncapped() if you need more.</remarks>
public byte[] ReadBytes(ulong address, uint length)
{
byte[] ba = new byte[length];
if (!ReadBytesCached(address, length))
return ba;
Unsafe.CopyBlockUnaligned(Unsafe.AsPointer(ref ba[0]), this._rwBuffer, length);
return ba;
}
/// <summary>
/// Reads a number of bytes from an address of the process.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <param name="length">The length of the byte array that should be read.</param>
/// <returns>The raw byte array, zero filled if read was not successful.</returns>
/// <remarks>This is slower than the buffered ReadBytes(), only use this if neccessary.</remarks>
public byte[] ReadBytesUncapped(ulong address, uint length)
{
byte[] ba = new byte[length];
fixed (byte* ptr = &ba[0])
{
CSliceMut_u8 cBytes = new()
{
data = ptr,
len = (nuint)length
};
if (Methods.mf_processinstance_read_raw_into(this._process, address, cBytes) != 0)
{
if (this._loglevel > 1)
PrintLog($"### Failed to read data from 0x{address:X}!");
}
return ba;
}
}
/// <summary>
/// Reads a given type from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The given type representation of the data, 0 or empty if read was not successful.</returns>
public T? Read<T>(ulong address)
{
if (!ReadBytesCached(address, (uint)Unsafe.SizeOf<T>()))
return default(T);
return Unsafe.Read<T>(this._rwBuffer);
}
/// <summary>
/// Reads an unsigned byte from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The byte representation of the data, 0 if read was not successful.</returns>
public Byte ReadByte(ulong address)
{
if (!ReadBytesCached(address, 1))
return 0;
return Unsafe.Read<Byte>(this._rwBuffer);
}
/// <summary>
/// Reads a 2 byte integer from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The integer representation of the data, 0 if read was not successful.</returns>
public Int16 ReadInt16(ulong address)
{
if (!ReadBytesCached(address, 2))
return 0;
//return *(Int16*)this._rwBuffer;
return Unsafe.Read<Int16>(this._rwBuffer);
}
/// <summary>
/// Reads a 4 byte integer from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The integer representation of the data, 0 if read was not successful.</returns>
public Int32 ReadInt32(ulong address)
{
if (!ReadBytesCached(address, 4))
return 0;
return Unsafe.Read<Int32>(this._rwBuffer);
}
/// <summary>
/// Reads a 8 byte integer from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The integer representation of the data, 0 if read was not successful.</returns>
public Int64 ReadInt64(ulong address)
{
if (!ReadBytesCached(address, 8))
return 0;
return Unsafe.Read<Int64>(this._rwBuffer);
}
/// <summary>
/// Reads a 2 byte unsigned integer from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The integer representation of the data, 0 if read was not successful.</returns>
public UInt16 ReadUInt16(ulong address)
{
if (!ReadBytesCached(address, 2))
return 0;
return Unsafe.Read<UInt16>(this._rwBuffer);
}
/// <summary>
/// Reads a 4 byte unsigned integer from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The integer representation of the data, 0 if read was not successful.</returns>
public UInt32 ReadUInt32(ulong address)
{
if (!ReadBytesCached(address, 4))
return 0;
return Unsafe.Read<UInt32>(this._rwBuffer);
}
/// <summary>
/// Reads a 8 byte unsigned integer from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The integer representation of the data, 0 if read was not successful.</returns>
public UInt64 ReadUInt64(ulong address)
{
if (!ReadBytesCached(address, 8))
return 0;
return Unsafe.Read<UInt64>(this._rwBuffer);
}
/// <summary>
/// Reads a 4 byte single-precision float from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The float representation of the data, 0 if read was not successful.</returns>
public Single ReadSingle(ulong address)
{
if (!ReadBytesCached(address, 4))
return 0;
return Unsafe.Read<Single>(this._rwBuffer);
}
/// <summary>
/// Reads a 8 byte double-precision float from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <returns>The float representation of the data, 0 if read was not successful.</returns>
public Double ReadDouble(ulong address)
{
if (!ReadBytesCached(address, 8))
return 0;
return Unsafe.Read<Double>(this._rwBuffer);
}
/// <summary>
/// Reads a fixed length string from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <param name="length">The length of the string in bytes.</param>
/// <param name="encoding">The encoding to use when reading.</param>
/// <returns>The string representation of the data, empty if read was not successful.</returns>
public string ReadFixedString(ulong address, uint length, Encoding encoding)
{
if (!ReadBytesCached(address, length))
return "";
return encoding.GetString(this._rwBuffer, (int)length);
}
/// <summary>
/// Reads an unknown length string, up to the first terminator, from memory.
/// </summary>
/// <param name="address">The virtual address to read from.</param>
/// <param name="encoding">The encoding to use when reading.</param>
/// <param name="length">The maximum length of the string in bytes.</param>
/// <returns>The string representation of the data, empty if read was not successful.</returns>
public string ReadVariableString(ulong address, Encoding encoding, uint maxLength = 32)
{
if (!ReadBytesCached(address, maxLength))
return "";
byte* p = this._rwBuffer;
for (int i = 0; i < maxLength; i++, p++)
{
// find terminator
if (*(p) == (byte)0x00)
return encoding.GetString(this._rwBuffer, i);
//return new string((sbyte*)this._rwBuffer); // DANGER! this will create a buffer-overflow if no null-terminator is present
}
return encoding.GetString(this._rwBuffer, (int)maxLength);
}
/// <summary>
/// Writes a byte array to an address of the process.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The data to write.</param>
/// <param name="length">The length of the byte array that should be written.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteBytesDirect(ulong address, byte* data, int length)
{
CSliceRef_u8 cBytes = new()
{
data = data,
len = (nuint)length,
};
if (Methods.mf_processinstance_write_raw(this._process, address, cBytes) != 0)
{
if (this._loglevel > 1)
PrintLog($"### Failed to write data to 0x{address:X}!");
return false;
}
return true;
}
/// <summary>
/// Writes a byte array from the internal buffer to an address of the process.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="length">The length of the data to write from buffer.</param>
/// <returns>True if writing was successful.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool WriteBytesCached(ulong address, int length)
{
CSliceRef_u8 cBytes = new()
{
data = this._rwBuffer,
len = (nuint)length,
};
if (Methods.mf_processinstance_write_raw(this._process, address, cBytes) != 0)
{
if (this._loglevel > 1)
PrintLog($"### Failed to write data to 0x{address:X}!");
return false;
}
return true;
}
/// <summary>
/// Writes a byte array smaller than 4096 bytes to an address of the process.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The data to write. Maximum size is 4096 bytes.</param>
/// <returns>True if writing was successful.</returns>
/// <remarks>Maximum length of the array is 4096 bytes. Use WriteBytesUncapped() if you need more.</remarks>
public bool WriteBytes(ulong address, byte[] data)
{
Unsafe.CopyBlockUnaligned(this._rwBuffer, Unsafe.AsPointer(ref data[0]), (uint)data.Length);
return WriteBytesCached(address, data.Length);
}
/// <summary>
/// Writes a byte array to an address of the process.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The data to write.</param>
/// <returns>True if writing was successful.</returns>
/// <remarks>This is slower than the buffered WriteBytes(), only use this if neccessary.</remarks>
public bool WriteBytesUncapped(ulong address, byte[] data)
{
fixed (byte* ptr = &data[0])
{
CSliceRef_u8 cBytes = new()
{
data = ptr,
len = (nuint)data.Length,
};
if (Methods.mf_processinstance_write_raw(this._process, address, cBytes) != 0)
{
if (this._loglevel > 1)
PrintLog($"### Failed to write data to 0x{address:X}!");
return false;
}
return true;
}
}
/// <summary>
/// Writes a given type to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The data to write.</param>
/// <returns>True if writing was successful.</returns>
public bool Write<T>(ulong address, T data)
{
Unsafe.Write<T>(this._rwBuffer, data);
return WriteBytesCached(address, Unsafe.SizeOf<T>());
}
/// <summary>
/// Writes an unsigned byte to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The byte to write.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteByte(ulong address, byte data)
{
Unsafe.Write<Byte>(this._rwBuffer, data);
return WriteBytesCached(address, 1);
}
/// <summary>
/// Writes a 2 byte integer to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The integer to write.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteInt16(ulong address, Int16 data)
{
Unsafe.Write<Int16>(this._rwBuffer, data);
return WriteBytesCached(address, 2);
}
/// <summary>
/// Writes a 4 byte integer to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The integer to write.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteInt32(ulong address, Int32 data)
{
Unsafe.Write<Int32>(this._rwBuffer, data);
return WriteBytesCached(address, 4);
}
/// <summary>
/// Writes a 8 byte integer to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The integer to write.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteInt64(ulong address, Int64 data)
{
Unsafe.Write<Int64>(this._rwBuffer, data);
return WriteBytesCached(address, 8);
}
/// <summary>
/// Writes a 2 byte unsigned integer to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The integer to write.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteUInt16(ulong address, UInt16 data)
{
Unsafe.Write<UInt16>(this._rwBuffer, data);
return WriteBytesCached(address, 2);
}
/// <summary>
/// Writes a 4 byte unsigned integer to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The integer to write.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteUInt32(ulong address, UInt32 data)
{
Unsafe.Write<UInt32>(this._rwBuffer, data);
return WriteBytesCached(address, 4);
}
/// <summary>
/// Writes a 8 byte unsigned integer to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The integer to write.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteUInt64(ulong address, UInt64 data)
{
Unsafe.Write<UInt64>(this._rwBuffer, data);
return WriteBytesCached(address, 8);
}
/// <summary>
/// Writes a 4 byte single-precision float to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The float to write.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteSingle(ulong address, float data)
{
Unsafe.Write<Single>(this._rwBuffer, data);
return WriteBytesCached(address, 4);
}
/// <summary>
/// Writes a 8 byte double-precision float to memory.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The float to write.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteDouble(ulong address, float data)
{
Unsafe.Write<Double>(this._rwBuffer, data);
return WriteBytesCached(address, 8);
}
/// <summary>
/// Writes a managed string as an encoded byte sequence to memory.
/// If encoding uses single byte representation this will add a null-terminator.
/// </summary>
/// <param name="address">The virtual address to write to.</param>
/// <param name="data">The string to write.</param>
/// <param name="encoding">The encoding to use when writing.</param>
/// <returns>True if writing was successful.</returns>
public bool WriteString(ulong address, string data, Encoding encoding)