-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBattleOpsImported.cs
More file actions
978 lines (873 loc) · 41.1 KB
/
Copy pathBattleOpsImported.cs
File metadata and controls
978 lines (873 loc) · 41.1 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
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace XISOSharp.BattleTests;
/// <summary>
/// Battle ops for features XISOSharp imported from xdvdfs 0.8.3 (checksum, md5,
/// unpack, pack, cso) and XboxKit 0.7 (petrify, video, random, seed, trim, wipe,
/// zar, rebuild). Part of <see cref="BattleRunner"/>.
/// </summary>
internal static partial class BattleRunner
{
private static readonly Regex Hex64Regex =
new("^[0-9a-f]{64}$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled,
TimeSpan.FromMilliseconds(100));
private static readonly Regex Md5LineRegex =
new(@"^(?<hash>[0-9a-f]{32})\s+(?<path>/\S.*)$", RegexOptions.IgnoreCase | RegexOptions.Compiled,
TimeSpan.FromMilliseconds(100));
// ---- xdvdfs oracle -------------------------------------------------------
/// <summary>Battle: deterministic SHA3-256 image checksums must match exactly.</summary>
private static SubResult RunChecksum(string iso, ToolProcess cli, ToolProcess xdvdfs)
{
Stopwatch sw = Stopwatch.StartNew();
try
{
(int cCode, string cOut, string cErr, double cSec) = cli.Run("checksum", "--silent", iso);
(int oCode, string oOut, string oErr, double oSec) = xdvdfs.Run("checksum", iso);
if (cCode != 0 && oCode != 0)
{
return Done(sw, "checksum", BattleStatus.Skipped,
$"both tools failed: cli: {First(cErr, cOut)}, xdvdfs: {First(oErr, oOut)}", cSec, oSec);
}
if (cCode != 0)
{
return Done(sw, "checksum", BattleStatus.Failed,
$"CLI exit {cCode}: {First(cErr, cOut)} (xdvdfs exit 0)", cSec, oSec);
}
if (oCode != 0)
{
return Done(sw, "checksum", BattleStatus.Failed,
$"xdvdfs exit {oCode}: {First(oErr, oOut)} (CLI exit 0)", cSec, oSec);
}
string? cHex = FirstHex(cOut);
string? oHex = FirstHex(oOut);
if (cHex is null || oHex is null)
{
return Done(sw, "checksum", BattleStatus.Skipped,
$"could not parse hex checksums: cli={cHex ?? "null"}, xdvdfs={oHex ?? "null"}", cSec, oSec);
}
return string.Equals(cHex, oHex, StringComparison.OrdinalIgnoreCase)
? Done(sw, "checksum", BattleStatus.Passed, $"SHA3-256 {cHex}", cSec, oSec)
: Done(sw, "checksum", BattleStatus.Failed, $"SHA3-256 mismatch: cli {cHex} vs xdvdfs {oHex}", cSec,
oSec);
}
catch (Exception ex)
{
return Done(sw, "checksum", BattleStatus.Failed, $"{ex.GetType().Name}: {ex.Message}", 0, 0);
}
}
/// <summary>Battle: per-file MD5 lists must agree (every CLI entry must exist in the
/// xdvdfs list with the same hash; extra xdvdfs-only entries — e.g. directory rows —
/// are noted but not fatal).</summary>
private static SubResult RunMd5(string iso, ToolProcess cli, ToolProcess xdvdfs)
{
Stopwatch sw = Stopwatch.StartNew();
try
{
(int cCode, string cOut, string cErr, double cSec) = cli.Run("--md5", iso);
(int oCode, string oOut, string oErr, double oSec) = xdvdfs.Run("md5", iso);
if (cCode != 0 && oCode != 0)
{
return Done(sw, "md5", BattleStatus.Skipped,
$"both tools failed: cli: {First(cErr, cOut)}, xdvdfs: {First(oErr, oOut)}", cSec, oSec);
}
if (cCode != 0)
{
return Done(sw, "md5", BattleStatus.Failed, $"CLI exit {cCode}: {First(cErr, cOut)} (xdvdfs exit 0)",
cSec, oSec);
}
if (oCode != 0)
{
return Done(sw, "md5", BattleStatus.Failed, $"xdvdfs exit {oCode}: {First(oErr, oOut)} (CLI exit 0)",
cSec, oSec);
}
Dictionary<string, string> cMap = ParseMd5Map(cOut);
Dictionary<string, string> oMap = ParseMd5Map(oOut);
if (cMap.Count == 0 && oMap.Count == 0)
{
return Done(sw, "md5", BattleStatus.Skipped, "no md5 entries parsed from either tool", cSec, oSec);
}
List<string> diffs = [];
foreach ((string path, string hash) in cMap)
{
if (!oMap.TryGetValue(path, out string? oHash))
{
diffs.Add($"missing in xdvdfs list: {path}");
}
else if (!string.Equals(hash, oHash, StringComparison.OrdinalIgnoreCase))
{
diffs.Add($"md5 mismatch: {path}: cli {hash} vs xdvdfs {oHash}");
}
if (diffs.Count >= 5)
{
break;
}
}
int onlyXdvdfs = oMap.Keys.Except(cMap.Keys, StringComparer.Ordinal).Count();
if (diffs.Count > 0)
{
return Done(sw, "md5", BattleStatus.Failed,
$"{cMap.Count} cli entries vs {oMap.Count} xdvdfs entries\n " +
string.Join("\n ", diffs), cSec, oSec);
}
return Done(sw, "md5", BattleStatus.Passed,
$"{cMap.Count} files agree" +
(onlyXdvdfs > 0 ? $" ({onlyXdvdfs} xdvdfs-only dir/extra entries)" : string.Empty), cSec, oSec);
}
catch (Exception ex)
{
return Done(sw, "md5", BattleStatus.Failed, $"{ex.GetType().Name}: {ex.Message}", 0, 0);
}
}
/// <summary>Battle: --unpack vs `xdvdfs unpack` — extracted trees must match
/// (file set, per-file SHA-256, dir set).</summary>
private static SubResult RunUnpack(string iso, ToolProcess cli, ToolProcess xdvdfs, string work)
{
Stopwatch sw = Stopwatch.StartNew();
try
{
string csDir = Path.Combine(work, "cs");
string xdDir = Path.Combine(work, "xd");
Directory.CreateDirectory(csDir);
Directory.CreateDirectory(xdDir);
(int cCode, _, string cErr, double cSec) = cli.Run("--unpack", iso, csDir);
(int oCode, _, string oErr, double oSec) = xdvdfs.Run("unpack", iso, xdDir);
if (cCode != 0 && oCode != 0)
{
return Done(sw, "unpack", BattleStatus.Skipped,
$"both tools failed: cli: {First(cErr)}, xdvdfs: {First(oErr)}", cSec, oSec);
}
if (cCode != 0)
{
return Done(sw, "unpack", BattleStatus.Failed, $"CLI exit {cCode}: {First(cErr)} (xdvdfs exit 0)", cSec,
oSec);
}
if (oCode != 0)
{
return Done(sw, "unpack", BattleStatus.Failed, $"xdvdfs exit {oCode}: {First(oErr)} (CLI exit 0)", cSec,
oSec);
}
(bool equal, string detail) = CompareTrees(csDir, xdDir);
return Done(sw, "unpack", equal ? BattleStatus.Passed : BattleStatus.Failed, detail, cSec, oSec);
}
catch (Exception ex)
{
return Done(sw, "unpack", BattleStatus.Failed, $"{ex.GetType().Name}: {ex.Message}", 0, 0);
}
}
/// <summary>
/// Battle: `-c` (media patch off via -m) vs `xdvdfs pack` over the same unpacked
/// dir. The two packed images are compared via the deterministic content checksum
/// (layout-agnostic): identical file sets + bytes must produce identical SHA3-256.
/// </summary>
private static SubResult RunPack(string iso, ToolProcess cli, ToolProcess xdvdfs, string work)
{
Stopwatch sw = Stopwatch.StartNew();
try
{
Directory.CreateDirectory(work);
string dir = Path.Combine(work, "src");
string pIso = Path.Combine(work, "cs_packed.iso");
string xIso = Path.Combine(work, "xd_packed.iso");
(int uCode, _, string uErr, _) = cli.Run("--unpack", iso, dir);
if (uCode != 0)
{
return Done(sw, "pack", BattleStatus.Skipped, $"source unpack failed: {First(uErr)}", 0, 0);
}
// -m (no media patch) must precede -c: -c consumes the rest as positionals.
(int cCode, _, string cErr, double cSec) = cli.Run("-m", "-c", dir, pIso);
(int oCode, _, string oErr, double oSec) = xdvdfs.Run("pack", dir, xIso);
if (cCode != 0 && oCode != 0)
{
return Done(sw, "pack", BattleStatus.Skipped,
$"both tools failed: cli: {First(cErr)}, xdvdfs: {First(oErr)}", cSec, oSec);
}
if (cCode != 0)
{
return Done(sw, "pack", BattleStatus.Failed, $"CLI exit {cCode}: {First(cErr)} (xdvdfs exit 0)", cSec,
oSec);
}
if (oCode != 0)
{
return Done(sw, "pack", BattleStatus.Failed, $"xdvdfs exit {oCode}: {First(oErr)} (CLI exit 0)", cSec,
oSec);
}
(_, string cHex, _, _) = cli.Run("checksum", "--silent", pIso);
(_, string oHex, _, _) = cli.Run("checksum", "--silent", xIso);
string? pHex = FirstHex(cHex);
string? xHex = FirstHex(oHex);
if (pHex is null || xHex is null)
{
return Done(sw, "pack", BattleStatus.Skipped, "could not parse content checksums of the packed images",
cSec, oSec);
}
long pLen = new FileInfo(pIso).Length;
long xLen = new FileInfo(xIso).Length;
return string.Equals(pHex, xHex, StringComparison.OrdinalIgnoreCase)
? Done(sw, "pack", BattleStatus.Passed,
$"content parity: SHA3-256 {pHex} (cli {pLen} B, xdvdfs {xLen} B)", cSec, oSec)
: Done(sw, "pack", BattleStatus.Failed,
$"content mismatch: cli SHA3-256 {pHex} ({pLen} B) vs xdvdfs {xHex} ({xLen} B) over the same source dir",
cSec, oSec);
}
catch (Exception ex)
{
return Done(sw, "pack", BattleStatus.Failed, $"{ex.GetType().Name}: {ex.Message}", 0, 0);
}
}
/// <summary>
/// Battle: CISO round-trip with oracle cross-read. XISOSharp compresses the ISO
/// (split CSO), xdvdfs reads the CSO back (md5 per file — proves oracle-compatible
/// CSO output), XISOSharp decompresses and the content checksum must equal the
/// source image's. Redump inputs start with the video partition, which no CSO
/// reader accepts at sector 0 (xdvdfs compress itself refuses them), so the game
/// partition is staged to a sector-0 file first and the battle runs on that.
/// </summary>
private static SubResult RunCso(string iso, ToolProcess cli, ToolProcess xdvdfs, string work)
{
Stopwatch sw = Stopwatch.StartNew();
try
{
Directory.CreateDirectory(work);
string csoInput = TryStageRedumpPartition(iso, work) ?? iso;
(_, string srcHexOut, _, _) = cli.Run("checksum", "--silent", csoInput);
string? srcHex = FirstHex(srcHexOut);
if (srcHex is null)
{
return Done(sw, "cso", BattleStatus.Skipped, "could not parse source content checksum", 0, 0);
}
string csoPath = Path.Combine(work, "o.cso");
(int cCode, _, string cErr, double cSec) = cli.Run("cso", csoInput, csoPath);
if (cCode != 0)
{
return Done(sw, "cso", BattleStatus.Failed, $"CLI compress exit {cCode}: {First(cErr, "no output")}",
cSec, 0);
}
string[] parts = Directory.GetFiles(work, "*.cso", SearchOption.TopDirectoryOnly)
.OrderBy(static f => f, StringComparer.OrdinalIgnoreCase)
.ToArray();
if (parts.Length == 0)
{
return Done(sw, "cso", BattleStatus.Failed, "no CSO parts found after compress", cSec, 0);
}
(int oCode, string oOut, string oErr, double oSec) = xdvdfs.Run("md5", parts[0]);
if (oCode != 0)
{
return Done(sw, "cso", BattleStatus.Failed,
$"xdvdfs could not read the XISOSharp CSO (exit {oCode}): {First(oErr, oOut)}", cSec, oSec);
}
(_, string isoMd5Out, _, _) = cli.Run("--md5", csoInput);
Dictionary<string, string> isoMap = ParseMd5Map(isoMd5Out);
Dictionary<string, string> csoMap = ParseMd5Map(oOut);
List<string> diffs = [];
foreach ((string path, string hash) in isoMap)
{
if (!csoMap.TryGetValue(path, out string? cHash))
{
diffs.Add($"missing in xdvdfs md5 of CSO: {path}");
}
else if (!string.Equals(hash, cHash, StringComparison.OrdinalIgnoreCase))
{
diffs.Add($"md5 mismatch through CSO: {path}");
}
if (diffs.Count >= 5)
{
break;
}
}
string backIso = Path.Combine(work, "back.iso");
(int dCode, _, string dErr, _) = cli.Run("decompress", parts[0], backIso);
if (dCode != 0)
{
return Done(sw, "cso", BattleStatus.Failed, $"CLI decompress exit {dCode}: {First(dErr)}", cSec, oSec);
}
(_, string backHexOut, _, _) = cli.Run("checksum", "--silent", backIso);
string? backHex = FirstHex(backHexOut);
bool roundTrip = string.Equals(backHex, srcHex, StringComparison.OrdinalIgnoreCase);
if (!roundTrip)
{
diffs.Add($"round-trip checksum: source {srcHex} vs decompressed {backHex ?? "null"}");
}
return diffs.Count == 0
? Done(sw, "cso", BattleStatus.Passed,
$"{parts.Length} part(s); xdvdfs cross-read OK; round-trip checksum {backHex}", cSec, oSec)
: Done(sw, "cso", BattleStatus.Failed, string.Join("\n ", diffs), cSec, oSec);
}
catch (Exception ex)
{
return Done(sw, "cso", BattleStatus.Failed, $"{ex.GetType().Name}: {ex.Message}", 0, 0);
}
}
// ---- trim / wipe (xboxkit oracle) ----------------------------------------
/// <summary>
/// Battle: trim/wipe the game partition. xboxkit 0.7 cannot trim/wipe a full
/// Redump at all — <c>ExtractRedump</c> only writes XISOs for <c>-x</c>/<c>-p</c>/<c>-r</c>
/// and its <c>-t</c>/<c>-w</c>-alone warning is suppressed by <c>-y</c>, so it exits 0
/// with no output (KOTOR battle: "no trim output"). Like <c>cso</c>, the game
/// partition is staged to a sector-0 file first and both tools run on that in
/// xboxkit's ProcessXISO mode, which writes <c><name>.xiso</c> beside the input.
/// Outputs are compared byte-for-byte: trim copies merged extents verbatim and
/// truncates after the last one; wipe zeroes the gaps and copies extents
/// verbatim (both tools use merged bone+file ranges).
/// </summary>
private static SubResult RunTrimWipe(string op, string iso, ToolProcess cli, ToolProcess xk, string work,
string cliFlag, string xkFlag)
{
Stopwatch sw = Stopwatch.StartNew();
try
{
Directory.CreateDirectory(work);
string? stagedPart = TryStageRedumpPartition(iso, work);
bool staged = stagedPart is not null;
string part = stagedPart ?? Path.Combine(work, "src.iso");
if (!staged)
{
File.Copy(iso, part, true);
}
string xsOut = Path.Combine(work, "out.iso");
string xkOut = Path.Combine(work, Path.GetFileNameWithoutExtension(part) + ".xiso");
(int cCode, _, string cErr, double cSec) = cli.Run(cliFlag, "-o", xsOut, part);
(int oCode, string oOut, string oErr, double oSec) = xk.Run(xkFlag, "-y", "-q", part);
bool cliOk = cCode == 0 && File.Exists(xsOut);
bool xkOk = oCode == 0 && File.Exists(xkOut);
if (!cliOk && !xkOk)
{
return Done(sw, op, BattleStatus.Skipped,
$"both tools refused: cli: {First(cErr, $"no {op} output")}, xboxkit: {First(oErr, oOut)}", cSec,
oSec);
}
// Only comparable outputs can pass or fail; an asymmetric refusal is a
// capability difference surfaced in the detail, not a hash mismatch.
if (!xkOk)
{
return Done(sw, op, BattleStatus.Skipped,
$"xboxkit refused (exit {oCode}, no {op} output — trimmed/unsupported input?); CLI produced {Path.GetFileName(xsOut)} — nothing to compare",
cSec, oSec);
}
if (!cliOk)
{
return Done(sw, op, BattleStatus.Skipped,
$"CLI refused (exit {cCode}: {First(cErr, $"no {op} output")}); xboxkit produced {Path.GetFileName(xkOut)} — nothing to compare",
cSec, oSec);
}
string xsHash = HashUtil.ComputeSha256(xsOut);
string xkHash = HashUtil.ComputeSha256(xkOut);
long xsLen = new FileInfo(xsOut).Length;
long xkLen = new FileInfo(xkOut).Length;
return string.Equals(xsHash, xkHash, StringComparison.OrdinalIgnoreCase)
? Done(sw, op, BattleStatus.Passed,
$"{(staged ? "staged partition; " : string.Empty)}SHA256 {xsHash} ({xsLen} bytes)", cSec, oSec)
: Done(sw, op, BattleStatus.Failed,
$"SHA256 mismatch: cli {xsHash} ({xsLen} bytes) vs xboxkit {xkHash} ({xkLen} bytes)", cSec, oSec);
}
catch (Exception ex)
{
return Done(sw, op, BattleStatus.Failed, $"{ex.GetType().Name}: {ex.Message}", 0, 0);
}
}
// ---- xboxkit oracle ------------------------------------------------------
/// <summary>
/// Shared runner for the staged-copy, hash-compare xboxkit ops (petrify, video,
/// random, seed, zar). Each side works on its own staged copy of the
/// ISO (xboxkit writes beside / in-place on its input), outputs are discovered
/// (xboxkit always exits 0, so presence is the success signal), and the files are
/// compared by SHA-256. Both sides refusing = Skipped (e.g. trimmed ISOs for
/// redump-only ops); one side failing = Failed.
/// </summary>
/// <param name="op">Op name for reporting.</param>
/// <param name="iso">Path of the source ISO to stage a copy of per side.</param>
/// <param name="cli">The XISOSharp CLI process.</param>
/// <param name="xk">The xboxkit.exe oracle process.</param>
/// <param name="work">Scratch dir receiving the per-side staged copies.</param>
/// <param name="cliTemplate">CLI args template with {ISO}/{OUT} placeholders.</param>
/// <param name="xkTemplate">xboxkit args template with {ISO} placeholder.</param>
/// <param name="preferredPattern">Output glob hint for both sides (e.g. "*video*").</param>
private static SubResult RunStagedCompare(string op, string iso, ToolProcess cli, ToolProcess xk, string work,
string[] cliTemplate, string[] xkTemplate, string? preferredPattern)
{
Stopwatch sw = Stopwatch.StartNew();
try
{
string xsDir = Path.Combine(work, "cs");
string xkDir = Path.Combine(work, "xk");
Directory.CreateDirectory(xsDir);
Directory.CreateDirectory(xkDir);
string name = Path.GetFileName(iso);
string xsIso = Path.Combine(xsDir, name);
string xkIso = Path.Combine(xkDir, name);
File.Copy(iso, xsIso, true);
File.Copy(iso, xkIso, true);
string outExt = string.Equals(op, "zar", StringComparison.Ordinal) ? ".zar" : ".iso";
string xsOut = Path.Combine(xsDir, "out" + outExt);
string[] cliArgs =
[
.. cliTemplate.Select(a => a
.Replace("{ISO}", xsIso)
.Replace("{OUT}", xsOut))
];
string[] xkArgs = [.. xkTemplate.Select(a => a.Replace("{ISO}", xkIso))];
(int cCode, _, string cErr, double cSec) = cli.Run(cliArgs);
string? xkPreHash = preferredPattern is null ? HashUtil.ComputeSha256(xkIso) : null;
(int oCode, _, string oErr, double oSec) = xk.Run(xkArgs);
string? xsFile = cliTemplate.Any(static a => string.Equals(a, "{OUT}", StringComparison.Ordinal))
? (File.Exists(xsOut) ? xsOut : null)
: FindOutput(xsDir, xsIso, preferredPattern);
string? xkFile = preferredPattern is null
? (File.Exists(xkIso) ? xkIso : null)
: FindOutput(xkDir, xkIso, preferredPattern);
bool cliOk = cCode == 0 && xsFile is not null;
// In-place ops (trim/wipe): xboxkit always exits 0, so require an actual
// change — a different hash or an .old backup beside the staged input.
bool xkChanged = xkFile is not null &&
(preferredPattern is not null ||
!string.Equals(HashUtil.ComputeSha256(xkFile), xkPreHash,
StringComparison.OrdinalIgnoreCase) ||
Directory.GetFiles(xkDir, "*.old", SearchOption.TopDirectoryOnly).Length > 0);
bool xkOk = xkChanged;
if (!cliOk && !xkOk)
{
return Done(sw, op, BattleStatus.Skipped,
$"both tools refused: cli: {First(cErr, $"no {op} output")}, xboxkit: {First(oErr, $"no {op} output")}",
cSec, oSec);
}
// Only comparable outputs can pass or fail; an asymmetric refusal is a
// capability difference surfaced in the detail, not a hash mismatch.
if (!xkOk)
{
return Done(sw, op, BattleStatus.Skipped,
$"xboxkit refused (exit {oCode}, no {op} output — trimmed/unsupported input?); CLI produced {Path.GetFileName(xsFile)} — nothing to compare",
cSec, oSec);
}
if (!cliOk)
{
return Done(sw, op, BattleStatus.Skipped,
$"CLI refused (exit {cCode}: {First(cErr, $"no {op} output")}); xboxkit produced {Path.GetFileName(xkFile)} — nothing to compare",
cSec, oSec);
}
string xsHash = HashUtil.ComputeSha256(xsFile!);
string xkHash = HashUtil.ComputeSha256(xkFile!);
long xsLen = new FileInfo(xsFile!).Length;
long xkLen = new FileInfo(xkFile!).Length;
if (string.Equals(xsHash, xkHash, StringComparison.OrdinalIgnoreCase))
{
return Done(sw, op, BattleStatus.Passed, $"SHA256 {xsHash} ({xsLen} bytes)", cSec, oSec);
}
// Petrify tiebreaker: on a byte mismatch, verify our skeleton
// structurally before failing (see VerifySkeletonStructure).
if (string.Equals(op, "petrify", StringComparison.Ordinal))
{
SubResult? tie = PetrifyTiebreaker(sw, iso, xsFile!, cSec, oSec);
if (tie is not null)
{
return tie;
}
}
return Done(sw, op, BattleStatus.Failed,
$"SHA256 mismatch: cli {xsHash} ({xsLen} bytes) vs xboxkit {xkHash} ({xkLen} bytes)", cSec, oSec);
}
catch (Exception ex)
{
return Done(sw, op, BattleStatus.Failed, $"{ex.GetType().Name}: {ex.Message}", 0, 0);
}
}
/// <summary>
/// Battle: lossless redump rebuild. Components (video partition, filler, optional
/// su20076000 update) are extracted once with the CLI, then both tools rebuild the
/// full image from them; each rebuilt image must match the original byte-for-byte.
/// Requires a full redump image — skips on trimmed XISOs.
/// </summary>
private static SubResult RunRebuild(string iso, ToolProcess cli, ToolProcess xk, string work)
{
Stopwatch sw = Stopwatch.StartNew();
try
{
string xsDir = Path.Combine(work, "cs");
string xkDir = Path.Combine(work, "xk");
Directory.CreateDirectory(xsDir);
Directory.CreateDirectory(xkDir);
string stem = Path.GetFileNameWithoutExtension(iso);
string xsIso = Path.Combine(xsDir, stem + ".xiso");
string xkIso = Path.Combine(xkDir, stem + ".xiso");
File.Copy(iso, xsIso, true);
File.Copy(iso, xkIso, true);
(int vCode, _, string vErr, _) = cli.Run("--video", xsIso);
(int rCode, _, string rErr, _) = cli.Run("--random", xsIso);
if (vCode != 0 || rCode != 0)
{
return Done(sw, "rebuild", BattleStatus.Skipped,
$"component extraction refused (trimmed ISO?): video {vCode} {First(vErr)}, random {rCode} {First(rErr)}",
0, 0);
}
string? video = FindOutput(xsDir, xsIso, "*video*");
string? filler = FindOutput(xsDir, xsIso, "*filler*");
if (video is null || filler is null)
{
return Done(sw, "rebuild", BattleStatus.Skipped, "video/filler components not found after extraction",
0, 0);
}
(_, string uOut, _, _) = cli.Run("--update", xsIso);
string? update = Directory.GetFiles(xsDir, "su20076000*", SearchOption.TopDirectoryOnly).FirstOrDefault();
_ = uOut;
// Identical component inputs for both rebuilders.
File.Copy(video, Path.Combine(xkDir, Path.GetFileName(video)), true);
File.Copy(filler, Path.Combine(xkDir, Path.GetFileName(filler)), true);
if (update is not null)
{
File.Copy(update, Path.Combine(xkDir, Path.GetFileName(update)), true);
}
// Both rebuilders validate the XISO header at 0x10000, so the full
// Redump staged copies are not usable as the <xiso> component —
// stage the game partition (sector-0 file) as the rebuild input for
// both sides; for non-Redump inputs the staged copy already is it.
string? stagedPart = TryStageRedumpPartition(iso, xsDir);
if (stagedPart is not null)
{
File.Copy(stagedPart, xkIso, true);
}
string gameXiso = stagedPart ?? xsIso;
string xsOut = Path.Combine(xsDir, "rebuilt.iso");
List<string> xsArgs = ["rebuild", gameXiso, video, filler];
List<string> xkArgs = [xkIso, Path.GetFileName(video), Path.GetFileName(filler)];
if (update is not null)
{
xsArgs.Add(update);
xkArgs.Add(Path.GetFileName(update));
}
xsArgs.AddRange(["-o", xsOut]);
(int cCode, _, string cErr, double cSec) = cli.Run([.. xsArgs]);
// xboxkit rebuild mode combines the input files (cwd-sensitive args first,
// relative component names resolve beside the staged input).
string prevDir = Directory.GetCurrentDirectory();
double oSec = 0;
int oCode = 0;
string oErr = string.Empty;
try
{
Directory.SetCurrentDirectory(xkDir);
(oCode, _, oErr, oSec) = xk.Run([.. xkArgs]);
}
finally
{
Directory.SetCurrentDirectory(prevDir);
}
if (cCode != 0 && oCode != 0)
{
return Done(sw, "rebuild", BattleStatus.Skipped,
$"both tools failed: cli: {First(cErr)}, xboxkit: {First(oErr)}", cSec, oSec);
}
string originalHash = HashUtil.ComputeSha256(iso);
long originalLen = new FileInfo(iso).Length;
string? xsFile = File.Exists(xsOut) ? xsOut : FindOutput(xsDir, xsIso, "rebuilt*");
// xboxkit's rebuild default output is <stem>.iso beside the staged
// input (RebuildISO.ResolvePaths); never guess by timestamp here —
// the component copies (video/filler/update) also land in xkDir.
string xkExpected = Path.Combine(xkDir, stem + ".iso");
string? xkFile = File.Exists(xkExpected) ? xkExpected : null;
List<string> verdicts = [];
bool xsOk = false;
bool xkOk = false;
if (cCode != 0 || xsFile is null)
{
verdicts.Add($"CLI rebuild failed: exit {cCode}: {First(cErr, "no output")}");
}
else
{
string h = HashUtil.ComputeSha256(xsFile);
xsOk = string.Equals(h, originalHash, StringComparison.OrdinalIgnoreCase);
verdicts.Add(
$"cli rebuilt {(xsOk ? "MATCH" : "MISMATCH")} vs original ({h} vs {originalHash}, {new FileInfo(xsFile).Length}/{originalLen} B)");
}
if (oCode != 0 || xkFile is null)
{
verdicts.Add($"xboxkit rebuild failed: exit {oCode}: {First(oErr, "no output")}");
}
else
{
string h = HashUtil.ComputeSha256(xkFile);
xkOk = string.Equals(h, originalHash, StringComparison.OrdinalIgnoreCase);
verdicts.Add(
$"xboxkit rebuilt {(xkOk ? "MATCH" : "MISMATCH")} vs original ({h} vs {originalHash}, {new FileInfo(xkFile).Length}/{originalLen} B)");
}
BattleStatus status = xsOk && xkOk ? BattleStatus.Passed : BattleStatus.Failed;
return Done(sw, "rebuild", status, string.Join("\n ", verdicts), cSec, oSec);
}
catch (Exception ex)
{
return Done(sw, "rebuild", BattleStatus.Failed, $"{ex.GetType().Name}: {ex.Message}", 0, 0);
}
}
// ---- helpers -------------------------------------------------------------
/// <summary>
/// Tiebreaker for petrify byte mismatches. xboxkit 0.7's skeleton walk zeroes
/// to merged-extent ends (paving over bone islands that share an extent with
/// file data) and can desync its read position while hashing inline, so it
/// emits unlistable skeletons on real mastered images. When our skeleton
/// verifies structurally (bones verbatim, everything else zero) the mismatch
/// is an oracle-side defect (Skipped), not a CLI failure. Returns null when
/// our skeleton does not verify (fall through to Failed).
/// </summary>
private static SubResult? PetrifyTiebreaker(Stopwatch sw, string iso, string xsFile, double cSec, double oSec)
{
if (VerifySkeletonStructure(iso, xsFile, out string detail))
{
return Done(sw, "petrify", BattleStatus.Skipped,
$"CLI skeleton is structurally correct ({detail}) but differs from xboxkit -p " +
"(oracle zeroes filesystem tables inside mixed bone/file extents — oracle-side defect, not comparable)",
cSec, oSec);
}
return null;
}
/// <summary>
/// Structural skeleton check: same byte length as the game partition, every
/// filesystem (bone) byte identical to the source, every other byte zero.
/// Partition bounds mirror the CLI's Redump detection.
/// </summary>
private static bool VerifySkeletonStructure(string iso, string skeleton, out string detail)
{
detail = string.Empty;
try
{
long size = new FileInfo(iso).Length;
long isoOffset = 0;
long partLen = size;
if (TryGetPartitionBounds(iso, size, out long off, out long len))
{
isoOffset = off;
partLen = len;
}
long skelLen = new FileInfo(skeleton).Length;
if (skelLen != partLen)
{
detail = $"skeleton size {skelLen} != partition length {partLen}";
return false;
}
(List<(uint Start, uint End)> bones, _) = XisoRanges.GetXisoRanges(iso, isoOffset, true);
long baseSector = isoOffset / 2048;
List<(long Start, long End)> keep = [];
foreach ((uint s, uint e) in bones)
{
long cs = Math.Max((long)s, baseSector);
long ce = Math.Min((long)e, baseSector + ((partLen + 2047) / 2048) - 1);
if (ce < cs)
{
continue;
}
long bs = (cs - baseSector) * 2048;
long be = Math.Min((ce - baseSector + 1) * 2048, partLen);
if (bs < be && (keep.Count == 0 || bs > keep[^1].End))
{
keep.Add((bs, be));
}
else if (bs < be)
{
keep[^1] = (keep[^1].Start, Math.Max(keep[^1].End, be));
}
}
using FileStream srcFs = new(iso, FileMode.Open, FileAccess.Read, FileShare.Read, 65536);
using FileStream skFs = new(skeleton, FileMode.Open, FileAccess.Read, FileShare.Read, 65536);
srcFs.Seek(isoOffset, SeekOrigin.Begin);
byte[] srcBuf = new byte[1024 * 1024];
byte[] skBuf = new byte[1024 * 1024];
long pos = 0;
int ki = 0;
long boneBytes = 0;
while (pos < partLen)
{
int n = (int)Math.Min(srcBuf.Length, partLen - pos);
if (ReadFull(srcFs, srcBuf, n) != n || ReadFull(skFs, skBuf, n) != n)
{
detail = $"short read at partition offset {pos}";
return false;
}
for (int i = 0; i < n; i++)
{
long abs = pos + i;
while (ki < keep.Count && abs >= keep[ki].End)
{
ki++;
}
bool inBone = ki < keep.Count && abs >= keep[ki].Start;
if (inBone)
{
boneBytes++;
if (skBuf[i] != srcBuf[i])
{
detail = $"bone byte differs at partition offset {abs}";
return false;
}
}
else if (skBuf[i] != 0)
{
detail = $"non-zero non-bone byte at partition offset {abs}";
return false;
}
}
pos += n;
}
detail = $"{boneBytes} bone bytes verbatim, rest zeroed";
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
detail = $"verification I/O error: {ex.Message.Split('\n')[0]}";
return false;
}
}
private static int ReadFull(FileStream fs, byte[] buf, int count)
{
int total = 0;
while (total < count)
{
int n = fs.Read(buf, total, count - total);
if (n == 0)
{
break;
}
total += n;
}
return total;
}
/// <summary>
/// Resolves the game-partition bounds of a Redump ISO (mirrors the CLI's
/// detection); returns false for non-Redump inputs.
/// </summary>
private static bool TryGetPartitionBounds(string iso, long size, out long isoOffset, out long xisoLen)
{
isoOffset = 0;
xisoLen = size;
try
{
int redumpType = XgdTables.GetRedumpIsoTypeBySize(size);
if (redumpType < 0)
{
return false;
}
using FileStream fs = new(iso, FileMode.Open, FileAccess.Read, FileShare.Read, 65536);
int videoType = XgdTables.GetVideoType(fs, redumpType);
int xsType = XgdTables.GetXisoTypeFromVideo(videoType >= 0 ? videoType : 0);
if (xsType < 0 || xsType >= XgdTables.XisoOffset.Length)
{
xsType = XgdTables.GetXgdType(redumpType);
}
if (xsType < 0 || xsType >= XgdTables.XisoOffset.Length)
{
return false;
}
isoOffset = XgdTables.XisoOffset[xsType];
xisoLen = XgdTables.XisoLength[xsType];
return isoOffset >= 0 && xisoLen > 0 && isoOffset + xisoLen <= size;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}
}
/// <summary>
/// Stages the game-partition bytes of a Redump ISO as a sector-0 file
/// (<c>part.iso</c> under <paramref name="work"/>), or returns null when the
/// input is not a known Redump size (used as-is then). Partition bounds mirror
/// the CLI's Redump detection (<c>XgdTables</c>, pulled in transitively via the
/// CLI project reference).
/// </summary>
private static string? TryStageRedumpPartition(string iso, string work)
{
try
{
long size = new FileInfo(iso).Length;
if (!TryGetPartitionBounds(iso, size, out long isoOffset, out long xisoLen))
{
return null;
}
string part = Path.Combine(work, "part.iso");
using FileStream src = new(iso, FileMode.Open, FileAccess.Read, FileShare.Read, 65536);
using FileStream dst = new(part, FileMode.Create, FileAccess.Write, FileShare.None, 65536);
src.Seek(isoOffset, SeekOrigin.Begin);
byte[] buf = new byte[1024 * 1024];
long remaining = xisoLen;
while (remaining > 0)
{
int n = src.Read(buf, 0, (int)Math.Min(buf.Length, remaining));
if (n == 0)
{
return null;
}
dst.Write(buf, 0, n);
remaining -= n;
}
return part;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
/// <summary>First 64-hex token in the output (checksum lines are "hex" or "hex\tpath").</summary>
private static string? FirstHex(string stdout) =>
stdout.Split('\n')
.Select(static l => l.TrimEnd('\r').Trim())
.Select(static l => l.Split('\t', ' ')[0])
.FirstOrDefault(static t => t is not null && Hex64Regex.IsMatch(t));
/// <summary>Parses "md5 /path" lines into a path → hash map.</summary>
private static Dictionary<string, string> ParseMd5Map(string stdout)
{
Dictionary<string, string> map = new(StringComparer.Ordinal);
foreach (string line in stdout.Split('\n'))
{
Match m = Md5LineRegex.Match(line.TrimEnd('\r').TrimEnd());
if (m.Success)
{
map[m.Groups["path"].Value] = m.Groups["hash"].Value;
}
}
return map;
}
/// <summary>
/// Newest file in <paramref name="dir"/> matching <paramref name="preferredPattern"/>
/// (when given), excluding the staged input and *.old backups; falls back to the
/// newest non-input, non-.old file so unknown oracle naming still works.
/// </summary>
private static string? FindOutput(string dir, string inputPath, string? preferredPattern)
{
List<string> candidates = Directory.GetFiles(dir, "*", SearchOption.TopDirectoryOnly)
.Where(f => !string.Equals(f, inputPath, StringComparison.OrdinalIgnoreCase) &&
!f.EndsWith(".old", StringComparison.OrdinalIgnoreCase))
.ToList();
if (preferredPattern is not null)
{
string? hit = candidates
.Where(f => MatchesPattern(Path.GetFileName(f), preferredPattern))
.OrderByDescending(static f => new FileInfo(f).LastWriteTimeUtc)
.FirstOrDefault();
if (hit is not null)
{
return hit;
}
}
return candidates
.OrderByDescending(static f => new FileInfo(f).LastWriteTimeUtc)
.FirstOrDefault();
}
/// <summary>Case-insensitive glob match supporting the * wildcard only.</summary>
private static bool MatchesPattern(string name, string pattern)
{
if (!pattern.Contains('*'))
{
return string.Equals(name, pattern, StringComparison.OrdinalIgnoreCase);
}
string[] parts = pattern.Split('*');
int pos = 0;
foreach (string part in parts)
{
if (part.Length == 0)
{
continue;
}
int idx = name.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase);
if (idx < 0)
{
return false;
}
pos = idx + part.Length;
}
return true;
}
}