-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathProgram.cs
1687 lines (1275 loc) · 66.3 KB
/
Program.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.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using McMaster.Extensions.CommandLineUtils;
namespace read_memory_64_bit;
class Program
{
static string AppVersionId => "2024-05-26";
static int Main(string[] args)
{
var app = new CommandLineApplication
{
Name = "read-memory-64-bit",
Description = "Welcome to the Sanderling memory reading command-line interface. This tool helps you read objects from the memory of a 64-bit EVE Online client process and save it to a file. In addition to that, you have the option to save the entire memory contents of a game client process to a file.\nTo get help or report an issue, see the project website at https://github.com/Arcitectus/Sanderling",
};
app.HelpOption(inherited: true);
app.VersionOption(template: "-v|--version", shortFormVersion: "version " + AppVersionId);
app.Command("save-process-sample", saveProcessSampleCmd =>
{
saveProcessSampleCmd.Description = "Save a sample from a live process to a file. Use the '--pid' parameter to specify the process id.";
var processIdParam =
saveProcessSampleCmd.Option("--pid", "[Required] Id of the Windows process to read from.", CommandOptionType.SingleValue).IsRequired(errorMessage: "From which process should I read?");
var delaySecondsParam =
saveProcessSampleCmd.Option("--delay", "Timespan to wait before starting the collection of the sample, in seconds.", CommandOptionType.SingleValue);
saveProcessSampleCmd.OnExecute(() =>
{
var processIdArgument = processIdParam.Value();
var delayMilliSeconds =
delaySecondsParam.HasValue() ?
(int)(double.Parse(delaySecondsParam.Value()) * 1000) :
0;
var processId = int.Parse(processIdArgument);
if (0 < delayMilliSeconds)
{
Console.WriteLine("Delaying for " + delayMilliSeconds + " milliseconds.");
Task.Delay(TimeSpan.FromMilliseconds(delayMilliSeconds)).Wait();
}
Console.WriteLine("Starting to collect the sample...");
var processSampleFile = GetProcessSampleFileFromProcessId(processId);
Console.WriteLine("Completed collecting the sample.");
var processSampleId = Pine.CommonConversion.StringBase16(
Pine.CommonConversion.HashSHA256(processSampleFile));
var fileName = "process-sample-" + processSampleId[..10] + ".zip";
System.IO.File.WriteAllBytes(fileName, processSampleFile);
Console.WriteLine("Saved sample {0} to file '{1}'.", processSampleId, fileName);
});
});
app.Command("read-memory-eve-online", readMemoryEveOnlineCmd =>
{
readMemoryEveOnlineCmd.Description = "Read the memory of an 64 bit EVE Online client process. You can use a live process ('--pid') or a process sample file ('--source-file') as the source.";
var processIdParam = readMemoryEveOnlineCmd.Option("--pid", "Id of the Windows process to read from.", CommandOptionType.SingleValue);
var rootAddressParam = readMemoryEveOnlineCmd.Option("--root-address", "Address of the UI root. If the address is not specified, the program searches the whole process memory for UI roots.", CommandOptionType.SingleValue);
var sourceFileParam = readMemoryEveOnlineCmd.Option("--source-file", "Process sample file to read from.", CommandOptionType.SingleValue);
var outputFileParam = readMemoryEveOnlineCmd.Option("--output-file", "File to save the memory reading result to.", CommandOptionType.SingleValue);
var removeOtherDictEntriesParam = readMemoryEveOnlineCmd.Option("--remove-other-dict-entries", "Use this to remove the other dict entries from the UI nodes in the resulting JSON representation.", CommandOptionType.NoValue);
var warmupIterationsParam = readMemoryEveOnlineCmd.Option("--warmup-iterations", "Only to measure execution time: Use this to perform additional warmup runs before measuring execution time.", CommandOptionType.SingleValue);
readMemoryEveOnlineCmd.OnExecute(() =>
{
var processIdArgument = processIdParam.Value();
var rootAddressArgument = rootAddressParam.Value();
var sourceFileArgument = sourceFileParam.Value();
var outputFileArgument = outputFileParam.Value();
var removeOtherDictEntriesArgument = removeOtherDictEntriesParam.HasValue();
var warmupIterationsArgument = warmupIterationsParam.Value();
var processId =
0 < processIdArgument?.Length
?
(int?)int.Parse(processIdArgument)
:
null;
(IMemoryReader, IImmutableList<ulong>) GetMemoryReaderAndRootAddressesFromProcessSampleFile(byte[] processSampleFile)
{
var processSampleId = Pine.CommonConversion.StringBase16(
Pine.CommonConversion.HashSHA256(processSampleFile));
Console.WriteLine($"Reading from process sample {processSampleId}.");
var processSampleUnpacked = ProcessSample.ProcessSampleFromZipArchive(processSampleFile);
var memoryReader = new MemoryReaderFromProcessSample(processSampleUnpacked.memoryRegions);
var searchUIRootsStopwatch = System.Diagnostics.Stopwatch.StartNew();
var memoryRegions =
processSampleUnpacked.memoryRegions
.Select(memoryRegion => (memoryRegion.baseAddress, length: memoryRegion.content.Value.Length))
.ToImmutableList();
var uiRootCandidatesAddresses =
EveOnline64.EnumeratePossibleAddressesForUIRootObjects(memoryRegions, memoryReader)
.ToImmutableList();
searchUIRootsStopwatch.Stop();
Console.WriteLine($"Found {uiRootCandidatesAddresses.Count} candidates for UIRoot in {(int)searchUIRootsStopwatch.Elapsed.TotalSeconds} seconds: " + string.Join(",", uiRootCandidatesAddresses.Select(address => $"0x{address:X}")));
return (memoryReader, uiRootCandidatesAddresses);
}
(IMemoryReader, IImmutableList<ulong>) GetMemoryReaderAndWithSpecifiedRootFromProcessSampleFile(byte[] processSampleFile, ulong rootAddress)
{
var processSampleId = Pine.CommonConversion.StringBase16(
Pine.CommonConversion.HashSHA256(processSampleFile));
Console.WriteLine($"Reading from process sample {processSampleId}.");
var processSampleUnpacked = ProcessSample.ProcessSampleFromZipArchive(processSampleFile);
var memoryReader = new MemoryReaderFromProcessSample(processSampleUnpacked.memoryRegions);
Console.WriteLine($"Reading UIRoot from specified address: {rootAddress}");
return (memoryReader, ImmutableList<ulong>.Empty.Add(rootAddress));
}
(IMemoryReader, IImmutableList<ulong>) GetMemoryReaderAndRootAddresses()
{
if (processId.HasValue)
{
var possibleRootAddresses = 0 < rootAddressArgument?.Length ? ImmutableList.Create(ParseULong(rootAddressArgument)) : EveOnline64.EnumeratePossibleAddressesForUIRootObjectsFromProcessId(processId.Value);
return (new MemoryReaderFromLiveProcess(processId.Value), possibleRootAddresses);
}
if (!(0 < sourceFileArgument?.Length))
{
throw new Exception("Where should I read from?");
}
if (0 < rootAddressArgument?.Length)
{
return GetMemoryReaderAndWithSpecifiedRootFromProcessSampleFile(System.IO.File.ReadAllBytes(sourceFileArgument), ParseULong(rootAddressArgument));
}
return GetMemoryReaderAndRootAddressesFromProcessSampleFile(System.IO.File.ReadAllBytes(sourceFileArgument));
}
var (memoryReader, uiRootCandidatesAddresses) = GetMemoryReaderAndRootAddresses();
IImmutableList<UITreeNode> ReadUITrees() =>
uiRootCandidatesAddresses
.Select(uiTreeRoot => EveOnline64.ReadUITreeFromAddress(uiTreeRoot, memoryReader, 99))
.Where(uiTree => uiTree != null)
.ToImmutableList();
if (warmupIterationsArgument != null)
{
var iterations = int.Parse(warmupIterationsArgument);
Console.WriteLine("Performing " + iterations + " warmup iterations...");
for (var i = 0; i < iterations; i++)
{
ReadUITrees().ToList();
System.Threading.Thread.Sleep(1111);
}
}
var readUiTreesStopwatch = System.Diagnostics.Stopwatch.StartNew();
var uiTrees = ReadUITrees();
readUiTreesStopwatch.Stop();
var uiTreesWithStats =
uiTrees
.Select(uiTree =>
new
{
uiTree = uiTree,
nodeCount = uiTree.EnumerateSelfAndDescendants().Count()
})
.OrderByDescending(uiTreeWithStats => uiTreeWithStats.nodeCount)
.ToImmutableList();
var uiTreesReport =
uiTreesWithStats
.Select(uiTreeWithStats => $"\n0x{uiTreeWithStats.uiTree.pythonObjectAddress:X}: {uiTreeWithStats.nodeCount} nodes.")
.ToImmutableList();
Console.WriteLine($"Read {uiTrees.Count} UI trees in {(int)readUiTreesStopwatch.Elapsed.TotalMilliseconds} milliseconds:" + string.Join("", uiTreesReport));
var largestUiTree =
uiTreesWithStats
.OrderByDescending(uiTreeWithStats => uiTreeWithStats.nodeCount)
.FirstOrDefault().uiTree;
if (largestUiTree != null)
{
var uiTreePreparedForFile = largestUiTree;
if (removeOtherDictEntriesArgument)
{
uiTreePreparedForFile = uiTreePreparedForFile.WithOtherDictEntriesRemoved();
}
var serializeStopwatch = System.Diagnostics.Stopwatch.StartNew();
var uiTreeAsJson = EveOnline64.SerializeMemoryReadingNodeToJson(uiTreePreparedForFile);
serializeStopwatch.Stop();
Console.WriteLine(
"Serialized largest tree to " + uiTreeAsJson.Length + " characters of JSON in " +
serializeStopwatch.ElapsedMilliseconds + " milliseconds.");
var fileContent = System.Text.Encoding.UTF8.GetBytes(uiTreeAsJson);
var sampleId = Pine.CommonConversion.StringBase16(Pine.CommonConversion.HashSHA256(fileContent));
var outputFilePath = outputFileArgument;
if (!(0 < outputFileArgument?.Length))
{
var outputFileName = "eve-online-memory-reading-" + sampleId[..10] + ".json";
outputFilePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), outputFileName);
Console.WriteLine(
"I found no configuration of an output file path, so I use '" +
outputFilePath + "' as the default.");
}
System.IO.File.WriteAllBytes(outputFilePath, fileContent);
Console.WriteLine($"I saved memory reading {sampleId} from address 0x{largestUiTree.pythonObjectAddress:X} to file '{outputFilePath}'.");
}
else
{
Console.WriteLine("No largest UI tree.");
}
});
});
app.OnExecute(() =>
{
Console.WriteLine("Please specify a subcommand.");
app.ShowHelp();
return 1;
});
return app.Execute(args);
}
static byte[] GetProcessSampleFileFromProcessId(int processId)
{
var process = System.Diagnostics.Process.GetProcessById(processId);
var beginMainWindowClientAreaScreenshotBmp = BMPFileFromBitmap(GetScreenshotOfWindowClientAreaAsBitmap(process.MainWindowHandle));
var (committedRegions, logEntries) = EveOnline64.ReadCommittedMemoryRegionsWithContentFromProcessId(processId);
var endMainWindowClientAreaScreenshotBmp = BMPFileFromBitmap(GetScreenshotOfWindowClientAreaAsBitmap(process.MainWindowHandle));
return ProcessSample.ZipArchiveFromProcessSample(
committedRegions,
logEntries,
beginMainWindowClientAreaScreenshotBmp: beginMainWindowClientAreaScreenshotBmp,
endMainWindowClientAreaScreenshotBmp: endMainWindowClientAreaScreenshotBmp);
}
// Screenshot implementation found at https://github.com/Viir/bots/blob/225c680115328d9ba0223760cec85d56f2ea9a87/implement/templates/locate-object-in-window/src/BotEngine/VolatileHostWindowsApi.elm#L479-L557
static public byte[] BMPFileFromBitmap(System.Drawing.Bitmap bitmap)
{
using var stream = new System.IO.MemoryStream();
bitmap.Save(stream, format: System.Drawing.Imaging.ImageFormat.Bmp);
return stream.ToArray();
}
static public int[][] GetScreenshotOfWindowAsPixelsValuesR8G8B8(IntPtr windowHandle)
{
var screenshotAsBitmap = GetScreenshotOfWindowAsBitmap(windowHandle);
if (screenshotAsBitmap == null)
return null;
var bitmapData = screenshotAsBitmap.LockBits(
new System.Drawing.Rectangle(0, 0, screenshotAsBitmap.Width, screenshotAsBitmap.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
int byteCount = bitmapData.Stride * screenshotAsBitmap.Height;
byte[] pixelsArray = new byte[byteCount];
IntPtr ptrFirstPixel = bitmapData.Scan0;
Marshal.Copy(ptrFirstPixel, pixelsArray, 0, pixelsArray.Length);
screenshotAsBitmap.UnlockBits(bitmapData);
var pixels = new int[screenshotAsBitmap.Height][];
for (var rowIndex = 0; rowIndex < screenshotAsBitmap.Height; ++rowIndex)
{
var rowPixelValues = new int[screenshotAsBitmap.Width];
for (var columnIndex = 0; columnIndex < screenshotAsBitmap.Width; ++columnIndex)
{
var pixelBeginInArray = bitmapData.Stride * rowIndex + columnIndex * 3;
var red = pixelsArray[pixelBeginInArray + 2];
var green = pixelsArray[pixelBeginInArray + 1];
var blue = pixelsArray[pixelBeginInArray + 0];
rowPixelValues[columnIndex] = (red << 16) | (green << 8) | blue;
}
pixels[rowIndex] = rowPixelValues;
}
return pixels;
}
// https://github.com/Viir/bots/blob/225c680115328d9ba0223760cec85d56f2ea9a87/implement/templates/locate-object-in-window/src/BotEngine/VolatileHostWindowsApi.elm#L535-L557
static public System.Drawing.Bitmap GetScreenshotOfWindowAsBitmap(IntPtr windowHandle)
{
SetProcessDPIAware();
var windowRect = new WinApi.Rect();
if (WinApi.GetWindowRect(windowHandle, ref windowRect) == IntPtr.Zero)
return null;
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
var asBitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
System.Drawing.Graphics.FromImage(asBitmap).CopyFromScreen(
windowRect.left,
windowRect.top,
0,
0,
new System.Drawing.Size(width, height),
System.Drawing.CopyPixelOperation.SourceCopy);
return asBitmap;
}
static public System.Drawing.Bitmap GetScreenshotOfWindowClientAreaAsBitmap(IntPtr windowHandle)
{
SetProcessDPIAware();
var clientRect = new WinApi.Rect();
if (WinApi.GetClientRect(windowHandle, ref clientRect) == IntPtr.Zero)
return null;
var clientRectLeftTop = new WinApi.Point { x = clientRect.left, y = clientRect.top };
var clientRectRightBottom = new WinApi.Point { x = clientRect.right, y = clientRect.bottom };
WinApi.ClientToScreen(windowHandle, ref clientRectLeftTop);
WinApi.ClientToScreen(windowHandle, ref clientRectRightBottom);
clientRect = new WinApi.Rect
{
left = clientRectLeftTop.x,
top = clientRectLeftTop.y,
right = clientRectRightBottom.x,
bottom = clientRectRightBottom.y
};
int width = clientRect.right - clientRect.left;
int height = clientRect.bottom - clientRect.top;
var asBitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
System.Drawing.Graphics.FromImage(asBitmap).CopyFromScreen(
clientRect.left,
clientRect.top,
0,
0,
new System.Drawing.Size(width, height),
System.Drawing.CopyPixelOperation.SourceCopy);
return asBitmap;
}
static void SetProcessDPIAware()
{
// https://www.google.com/search?q=GetWindowRect+dpi
// https://github.com/dotnet/wpf/issues/859
// https://github.com/dotnet/winforms/issues/135
WinApi.SetProcessDPIAware();
}
static ulong ParseULong(string asString)
{
if (asString.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
return ulong.Parse(asString[2..], System.Globalization.NumberStyles.HexNumber);
return ulong.Parse(asString);
}
}
public class EveOnline64
{
static public IImmutableList<ulong> EnumeratePossibleAddressesForUIRootObjectsFromProcessId(int processId)
{
var memoryReader = new MemoryReaderFromLiveProcess(processId);
var (committedMemoryRegions, _) = ReadCommittedMemoryRegionsWithoutContentFromProcessId(processId);
return EnumeratePossibleAddressesForUIRootObjects(committedMemoryRegions, memoryReader);
}
static public (IImmutableList<SampleMemoryRegion> memoryRegions, IImmutableList<string> logEntries) ReadCommittedMemoryRegionsWithContentFromProcessId(int processId)
{
var genericResult = ReadCommittedMemoryRegionsFromProcessId(processId, readContent: true);
return genericResult;
}
static public (IImmutableList<(ulong baseAddress, int length)> memoryRegions, IImmutableList<string> logEntries) ReadCommittedMemoryRegionsWithoutContentFromProcessId(int processId)
{
var genericResult = ReadCommittedMemoryRegionsFromProcessId(processId, readContent: false);
var memoryRegions =
genericResult.memoryRegions
.Select(memoryRegion => (baseAddress: memoryRegion.baseAddress, length: (int)memoryRegion.length))
.ToImmutableList();
return (memoryRegions, genericResult.logEntries);
}
static public (IImmutableList<SampleMemoryRegion> memoryRegions, IImmutableList<string> logEntries) ReadCommittedMemoryRegionsFromProcessId(
int processId,
bool readContent)
{
var logEntries = new List<string>();
void logLine(string lineText)
{
logEntries.Add(lineText);
// Console.WriteLine(lineText);
}
logLine("Reading from process " + processId + ".");
var processHandle = WinApi.OpenProcess(
(int)(WinApi.ProcessAccessFlags.QueryInformation | WinApi.ProcessAccessFlags.VirtualMemoryRead), false, processId);
long address = 0;
var committedRegions = new List<SampleMemoryRegion>();
do
{
int result = WinApi.VirtualQueryEx(
processHandle,
(IntPtr)address,
out WinApi.MEMORY_BASIC_INFORMATION64 m,
(uint)Marshal.SizeOf(typeof(WinApi.MEMORY_BASIC_INFORMATION64)));
var regionProtection = (WinApi.MemoryInformationProtection)m.Protect;
logLine($"{m.BaseAddress}-{(uint)m.BaseAddress + (uint)m.RegionSize - 1} : {m.RegionSize} bytes result={result}, state={(WinApi.MemoryInformationState)m.State}, type={(WinApi.MemoryInformationType)m.Type}, protection={regionProtection}");
if (address == (long)m.BaseAddress + (long)m.RegionSize)
break;
address = (long)m.BaseAddress + (long)m.RegionSize;
if (m.State != (int)WinApi.MemoryInformationState.MEM_COMMIT)
continue;
var protectionFlagsToSkip = WinApi.MemoryInformationProtection.PAGE_GUARD | WinApi.MemoryInformationProtection.PAGE_NOACCESS;
var matchingFlagsToSkip = protectionFlagsToSkip & regionProtection;
if (matchingFlagsToSkip != 0)
{
logLine($"Skipping region beginning at {m.BaseAddress:X} as it has flags {matchingFlagsToSkip}.");
continue;
}
var regionBaseAddress = m.BaseAddress;
byte[] regionContent = null;
if (readContent)
{
UIntPtr bytesRead = UIntPtr.Zero;
var regionContentBuffer = new byte[(long)m.RegionSize];
WinApi.ReadProcessMemory(processHandle, regionBaseAddress, regionContentBuffer, (UIntPtr)regionContentBuffer.LongLength, ref bytesRead);
if (bytesRead.ToUInt64() != (ulong)regionContentBuffer.LongLength)
throw new Exception($"Failed to ReadProcessMemory at 0x{regionBaseAddress:X}: Only read " + bytesRead + " bytes.");
regionContent = regionContentBuffer;
}
committedRegions.Add(new SampleMemoryRegion(
baseAddress: regionBaseAddress,
length: m.RegionSize,
content: regionContent));
} while (true);
logLine($"Found {committedRegions.Count} committed regions with a total size of {committedRegions.Select(region => (long)region.length).Sum()}.");
return (committedRegions.ToImmutableList(), logEntries.ToImmutableList());
}
static public IImmutableList<ulong> EnumeratePossibleAddressesForUIRootObjects(
IEnumerable<(ulong baseAddress, int length)> memoryRegions,
IMemoryReader memoryReader)
{
var memoryRegionsOrderedByAddress =
memoryRegions
.OrderBy(memoryRegion => memoryRegion.baseAddress)
.ToImmutableArray();
string ReadNullTerminatedAsciiStringFromAddressUpTo255(ulong address)
{
var asMemory = memoryReader.ReadBytes(address, 0x100);
if (asMemory == null)
return null;
var asSpan = asMemory.Value.Span;
var length = 0;
for (var i = 0; i < asSpan.Length; ++i)
{
length = i;
if (asSpan[i] == 0)
break;
}
return System.Text.Encoding.ASCII.GetString(asSpan[..length]);
}
ReadOnlyMemory<ulong>? ReadMemoryRegionContentAsULongArray((ulong baseAddress, int length) memoryRegion)
{
var asByteArray = memoryReader.ReadBytes(memoryRegion.baseAddress, memoryRegion.length);
if (asByteArray == null)
return null;
return TransformMemoryContent.AsULongMemory(asByteArray.Value);
}
IEnumerable<ulong> EnumerateCandidatesForPythonTypeObjectType()
{
IEnumerable<ulong> EnumerateCandidatesForPythonTypeObjectTypeInMemoryRegion((ulong baseAddress, int length) memoryRegion)
{
var memoryRegionContentAsULongArray = ReadMemoryRegionContentAsULongArray(memoryRegion);
if (memoryRegionContentAsULongArray == null)
yield break;
for (var candidateAddressIndex = 0; candidateAddressIndex < memoryRegionContentAsULongArray.Value.Length - 4; ++candidateAddressIndex)
{
var candidateAddressInProcess = memoryRegion.baseAddress + (ulong)candidateAddressIndex * 8;
var candidate_ob_type = memoryRegionContentAsULongArray.Value.Span[candidateAddressIndex + 1];
if (candidate_ob_type != candidateAddressInProcess)
continue;
var candidate_tp_name =
ReadNullTerminatedAsciiStringFromAddressUpTo255(
memoryRegionContentAsULongArray.Value.Span[candidateAddressIndex + 3]);
if (candidate_tp_name != "type")
continue;
yield return candidateAddressInProcess;
}
}
return
memoryRegionsOrderedByAddress
.AsParallel()
.WithDegreeOfParallelism(2)
.SelectMany(EnumerateCandidatesForPythonTypeObjectTypeInMemoryRegion)
.ToImmutableArray();
}
IEnumerable<(ulong address, string tp_name)> EnumerateCandidatesForPythonTypeObjects(
IImmutableList<ulong> typeObjectCandidatesAddresses)
{
if (typeObjectCandidatesAddresses.Count < 1)
yield break;
var typeAddressMin = typeObjectCandidatesAddresses.Min();
var typeAddressMax = typeObjectCandidatesAddresses.Max();
foreach (var memoryRegion in memoryRegionsOrderedByAddress)
{
var memoryRegionContentAsULongArray = ReadMemoryRegionContentAsULongArray(memoryRegion);
if (memoryRegionContentAsULongArray == null)
continue;
for (var candidateAddressIndex = 0; candidateAddressIndex < memoryRegionContentAsULongArray.Value.Length - 4; ++candidateAddressIndex)
{
var candidateAddressInProcess = memoryRegion.baseAddress + (ulong)candidateAddressIndex * 8;
var candidate_ob_type = memoryRegionContentAsULongArray.Value.Span[candidateAddressIndex + 1];
{
// This check is redundant with the following one. It just implements a specialization to optimize runtime expenses.
if (candidate_ob_type < typeAddressMin || typeAddressMax < candidate_ob_type)
continue;
}
if (!typeObjectCandidatesAddresses.Contains(candidate_ob_type))
continue;
var candidate_tp_name =
ReadNullTerminatedAsciiStringFromAddressUpTo255(
memoryRegionContentAsULongArray.Value.Span[candidateAddressIndex + 3]);
if (candidate_tp_name == null)
continue;
yield return (candidateAddressInProcess, candidate_tp_name);
}
}
}
IEnumerable<ulong> EnumerateCandidatesForInstancesOfPythonType(
IImmutableList<ulong> typeObjectCandidatesAddresses)
{
if (typeObjectCandidatesAddresses.Count < 1)
yield break;
var typeAddressMin = typeObjectCandidatesAddresses.Min();
var typeAddressMax = typeObjectCandidatesAddresses.Max();
foreach (var memoryRegion in memoryRegionsOrderedByAddress)
{
var memoryRegionContentAsULongArray = ReadMemoryRegionContentAsULongArray(memoryRegion);
if (memoryRegionContentAsULongArray == null)
continue;
for (var candidateAddressIndex = 0; candidateAddressIndex < memoryRegionContentAsULongArray.Value.Length - 4; ++candidateAddressIndex)
{
var candidateAddressInProcess = memoryRegion.baseAddress + (ulong)candidateAddressIndex * 8;
var candidate_ob_type = memoryRegionContentAsULongArray.Value.Span[candidateAddressIndex + 1];
{
// This check is redundant with the following one. It just implements a specialization to reduce processing time.
if (candidate_ob_type < typeAddressMin || typeAddressMax < candidate_ob_type)
continue;
}
if (!typeObjectCandidatesAddresses.Contains(candidate_ob_type))
continue;
yield return candidateAddressInProcess;
}
}
}
var uiRootTypeObjectCandidatesAddresses =
EnumerateCandidatesForPythonTypeObjects(EnumerateCandidatesForPythonTypeObjectType().ToImmutableList())
.Where(typeObject => typeObject.tp_name == "UIRoot")
.Select(typeObject => typeObject.address)
.ToImmutableList();
return
EnumerateCandidatesForInstancesOfPythonType(uiRootTypeObjectCandidatesAddresses)
.ToImmutableList();
}
struct PyDictEntry
{
public ulong hash;
public ulong key;
public ulong value;
}
static readonly IImmutableSet<string> DictEntriesOfInterestKeys = ImmutableHashSet.Create(
"_top", "_left", "_width", "_height", "_displayX", "_displayY",
"_displayHeight", "_displayWidth",
"_name", "_text", "_setText",
"children",
"texturePath", "_bgTexturePath",
"_hint", "_display",
// HPGauges
"lastShield", "lastArmor", "lastStructure",
// Found in "ShipHudSpriteGauge"
"_lastValue",
// Found in "ModuleButton"
"ramp_active",
// Found in the Transforms contained in "ShipModuleButtonRamps"
"_rotation",
// Found under OverviewEntry in Sprite named "iconSprite"
"_color",
// Found in "SE_TextlineCore"
"_sr",
// Found in "_sr" Bunch
"htmlstr",
// 2023-01-03 Sample with PhotonUI: process-sample-ebdfff96e7.zip
"_texturePath", "_opacity", "_bgColor", "isExpanded"
);
struct LocalMemoryReadingTools
{
public IMemoryReader memoryReader;
public Func<ulong, IImmutableDictionary<string, ulong>> getDictionaryEntriesWithStringKeys;
public Func<ulong, string> GetPythonTypeNameFromPythonObjectAddress;
public Func<ulong, object> GetDictEntryValueRepresentation;
}
static readonly IImmutableDictionary<string, Func<ulong, LocalMemoryReadingTools, object>> specializedReadingFromPythonType =
ImmutableDictionary<string, Func<ulong, LocalMemoryReadingTools, object>>.Empty
.Add("str", new Func<ulong, LocalMemoryReadingTools, object>(ReadingFromPythonType_str))
.Add("unicode", new Func<ulong, LocalMemoryReadingTools, object>(ReadingFromPythonType_unicode))
.Add("int", new Func<ulong, LocalMemoryReadingTools, object>(ReadingFromPythonType_int))
.Add("bool", new Func<ulong, LocalMemoryReadingTools, object>(ReadingFromPythonType_bool))
.Add("float", new Func<ulong, LocalMemoryReadingTools, object>(ReadingFromPythonType_float))
.Add("PyColor", new Func<ulong, LocalMemoryReadingTools, object>(ReadingFromPythonType_PyColor))
.Add("Bunch", new Func<ulong, LocalMemoryReadingTools, object>(ReadingFromPythonType_Bunch))
/*
* 2024-05-26 observed dict entry with key "_setText" pointing to a python object of type "Link".
* The client used that instance of "Link" to display "Current Solar System" label in the location info panel.
* */
.Add("Link", new Func<ulong, LocalMemoryReadingTools, object>(ReadingFromPythonType_Link));
static object ReadingFromPythonType_str(ulong address, LocalMemoryReadingTools memoryReadingTools)
{
return ReadPythonStringValue(address, memoryReadingTools.memoryReader, 0x1000);
}
static object ReadingFromPythonType_unicode(ulong address, LocalMemoryReadingTools memoryReadingTools)
{
var pythonObjectMemory = memoryReadingTools.memoryReader.ReadBytes(address, 0x20);
if (!(pythonObjectMemory?.Length == 0x20))
return "Failed to read python object memory.";
var unicode_string_length = BitConverter.ToUInt64(pythonObjectMemory.Value.Span[0x10..]);
if (0x1000 < unicode_string_length)
return "String too long.";
var stringBytesCount = (int)unicode_string_length * 2;
var stringBytes = memoryReadingTools.memoryReader.ReadBytes(
BitConverter.ToUInt64(pythonObjectMemory.Value.Span[0x18..]), stringBytesCount);
if (!(stringBytes?.Length == stringBytesCount))
return "Failed to read string bytes.";
return System.Text.Encoding.Unicode.GetString(stringBytes.Value.Span);
}
static object ReadingFromPythonType_int(ulong address, LocalMemoryReadingTools memoryReadingTools)
{
var intObjectMemory = memoryReadingTools.memoryReader.ReadBytes(address, 0x18);
if (!(intObjectMemory?.Length == 0x18))
return "Failed to read int object memory.";
var value = BitConverter.ToInt64(intObjectMemory.Value.Span[0x10..]);
var asInt32 = (int)value;
if (asInt32 == value)
return asInt32;
return new
{
@int = value,
int_low32 = asInt32,
};
}
static object ReadingFromPythonType_bool(ulong address, LocalMemoryReadingTools memoryReadingTools)
{
var pythonObjectMemory = memoryReadingTools.memoryReader.ReadBytes(address, 0x18);
if (!(pythonObjectMemory?.Length == 0x18))
return "Failed to read python object memory.";
return BitConverter.ToInt64(pythonObjectMemory.Value.Span[0x10..]) != 0;
}
static object ReadingFromPythonType_float(ulong address, LocalMemoryReadingTools memoryReadingTools)
{
return ReadPythonFloatObjectValue(address, memoryReadingTools.memoryReader);
}
static object ReadingFromPythonType_PyColor(ulong address, LocalMemoryReadingTools memoryReadingTools)
{
var pyColorObjectMemory = memoryReadingTools.memoryReader.ReadBytes(address, 0x18);
if (!(pyColorObjectMemory?.Length == 0x18))
return "Failed to read pyColorObjectMemory.";
var dictionaryAddress = BitConverter.ToUInt64(pyColorObjectMemory.Value.Span[0x10..]);
var dictionaryEntries = memoryReadingTools.getDictionaryEntriesWithStringKeys(dictionaryAddress);
if (dictionaryEntries == null)
return "Failed to read dictionary entries.";
int? readValuePercentFromDictEntryKey(string dictEntryKey)
{
if (!dictionaryEntries.TryGetValue(dictEntryKey, out var valueAddress))
return null;
var valueAsFloat = ReadPythonFloatObjectValue(valueAddress, memoryReadingTools.memoryReader);
if (!valueAsFloat.HasValue)
return null;
return (int)(valueAsFloat.Value * 100);
}
return new
{
aPercent = readValuePercentFromDictEntryKey("_a"),
rPercent = readValuePercentFromDictEntryKey("_r"),
gPercent = readValuePercentFromDictEntryKey("_g"),
bPercent = readValuePercentFromDictEntryKey("_b"),
};
}
static object ReadingFromPythonType_Bunch(ulong address, LocalMemoryReadingTools memoryReadingTools)
{
var dictionaryEntries = memoryReadingTools.getDictionaryEntriesWithStringKeys(address);
if (dictionaryEntries == null)
return "Failed to read dictionary entries.";
var entriesOfInterest = new List<UITreeNode.DictEntry>();
foreach (var entry in dictionaryEntries)
{
if (!DictEntriesOfInterestKeys.Contains(entry.Key))
{
continue;
}
entriesOfInterest.Add(new UITreeNode.DictEntry
(
key: entry.Key,
value: memoryReadingTools.GetDictEntryValueRepresentation(entry.Value)
));
}
var entriesOfInterestJObject =
new System.Text.Json.Nodes.JsonObject(
entriesOfInterest.Select(dictEntry =>
new KeyValuePair<string, System.Text.Json.Nodes.JsonNode?>
(dictEntry.key,
System.Text.Json.Nodes.JsonNode.Parse(SerializeMemoryReadingNodeToJson(dictEntry.value)))));
return new UITreeNode.Bunch
(
entriesOfInterest: entriesOfInterestJObject
);
}
static object ReadingFromPythonType_Link(ulong address, LocalMemoryReadingTools memoryReadingTools)
{
var pythonObjectTypeName = memoryReadingTools.GetPythonTypeNameFromPythonObjectAddress(address);
var linkMemory = memoryReadingTools.memoryReader.ReadBytes(address, 0x40);
if (linkMemory is null)
return null;
var linkMemoryAsLongMemory = TransformMemoryContent.AsULongMemory(linkMemory.Value);
/*
* 2024-05-26 observed a reference to a dictionary object at offset 6 * 4 bytes.
* */
var firstDictReference =
linkMemoryAsLongMemory
.ToArray()
.Where(reference =>
{
var referencedObjectTypeName = memoryReadingTools.GetPythonTypeNameFromPythonObjectAddress(reference);
return referencedObjectTypeName is "dict";
})
.FirstOrDefault();
if (firstDictReference is 0)
return null;
var dictEntries =
memoryReadingTools.getDictionaryEntriesWithStringKeys(firstDictReference)
?.ToImmutableDictionary(
keySelector: dictEntry => dictEntry.Key,
elementSelector: dictEntry => memoryReadingTools.GetDictEntryValueRepresentation(dictEntry.Value));
return new UITreeNode(
pythonObjectAddress: address,
pythonObjectTypeName: pythonObjectTypeName,
dictEntriesOfInterest: dictEntries,
otherDictEntriesKeys: null,
children: null);
}
class MemoryReadingCache
{
IDictionary<ulong, string> PythonTypeNameFromPythonObjectAddress;
IDictionary<ulong, string> PythonStringValueMaxLength4000;
IDictionary<ulong, object> DictEntryValueRepresentation;
public MemoryReadingCache()
{
PythonTypeNameFromPythonObjectAddress = new Dictionary<ulong, string>();
PythonStringValueMaxLength4000 = new Dictionary<ulong, string>();
DictEntryValueRepresentation = new Dictionary<ulong, object>();
}
public string GetPythonTypeNameFromPythonObjectAddress(ulong address, Func<ulong, string> getFresh) =>
GetFromCacheOrUpdate(PythonTypeNameFromPythonObjectAddress, address, getFresh);
public string GetPythonStringValueMaxLength4000(ulong address, Func<ulong, string> getFresh) =>
GetFromCacheOrUpdate(PythonStringValueMaxLength4000, address, getFresh);
public object GetDictEntryValueRepresentation(ulong address, Func<ulong, object> getFresh) =>
GetFromCacheOrUpdate(DictEntryValueRepresentation, address, getFresh);
static TValue GetFromCacheOrUpdate<TKey, TValue>(IDictionary<TKey, TValue> cache, TKey key, Func<TKey, TValue> getFresh)
{
if (cache.TryGetValue(key, out var fromCache))
return fromCache;
var fresh = getFresh(key);
cache[key] = fresh;
return fresh;
}
}
static public UITreeNode ReadUITreeFromAddress(ulong nodeAddress, IMemoryReader memoryReader, int maxDepth) =>
ReadUITreeFromAddress(nodeAddress, memoryReader, maxDepth, null);
static UITreeNode ReadUITreeFromAddress(ulong nodeAddress, IMemoryReader memoryReader, int maxDepth, MemoryReadingCache cache)
{
cache ??= new MemoryReadingCache();
var uiNodeObjectMemory = memoryReader.ReadBytes(nodeAddress, 0x30);
if (!(0x30 == uiNodeObjectMemory?.Length))
return null;
string getPythonTypeNameFromPythonTypeObjectAddress(ulong typeObjectAddress)
{
var typeObjectMemory = memoryReader.ReadBytes(typeObjectAddress, 0x20);
if (!(typeObjectMemory?.Length == 0x20))
return null;
var tp_name = BitConverter.ToUInt64(typeObjectMemory.Value.Span[0x18..]);
var nameBytes = memoryReader.ReadBytes(tp_name, 100)?.ToArray();
if (!(nameBytes?.Contains((byte)0) ?? false))
return null;
return System.Text.Encoding.ASCII.GetString(nameBytes.TakeWhile(character => character != 0).ToArray());
}
string getPythonTypeNameFromPythonObjectAddress(ulong objectAddress)
{
return cache.GetPythonTypeNameFromPythonObjectAddress(objectAddress, objectAddress =>
{
var objectMemory = memoryReader.ReadBytes(objectAddress, 0x10);
if (!(objectMemory?.Length == 0x10))
return null;