-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1398 lines (1185 loc) · 51.7 KB
/
Program.cs
File metadata and controls
1398 lines (1185 loc) · 51.7 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 SharpVM;
using SharpVM.Demos;
using SharpVM.Injector;
using SharpVM.Viewer;
// Check command line args
if (args.Length > 0 && args[0] == "--advanced")
{
// Run advanced demos
DemoRunner.RunAll();
return;
}
if (args.Length > 0 && args[0] == "--bios")
{
// Run BIOS viewer (placeholder)
var viewer = new VMViewer();
viewer.Run();
return;
}
if (args.Length > 0 && args[0] == "--bios-run")
{
// Run actual x86 CPU emulator with BIOS
string? biosPath = args.Length > 1 ? args[1] : null;
bool debug = args.Length > 2 && args[2] == "--debug";
var runner = new BiosRunner();
if (biosPath != null && File.Exists(biosPath))
{
if (!runner.LoadBios(biosPath))
{
Console.WriteLine("Failed to load BIOS file");
return;
}
}
else
{
Console.WriteLine("Creating test BIOS (no BIOS file specified or file not found)...");
runner.CreateTestBios();
}
runner.Initialize();
runner.TraceInstructions = true;
if (debug)
{
runner.Debug();
}
else
{
runner.Run(10000);
}
return;
}
if (args.Length > 0 && args[0] == "--boot-cdrom")
{
// Boot from CD-ROM ISO using SeaBIOS
string biosPath = @"D:\SharpVM\bios\bios.bin";
string isoPath = @"D:\SharpVM\iso\TinyCore-current.iso";
bool debug = args.Any(a => a == "--debug");
bool trace = args.Any(a => a == "--trace");
int maxInstructions = 1000000;
// Parse positional and named arguments (skip pure numbers which are --max values)
var positionalArgs = args.Skip(1).Where(a => !a.StartsWith("--") && !int.TryParse(a, out _)).ToList();
if (positionalArgs.Count >= 1) biosPath = positionalArgs[0];
if (positionalArgs.Count >= 2) isoPath = positionalArgs[1];
// Parse --max option
for (int i = 0; i < args.Length - 1; i++)
{
if (args[i] == "--max" && int.TryParse(args[i + 1], out int max))
{
maxInstructions = max;
break;
}
}
Console.WriteLine("╔═══════════════════════════════════════════════════════════════╗");
Console.WriteLine("║ SharpVM x86 Emulator - CD-ROM Boot ║");
Console.WriteLine("╚═══════════════════════════════════════════════════════════════╝");
Console.WriteLine();
if (!File.Exists(biosPath))
{
Console.WriteLine($"BIOS file not found: {biosPath}");
Console.WriteLine("Usage: SharpVM --boot-cdrom [bios.bin] [iso-file] [--debug] [--trace] [--max N]");
return;
}
if (!File.Exists(isoPath))
{
Console.WriteLine($"ISO file not found: {isoPath}");
Console.WriteLine("Usage: SharpVM --boot-cdrom [bios.bin] [iso-file] [--debug] [--trace] [--max N]");
return;
}
Console.WriteLine($"BIOS: {biosPath}");
Console.WriteLine($"ISO: {isoPath}");
Console.WriteLine();
var runner = new BiosRunner(32 * 1024 * 1024); // 32MB RAM
// Load BIOS
if (!runner.LoadBios(biosPath))
{
Console.WriteLine("Failed to load BIOS");
return;
}
// Attach CD-ROM
try
{
runner.AttachCdRom(isoPath);
Console.WriteLine("CD-ROM attached successfully");
if (runner.CdRom != null && runner.CdRom.IsBootable)
{
Console.WriteLine($" Boot image at LBA {runner.CdRom.BootImageLba}, {runner.CdRom.BootImageSectors} sectors");
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to attach CD-ROM: {ex.Message}");
return;
}
Console.WriteLine();
// Initialize and run
runner.Initialize();
runner.TraceInstructions = trace;
if (debug)
{
runner.Debug();
}
else
{
runner.Run(maxInstructions);
}
// Show final VGA screen
Console.WriteLine("\n=== VGA Display ===");
runner.Viewer.Render();
return;
}
if (args.Length > 0 && args[0] == "--direct-boot")
{
// Direct boot from CD-ROM ISO (bypasses SeaBIOS, loads boot image directly)
string isoPath = @"D:\SharpVM\iso\TinyCore-current.iso";
bool debug = args.Any(a => a == "--debug");
bool trace = args.Any(a => a == "--trace");
int maxInstructions = 1000000;
var positionalArgs = args.Skip(1).Where(a => !a.StartsWith("--") && !int.TryParse(a, out _)).ToList();
if (positionalArgs.Count >= 1) isoPath = positionalArgs[0];
for (int i = 0; i < args.Length - 1; i++)
{
if (args[i] == "--max" && int.TryParse(args[i + 1], out int max))
{
maxInstructions = max;
break;
}
}
Console.WriteLine("╔═══════════════════════════════════════════════════════════════╗");
Console.WriteLine("║ SharpVM x86 Emulator - Direct CD-ROM Boot ║");
Console.WriteLine("╚═══════════════════════════════════════════════════════════════╝");
Console.WriteLine();
if (!File.Exists(isoPath))
{
Console.WriteLine($"ISO file not found: {isoPath}");
return;
}
Console.WriteLine($"ISO: {isoPath}");
// Load ISO
var cdrom = new SharpVM.Devices.CdRomDevice(isoPath);
if (!cdrom.IsBootable)
{
Console.WriteLine("ISO is not bootable (no El Torito boot record)");
return;
}
Console.WriteLine($"Boot image: LBA {cdrom.BootImageLba}, {cdrom.BootImageSectors} sectors");
// Dump boot info table from boot image
byte[] bootImageInfo = cdrom.GetBootImage();
if (bootImageInfo.Length >= 24)
{
uint pvdLba = BitConverter.ToUInt32(bootImageInfo, 8);
uint bootFileLba = BitConverter.ToUInt32(bootImageInfo, 12);
uint bootFileLen = BitConverter.ToUInt32(bootImageInfo, 16);
uint checksum = BitConverter.ToUInt32(bootImageInfo, 20);
Console.WriteLine($"Boot Info Table:");
Console.WriteLine($" PVD LBA: {pvdLba}");
Console.WriteLine($" Boot file LBA: {bootFileLba}");
Console.WriteLine($" Boot file length: {bootFileLen}");
Console.WriteLine($" Checksum: 0x{checksum:X8}");
Console.WriteLine($" First 16 bytes: {BitConverter.ToString(bootImageInfo, 0, 16)}");
// Also show sector 16 (PVD) content
byte[] pvdSector = cdrom.ReadSector(16);
Console.Write($" Sector 16 (PVD) first 16 bytes: ");
for (int i = 0; i < 16 && i < pvdSector.Length; i++) Console.Write($"{pvdSector[i]:X2} ");
Console.Write(" |");
for (int i = 0; i < 16 && i < pvdSector.Length; i++)
{
char c = (char)pvdSector[i];
Console.Write(c >= 32 && c < 127 ? c : '.');
}
Console.WriteLine("|");
// And sector 1
byte[] sec1 = cdrom.ReadSector(1);
Console.Write($" Sector 1 first 16 bytes: ");
for (int i = 0; i < 16 && i < sec1.Length; i++) Console.Write($"{sec1[i]:X2} ");
Console.Write(" |");
for (int i = 0; i < 16 && i < sec1.Length; i++)
{
char c = (char)sec1[i];
Console.Write(c >= 32 && c < 127 ? c : '.');
}
Console.WriteLine("|");
}
Console.WriteLine();
// Create CPU with 32MB memory
var cpu = new SharpVM.CPU.X86Cpu(32 * 1024 * 1024);
cpu.Reset();
cpu.A20Enabled = true;
// Load boot image at 0x7C00 (standard boot sector address)
byte[] bootImage = cdrom.GetBootImage();
Console.WriteLine($"Loading {bootImage.Length} bytes at 0x7C00");
for (int i = 0; i < bootImage.Length; i++)
{
cpu.WriteByte(0x7C00 + (ulong)i, bootImage[i]);
}
// Set up minimal BIOS Data Area
cpu.WriteByte(0x410, 0x21); // Equipment: VGA, no floppy
cpu.WriteByte(0x411, 0x00);
cpu.WriteWord(0x413, 640); // 640KB base memory
cpu.WriteByte(0x449, 0x03); // Video mode 3 (80x25 text)
cpu.WriteByte(0x44A, 80); // 80 columns
cpu.WriteByte(0x484, 24); // 25 rows - 1
// Set up segment registers for boot
cpu.Regs.CS = 0x0000;
cpu.Regs.DS = 0x0000;
cpu.Regs.ES = 0x0000;
cpu.Regs.SS = 0x0000;
cpu.Regs.IP = 0x7C00;
cpu.Regs.SP = 0x7C00; // Stack just below boot sector
// DL = boot drive (0x80 for first hard disk, 0xE0 for CD-ROM)
cpu.Regs.SetReg8(SharpVM.CPU.X86Registers.RDX, 0xE0, false); // DL = CD-ROM drive
// Hook up CD-ROM for INT 13h
SharpVM.CPU.BiosInterrupts.SetCdRom(cdrom);
Console.WriteLine($"Starting execution at {cpu.Regs.CS:X4}:{cpu.Regs.IP:X4}");
Console.WriteLine($"DL = {cpu.Regs.DL:X2} (boot drive)");
// Verify boot info table in memory
uint pvdLbaInMem = cpu.ReadDword(0x7C08);
uint bootLbaInMem = cpu.ReadDword(0x7C0C);
Console.WriteLine($"Boot info at 0x7C08: PVD LBA={pvdLbaInMem}, Boot file LBA={bootLbaInMem}");
Console.WriteLine();
var viewer = new VMViewer();
int instructionCount = 0;
cpu.IsRunning = true;
while (cpu.IsRunning && instructionCount < maxInstructions && !cpu.Halted)
{
if (trace)
{
ulong addr = cpu.LinearAddress(cpu.Regs.CS, cpu.Regs.IP);
byte opcode = cpu.ReadByte(addr);
Console.WriteLine($"[{instructionCount:D8}] {cpu.Regs.CS:X4}:{cpu.Regs.IP:X4} {opcode:X2} " +
$"AX={cpu.Regs.AX:X4} BX={cpu.Regs.BX:X4} CX={cpu.Regs.CX:X4} DX={cpu.Regs.DX:X4}");
}
try
{
cpu.Step();
}
catch (Exception ex)
{
Console.WriteLine($"\nException at {cpu.Regs.CS:X4}:{cpu.Regs.IP:X4}: {ex.Message}");
break;
}
instructionCount++;
// Sync VGA periodically
if (instructionCount % 10000 == 0)
{
for (int i = 0; i < 80 * 25 * 2; i++)
{
viewer.WriteVideoMemory(i, cpu.ReadByte(0xB8000 + (ulong)i));
}
}
}
Console.WriteLine($"\nExecuted {instructionCount} instructions");
Console.WriteLine($"CS:IP = {cpu.Regs.CS:X4}:{cpu.Regs.IP:X4}");
Console.WriteLine($"Halted: {cpu.Halted}");
// Final VGA sync and display
for (int i = 0; i < 80 * 25 * 2; i++)
{
viewer.WriteVideoMemory(i, cpu.ReadByte(0xB8000 + (ulong)i));
}
Console.WriteLine("\n=== VGA Display ===");
viewer.Render();
if (debug)
{
// Simple debug loop
Console.WriteLine("\nDebug mode (s=step, r=run 100, q=quit):");
while (true)
{
Console.Write("> ");
string? cmd = Console.ReadLine()?.Trim().ToLower();
if (cmd == "q" || cmd == "quit") break;
if (cmd == "s" || cmd == "step")
{
ulong addr = cpu.LinearAddress(cpu.Regs.CS, cpu.Regs.IP);
byte opcode = cpu.ReadByte(addr);
Console.WriteLine($"{cpu.Regs.CS:X4}:{cpu.Regs.IP:X4} {opcode:X2}");
try { cpu.Step(); } catch (Exception ex) { Console.WriteLine(ex.Message); }
}
if (cmd == "r" || cmd == "run")
{
for (int i = 0; i < 100 && !cpu.Halted; i++)
try { cpu.Step(); } catch { break; }
Console.WriteLine($"Now at {cpu.Regs.CS:X4}:{cpu.Regs.IP:X4}");
}
}
}
return;
}
if (args.Length > 0 && args[0] == "--inject")
{
if (args.Length < 2)
{
Console.WriteLine("Usage: SharpVM --inject <path-to-exe>");
Console.WriteLine(" SharpVM --inject <path-to-exe> --analyze");
Console.WriteLine(" SharpVM --inject <path-to-exe> --trace");
return;
}
string exePath = args[1];
bool analyzeOnly = args.Length > 2 && args[2] == "--analyze";
bool enableTrace = args.Length > 2 && args[2] == "--trace";
var injector = new BinaryInjector
{
EnableTracing = enableTrace,
VerboseOutput = true,
MaxInstructions = 10000
};
try
{
injector.Load(exePath);
if (analyzeOnly)
{
injector.Analyze();
}
else
{
injector.Execute();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
if (ex.InnerException != null)
Console.WriteLine($" Inner: {ex.InnerException.Message}");
}
return;
}
// Universal Binary Analyzer
if (args.Length > 0 && args[0] == "--analyze")
{
string filePath = args.Length > 1 ? args[1] : "";
bool detailed = args.Any(a => a == "-v" || a == "--verbose");
string? outputPath = null;
// Parse --output option
for (int i = 0; i < args.Length - 1; i++)
{
if (args[i] == "-o" || args[i] == "--output")
{
outputPath = args[i + 1];
break;
}
}
Console.WriteLine("╔═══════════════════════════════════════════════════════════════╗");
Console.WriteLine("║ SharpVM - Universal Binary Analyzer ║");
Console.WriteLine("╚═══════════════════════════════════════════════════════════════╝");
Console.WriteLine();
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
{
Console.WriteLine("Usage: SharpVM --analyze <file> [options]");
Console.WriteLine("Options:");
Console.WriteLine(" -v, --verbose Show detailed analysis output");
Console.WriteLine(" -o, --output <path> Write report to file");
Console.WriteLine();
Console.WriteLine("Analyzes any binary file for:");
Console.WriteLine(" - File format detection (PE, ELF, Mach-O, etc.)");
Console.WriteLine(" - Cryptographic patterns (AES, XTEA, RC4, MD5, SHA, etc.)");
Console.WriteLine(" - Obfuscation/protection (VMProtect, Themida, Arxan, etc.)");
Console.WriteLine(" - Entropy analysis (packed/encrypted regions)");
Console.WriteLine(" - String analysis (suspicious strings, encrypted strings)");
Console.WriteLine(" - Code pattern analysis (anti-debug, VM handlers)");
Console.WriteLine(" - Import/export analysis (suspicious APIs)");
return;
}
var analyzer = new SharpVM.Analyzer.Core.UniversalAnalyzer();
var report = analyzer.Analyze(filePath);
analyzer.PrintReport(report, detailed);
if (!string.IsNullOrEmpty(outputPath))
{
using var writer = new StreamWriter(outputPath);
writer.WriteLine($"SharpVM Universal Binary Analysis Report");
writer.WriteLine($"File: {report.FilePath}");
writer.WriteLine($"Size: {report.FileSize:N0} bytes");
writer.WriteLine($"Analyzed: {report.AnalysisTime}");
writer.WriteLine();
writer.WriteLine($"Format: {report.DetectedFormat}");
writer.WriteLine();
writer.WriteLine("=== Findings ===");
foreach (var finding in report.Findings.OrderByDescending(f => f.Severity))
{
writer.WriteLine($"[{finding.Severity}] {finding.Title}");
writer.WriteLine($" {finding.Description}");
if (finding.Address.HasValue)
writer.WriteLine($" Address: 0x{finding.Address:X}");
}
writer.WriteLine();
writer.WriteLine("=== Detected Protections ===");
foreach (var tech in report.ObfuscationTechniques)
{
writer.WriteLine($"- {tech.Name} ({tech.Type}, confidence: {tech.Confidence:P0})");
writer.WriteLine($" {tech.Description}");
}
writer.WriteLine();
writer.WriteLine("=== Crypto Patterns ===");
foreach (var crypto in report.CryptoPatterns)
{
writer.WriteLine($"- {crypto.AlgorithmName} at 0x{crypto.Address:X}");
writer.WriteLine($" Type: {crypto.Type}, Confidence: {crypto.Confidence:P0}");
}
Console.WriteLine($"\nReport written to: {outputPath}");
}
return;
}
// PSP Firmware Analyzer
if (args.Length > 0 && args[0] == "--psp-analyze")
{
string filePath = args.Length > 1 ? args[1] : @"D:\SharpVM\bin\PS.BIN";
Console.WriteLine("╔═══════════════════════════════════════════════════════════════╗");
Console.WriteLine("║ SharpVM - PSP Firmware Analyzer (SCEUF Parser) ║");
Console.WriteLine("╚═══════════════════════════════════════════════════════════════╝");
Console.WriteLine();
var parser = new SharpVM.PSP.Firmware.SceufParser();
if (parser.Load(filePath))
{
Console.WriteLine($"\nTotal entries: {parser.Entries.Count}");
// Analyze first few entries
Console.WriteLine("\n=== Entry Analysis ===");
for (int i = 0; i < Math.Min(5, parser.Entries.Count); i++)
{
parser.AnalyzeEntry(i);
}
// Extract option
if (args.Any(a => a == "--extract"))
{
int entryIdx = 0;
for (int i = 0; i < args.Length - 1; i++)
{
if (args[i] == "--entry" && int.TryParse(args[i + 1], out int idx))
{
entryIdx = idx;
break;
}
}
string outPath = $"entry_{entryIdx}.bin";
parser.ExtractEntry(entryIdx, outPath);
}
}
return;
}
// Blackbone-style PE Loader
if (args.Length > 0 && args[0] == "--blackbone")
{
string filePath = args.Length > 1 ? args[1] : "";
bool interactive = args.Any(a => a == "-i" || a == "--interactive");
bool execute = args.Any(a => a == "-x" || a == "--execute");
bool trace = args.Any(a => a == "-t" || a == "--trace");
bool debug = args.Any(a => a == "-d" || a == "--debug");
bool passthrough = args.Any(a => a == "-p" || a == "--passthrough");
bool fullRun = args.Any(a => a == "--full" || a == "-f");
// Parse max instructions, dump path, vm analysis path, and memory dump path
int maxInstructions = fullRun ? int.MaxValue : 1000000;
string? dumpPath = null;
string? vmAnalysisPath = null;
string? memDumpPath = null;
string? traceDumpPath = null;
for (int i = 0; i < args.Length - 1; i++)
{
if (args[i] == "--max" && int.TryParse(args[i + 1], out int max))
{
maxInstructions = max;
}
if (args[i] == "--dump")
{
dumpPath = args[i + 1];
}
if (args[i] == "--vmanalysis")
{
vmAnalysisPath = args[i + 1];
}
if (args[i] == "--memdump")
{
memDumpPath = args[i + 1];
}
if (args[i] == "--tracedump")
{
traceDumpPath = args[i + 1];
}
}
// Default trace dump path for full run mode
if (fullRun && traceDumpPath == null)
{
traceDumpPath = Path.Combine(Path.GetDirectoryName(filePath) ?? ".",
Path.GetFileNameWithoutExtension(filePath) + "_trace.log");
}
if (fullRun && memDumpPath == null)
{
memDumpPath = Path.Combine(Path.GetDirectoryName(filePath) ?? ".",
Path.GetFileNameWithoutExtension(filePath) + "_memdump.bin");
}
Console.WriteLine("╔═══════════════════════════════════════════════════════════════╗");
Console.WriteLine("║ SharpVM - Blackbone Manual PE Mapper & Executor ║");
Console.WriteLine("╚═══════════════════════════════════════════════════════════════╝");
Console.WriteLine();
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
{
Console.WriteLine("Usage: SharpVM --blackbone <pe-file> [options]");
Console.WriteLine("Options:");
Console.WriteLine(" -i, --interactive Interactive exploration mode");
Console.WriteLine(" -x, --execute Execute through VM with API emulation");
Console.WriteLine(" -t, --trace Enable instruction tracing during execution");
Console.WriteLine(" -d, --debug Enable debugging (break on start)");
Console.WriteLine(" -p, --passthrough Forward ALL API calls to real Windows (no emulation)");
Console.WriteLine(" -f, --full Full run mode - execute until app exits, auto-dump on exit");
Console.WriteLine(" --dump <path> Dump execution trace to file (VM bytecode + memory)");
Console.WriteLine(" --max N Maximum instructions to execute (default 1000000)");
Console.WriteLine(" --vmanalysis <path> Enable protection VM analysis and write to file");
Console.WriteLine(" --memdump <path> Dump memory regions when protection completes");
Console.WriteLine(" --tracedump <path> Dump instruction trace to file");
Console.WriteLine();
Console.WriteLine("Examples:");
Console.WriteLine(" SharpVM --blackbone calc.exe # Load and analyze");
Console.WriteLine(" SharpVM --blackbone test.exe --execute # Execute through VM");
Console.WriteLine(" SharpVM --blackbone test.exe -x -t # Execute with tracing");
Console.WriteLine(" SharpVM --blackbone test.exe -x -d # Execute with debugger");
Console.WriteLine(" SharpVM --blackbone test.exe -x -p --dump trace.log # Passthrough with dump");
Console.WriteLine(" SharpVM --blackbone test.exe -x -t --full # Full run with auto-dump");
return;
}
var loader = new SharpVM.Blackbone.BlackboneLoader();
if (loader.LoadPE(filePath))
{
Console.WriteLine("\nPE file loaded successfully!");
Console.WriteLine();
loader.Disassemble(loader.GetEntryPoint(), 20);
if (execute)
{
// Execute through VM
Console.WriteLine("\n=== Executing through VM ===\n");
var executor = new SharpVM.Blackbone.Execution.VmExecutor(loader);
executor.MaxInstructions = maxInstructions;
executor.EnableTracing = trace;
executor.BreakOnApiCall = false;
executor.PassthroughMode = passthrough;
// Enable VM analysis if specified
if (!string.IsNullOrEmpty(vmAnalysisPath))
{
executor.EnableVmAnalysis = true;
executor.VmAnalysisPath = vmAnalysisPath;
Console.WriteLine($"[VM ANALYSIS] Will write protection VM analysis to: {vmAnalysisPath}");
}
// Enable memory dump if specified
if (!string.IsNullOrEmpty(memDumpPath))
{
executor.EnableMemoryDump = true;
executor.MemoryDumpPath = memDumpPath;
Console.WriteLine($"[MEM DUMP] Will dump memory to: {memDumpPath}");
Console.WriteLine($"[MEM DUMP] Auto-dump will trigger when protection completes (new API detected)");
}
// Set up dump file if specified
StreamWriter? dumpWriter = null;
if (!string.IsNullOrEmpty(dumpPath))
{
dumpWriter = new StreamWriter(dumpPath, false);
dumpWriter.WriteLine($"=== SharpVM Execution Dump ===");
dumpWriter.WriteLine($"Target: {filePath}");
dumpWriter.WriteLine($"Passthrough Mode: {passthrough}");
dumpWriter.WriteLine($"Started: {DateTime.Now}");
dumpWriter.WriteLine();
executor.EnableApiTracing = true;
executor.EnableTracing = true;
}
if (passthrough)
{
Console.WriteLine("[PASSTHROUGH MODE] All API calls forwarded to real Windows");
}
if (fullRun)
{
Console.WriteLine("[FULL RUN MODE] Executing until app exits or Ctrl+C pressed");
Console.WriteLine($" Trace dump: {traceDumpPath}");
Console.WriteLine($" Memory dump: {memDumpPath}");
Console.WriteLine(" Press Ctrl+C to stop and dump state");
}
// Set up trace dump writer for full run mode
StreamWriter? traceDumpWriter = null;
if (!string.IsNullOrEmpty(traceDumpPath))
{
traceDumpWriter = new StreamWriter(traceDumpPath, false);
traceDumpWriter.WriteLine($"=== SharpVM Full Trace Dump ===");
traceDumpWriter.WriteLine($"Target: {filePath}");
traceDumpWriter.WriteLine($"Started: {DateTime.Now}");
traceDumpWriter.WriteLine();
}
// Set up Ctrl+C handler for graceful shutdown
bool ctrlCPressed = false;
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true; // Prevent immediate termination
ctrlCPressed = true;
executor.RequestStop();
Console.WriteLine("\n[CTRL+C] Stopping execution and dumping state...");
};
// Hook output
executor.OnOutput += (s) => { /* Already written to console */ };
executor.OnApiCall += (addr, name) =>
{
if (trace)
{
// Already logged in tracer
}
dumpWriter?.WriteLine($"[API] {name} @ 0x{addr:X16}");
};
executor.Initialize();
// Initialize unified syscall emulation (Sogen integration)
// This enables real NT syscall handling for SYSCALL instructions
executor.InitializeSyscallEmulation(tracingEnabled: trace);
// Hook into ExecutionTracer for detailed dump if we have a dump file
if (dumpWriter != null && executor.Tracer != null)
{
executor.Tracer.SetDumpWriter(dumpWriter);
}
if (debug)
{
// Start with a breakpoint at entry
executor.AddBreakpoint(loader.GetEntryPoint());
}
var result = executor.Execute();
Console.WriteLine($"\n=== Execution Result ===");
Console.WriteLine($"Exit Reason: {result.ExitReason}");
Console.WriteLine($"Exit Code: {result.ExitCode}");
Console.WriteLine($"Instructions: {result.InstructionCount}");
if (result.Exception != null)
{
Console.WriteLine($"Exception: {result.Exception.Message}");
}
// Write final dump summary and close
if (dumpWriter != null)
{
dumpWriter.WriteLine();
dumpWriter.WriteLine($"=== Execution Complete ===");
dumpWriter.WriteLine($"Exit Reason: {result.ExitReason}");
dumpWriter.WriteLine($"Exit Code: {result.ExitCode}");
dumpWriter.WriteLine($"Instructions: {result.InstructionCount}");
dumpWriter.WriteLine($"Ended: {DateTime.Now}");
// Dump API call statistics
dumpWriter.WriteLine();
dumpWriter.WriteLine("=== API Call Statistics ===");
executor.ApiTracer.DumpToWriter(dumpWriter);
dumpWriter.Close();
Console.WriteLine($"\nDump written to: {dumpPath}");
}
// Write VM analysis summary if enabled
if (!string.IsNullOrEmpty(vmAnalysisPath))
{
executor.WriteVmAnalysisSummary();
Console.WriteLine($"\nVM analysis written to: {vmAnalysisPath}");
}
// Write trace dump if enabled (full run mode)
if (traceDumpWriter != null)
{
traceDumpWriter.WriteLine();
traceDumpWriter.WriteLine($"=== Execution Complete ===");
traceDumpWriter.WriteLine($"Exit Reason: {result.ExitReason}");
traceDumpWriter.WriteLine($"Exit Code: {result.ExitCode}");
traceDumpWriter.WriteLine($"Instructions: {result.InstructionCount}");
traceDumpWriter.WriteLine($"Stopped by Ctrl+C: {ctrlCPressed}");
traceDumpWriter.WriteLine($"Ended: {DateTime.Now}");
// Dump API call statistics
traceDumpWriter.WriteLine();
traceDumpWriter.WriteLine("=== API Call Statistics ===");
executor.ApiTracer.DumpToWriter(traceDumpWriter);
// Dump register state
traceDumpWriter.WriteLine();
traceDumpWriter.WriteLine("=== Final Register State ===");
executor.DumpRegistersToWriter(traceDumpWriter);
traceDumpWriter.Close();
Console.WriteLine($"\nTrace dump written to: {traceDumpPath}");
}
// Write memory dump if enabled (full run mode)
if (!string.IsNullOrEmpty(memDumpPath) && fullRun)
{
try
{
executor.DumpMemoryToFile(memDumpPath);
Console.WriteLine($"Memory dump written to: {memDumpPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to write memory dump: {ex.Message}");
}
}
}
else if (interactive)
{
loader.Interactive();
}
}
else
{
Console.WriteLine("Failed to load PE file");
}
return;
}
// Sogen Integration Test
if (args.Length > 0 && args[0] == "--sogen")
{
string filePath = args.Length > 1 ? args[1] : @"D:\Rockstar Games\Grand Theft Auto V\Menyoo.asi";
bool trace = args.Any(a => a == "-t" || a == "--trace");
Console.WriteLine("╔═══════════════════════════════════════════════════════════════╗");
Console.WriteLine("║ SharpVM - Sogen Windows Emulator Integration ║");
Console.WriteLine("╚═══════════════════════════════════════════════════════════════╝");
Console.WriteLine();
if (!File.Exists(filePath))
{
Console.WriteLine($"File not found: {filePath}");
Console.WriteLine();
Console.WriteLine("Usage: SharpVM --sogen <pe-file> [options]");
Console.WriteLine("Options:");
Console.WriteLine(" -t, --trace Enable syscall tracing");
Console.WriteLine();
Console.WriteLine("Examples:");
Console.WriteLine(" SharpVM --sogen Menyoo.asi");
Console.WriteLine(" SharpVM --sogen test.dll --trace");
return;
}
Console.WriteLine($"Target: {filePath}");
Console.WriteLine($"Trace: {trace}");
Console.WriteLine();
try
{
using var sogen = new SharpVM.Sogen.Core.SogenExecutor();
// Check if registry directory exists
string registryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "registry");
if (Directory.Exists(registryPath))
{
Console.WriteLine($"Using registry from: {registryPath}");
sogen.SetRegistryPath(registryPath);
}
else
{
Console.WriteLine("No registry directory found - running without registry");
}
// Enable syscall bridge with tracing
sogen.EnableSyscallBridge(enableTrace: trace);
Console.WriteLine("Loading PE file...");
if (sogen.LoadPE(filePath))
{
Console.WriteLine($"✓ Loaded at: 0x{sogen.ImageBase:X16}");
Console.WriteLine($"✓ Entry point: 0x{sogen.EntryPoint:X16}");
Console.WriteLine();
// Get loaded modules
var modules = sogen.GetModules();
Console.WriteLine($"Loaded modules: {modules.Count}");
foreach (var (name, baseAddr, size) in modules)
{
Console.WriteLine($" {name,-30} @ 0x{baseAddr:X16} (0x{size:X} bytes)");
}
Console.WriteLine();
Console.WriteLine("Executing DllMain...");
Console.WriteLine("Press Ctrl+C to stop");
Console.WriteLine();
// Execute
bool success = sogen.Execute();
Console.WriteLine();
Console.WriteLine("═══ Execution Results ═══");
Console.WriteLine($"Success: {success}");
Console.WriteLine($"Instructions: {sogen.InstructionCount:N0}");
Console.WriteLine($"Syscalls: {sogen.SyscallCount:N0}");
var dispatcher = sogen.GetDispatcher();
if (dispatcher != null)
{
Console.WriteLine($"Dispatcher syscalls: {dispatcher.SyscallCount:N0}");
}
if (!success)
{
string error = sogen.GetLastError();
Console.WriteLine($"Error: {error}");
}
}
else
{
string error = sogen.GetLastError();
Console.WriteLine($"✗ Failed to load PE: {error}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
Console.WriteLine(ex.StackTrace);
}
return;
}
// Hybrid Execution Mode (Hypervisor + Emulation)
if (args.Length > 0 && args[0] == "--hybrid")
{
string filePath = args.Length > 1 ? args[1] : "";
bool trace = args.Any(a => a == "-t" || a == "--trace");
string modeArg = args.FirstOrDefault(a => a.StartsWith("--mode=")) ?? "--mode=hybrid";
string mode = modeArg.Split('=').Last().ToLower();
Console.WriteLine("╔═══════════════════════════════════════════════════════════════╗");
Console.WriteLine("║ SharpVM - Hybrid Execution (Hypervisor + Emulation) ║");
Console.WriteLine("╚═══════════════════════════════════════════════════════════════╝");
Console.WriteLine();
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
{
Console.WriteLine("Usage: SharpVM --hybrid <pe-file> [options]");
Console.WriteLine("Options:");
Console.WriteLine(" -t, --trace Enable execution tracing");
Console.WriteLine(" --mode=<mode> Execution mode:");
Console.WriteLine(" hybrid - Use hypervisor + emulation (default)");
Console.WriteLine(" hypervisor - Pure hypervisor (real execution)");
Console.WriteLine(" emulation - Pure emulation (full control)");
Console.WriteLine();
Console.WriteLine("The hypervisor mode requires the momo5502 hypervisor driver to be installed.");
Console.WriteLine("Driver source: https://github.com/momo5502/hypervisor");
Console.WriteLine();
Console.WriteLine("Examples:");
Console.WriteLine(" SharpVM --hybrid game.exe # Hybrid mode");
Console.WriteLine(" SharpVM --hybrid game.exe --mode=hypervisor # Pure hypervisor");
Console.WriteLine(" SharpVM --hybrid game.exe --mode=emulation # Pure emulation");
Console.WriteLine(" SharpVM --hybrid game.exe -t # With tracing");
return;
}
Console.WriteLine($"Target: {filePath}");
Console.WriteLine($"Mode: {mode}");
Console.WriteLine($"Trace: {trace}");
Console.WriteLine();
// Check hypervisor availability
bool hypervisorAvailable = SharpVM.Hypervisor.HypervisorBridge.IsDriverAvailable();
Console.WriteLine($"Hypervisor Driver: {(hypervisorAvailable ? "Available" : "Not Found")}");
Console.WriteLine();
try
{
var loader = new SharpVM.Blackbone.BlackboneLoader();
if (loader.LoadPE(filePath))
{
Console.WriteLine("PE file loaded successfully!");
Console.WriteLine();
using var hybrid = new SharpVM.Hypervisor.HybridExecutor(loader);
// Set execution mode
hybrid.Mode = mode switch
{
"hypervisor" => SharpVM.Hypervisor.HybridExecutor.ExecutionMode.Hypervisor,
"emulation" => SharpVM.Hypervisor.HybridExecutor.ExecutionMode.Emulation,
_ => SharpVM.Hypervisor.HybridExecutor.ExecutionMode.Hybrid
};
hybrid.EnableTracing = trace;
// Hook events
hybrid.OnApiCall += (name) =>
{
if (trace) Console.WriteLine($"[API] {name}");
};
hybrid.OnCodeExecution += (addr) =>
{
if (trace) Console.WriteLine($"[EXEC] 0x{addr:X16}");
};
// Initialize and execute
hybrid.Initialize();