-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXisoCoverageTests.cs
More file actions
1432 lines (1240 loc) · 58.6 KB
/
Copy pathXisoCoverageTests.cs
File metadata and controls
1432 lines (1240 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
using XISOSharp.BlockDevice;
using XISOSharp.Models;
namespace XISOSharp.Tests;
/// <summary>
/// Targeted gap-closers for TODO #1 (full test suite, xdvdfs #107/#137):
/// exercises the <c>XisoReader</c> branches the suite never reached —
/// multi-sector directory tables, disc-layout probe ladders, block-device
/// error paths, sentinel/edge table shapes, and single-line guards — to
/// bring <c>XisoReader.cs</c> line coverage over 85%.
/// </summary>
[Collection("Sequential")]
public class XisoCoverageTests : IDisposable
{
private readonly List<string> _tempDirs = [];
private readonly TextWriter _savedOut;
private readonly TextWriter _savedError;
private readonly bool _savedQuiet;
private readonly bool _savedRealQuiet;
private readonly bool _savedRemoveSystemUpdate;
public XisoCoverageTests()
{
_savedOut = Logger.Out;
_savedError = Logger.Error;
_savedQuiet = Logger.Quiet;
_savedRealQuiet = Logger.RealQuiet;
_savedRemoveSystemUpdate = Logger.RemoveSystemUpdate;
}
public void Dispose()
{
foreach (string dir in _tempDirs)
{
try
{
if (Directory.Exists(dir)) Directory.Delete(dir, true);
else if (File.Exists(dir)) File.Delete(dir);
}
catch
{
/* best effort cleanup */
}
}
Logger.Out = _savedOut;
Logger.Error = _savedError;
Logger.Quiet = _savedQuiet;
Logger.RealQuiet = _savedRealQuiet;
Logger.RemoveSystemUpdate = _savedRemoveSystemUpdate;
}
private string CreateTempDir(string prefix)
{
string dir = Path.Combine(Path.GetTempPath(), $"{prefix}_{Guid.NewGuid():N}");
Directory.CreateDirectory(dir);
_tempDirs.Add(dir);
return dir;
}
private string CreateIso(Action<string> populate, string isoName)
{
string src = CreateTempDir("xiso_cov_src");
populate(src);
string dir = CreateTempDir("xiso_cov_iso");
int result = XisoWriter.CreateXiso(src, dir, null, null, out string? created, isoName, null);
Assert.Equal(0, result);
Assert.NotNull(created);
return created;
}
private string CopyIso(string isoPath, string prefix)
{
string dest = Path.Combine(CreateTempDir(prefix), Path.GetFileName(isoPath));
File.Copy(isoPath, dest);
return dest;
}
private static long FindEntryHeader(byte[] img, long tableAbs, uint tableSize, string name)
{
byte[] nameBytes = Encoding.ASCII.GetBytes(name);
long tableEnd = tableAbs + tableSize;
for (long i = tableAbs; i + 14 + nameBytes.Length <= Math.Min(tableEnd, img.Length); i++)
{
bool match = true;
for (int k = 0; k < nameBytes.Length; k++)
{
if (img[i + 14 + k] != nameBytes[k])
{
match = false;
break;
}
}
if (match && img[i + 13] == nameBytes.Length)
return i;
}
Assert.Fail($"entry '{name}' not found in directory table at {tableAbs}");
return -1;
}
private static (uint RootSize, long RootAbs) RootLayout(string isoPath)
{
VolumeInfo vol = XisoReader.GetVolumeInfo(isoPath);
Assert.True(vol.IsValid, $"fixture ISO invalid: {isoPath}");
return (vol.RootDirSize, ((long)vol.RootDirSector * Constants.SectorSize) + vol.DiscLseek);
}
// BUG-TEST-017: NTFS gating is discovery-time via [RequiresNtfsFact/Theory]
// (TEST-004 pattern) + SkipConditions.IsNtfsTempDrive — no private DriveInfo
// probe duplicate here.
// ------------------------------------------------------------------
// Multi-sector directory tables (sector-boundary advance + llCompat)
// ------------------------------------------------------------------
private string CreateManyFileIso(int count = 150) =>
CreateIso(src =>
{
for (int i = 0; i < count; i++)
File.WriteAllText(Path.Combine(src, $"file{i:000}.txt"), $"content {i}\n");
}, "many.iso");
[Fact]
public void ManyFileDir_Extract_CoversAllFiles()
{
string isoPath = CreateManyFileIso();
string dest = CreateTempDir("xiso_cov_dest");
Assert.Equal(0, XisoReader.Extract(isoPath, dest, false));
for (int i = 0; i < 150; i++)
Assert.Equal($"content {i}\n", File.ReadAllText(Path.Combine(dest, $"file{i:000}.txt")));
}
[Fact]
public void ManyFileDir_ExtractLlCompat_CoversAllFiles()
{
string isoPath = CreateManyFileIso();
string dest = CreateTempDir("xiso_cov_dest");
Assert.Equal(0, XisoReader.Extract(isoPath, dest, true));
for (int i = 0; i < 150; i++)
Assert.True(File.Exists(Path.Combine(dest, $"file{i:000}.txt")), $"file{i:000}.txt missing");
}
[Fact]
public void ManyFileDir_ListDirectory_CoversAllFiles()
{
string isoPath = CreateManyFileIso();
IReadOnlyList<EntryInfo> entries = XisoReader.ListDirectory(isoPath, "/");
Assert.Equal(150, entries.Count);
}
// ------------------------------------------------------------------
// Zeroed-table shapes (empty sentinels at start vs mid-table)
// ------------------------------------------------------------------
private static string ZeroTableStart(string isoPath, Func<string, string> copy)
{
VolumeInfo vol = XisoReader.GetVolumeInfo(isoPath);
long rootAbs = ((long)vol.RootDirSector * Constants.SectorSize) + vol.DiscLseek;
byte[] img = File.ReadAllBytes(isoPath);
Array.Clear(img, (int)rootAbs, 14);
string bad = copy(isoPath);
File.WriteAllBytes(bad, img);
return bad;
}
[Fact]
public void List_ZeroedTableStart_ReturnsZero()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
string bad = ZeroTableStart(isoPath, p => CopyIso(p, "xiso_cov_bad"));
Assert.Equal(0, XisoReader.List(bad, false));
}
[Fact]
public void ListDirectory_ZeroedTableStart_ReturnsEmpty()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
string bad = ZeroTableStart(isoPath, p => CopyIso(p, "xiso_cov_bad"));
Assert.Empty(XisoReader.ListDirectory(bad, "/"));
}
[Fact]
public void GetSectorLayout_ZeroedTableStart_HasOnlyRootTable()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
string bad = ZeroTableStart(isoPath, p => CopyIso(p, "xiso_cov_bad"));
SectorLayout layout = XisoReader.GetSectorLayout(bad);
Assert.DoesNotContain(layout.Entries, static e => !e.IsDirectory);
}
[Fact]
public void Extract_ZeroedNonFirstEntry_ThrowsOutsideTable()
{
// Zeroing a reachable non-first header turns it into an empty-table
// sentinel mid-walk: the sector-advance lands past the one-sector
// table, tripping the entry-outside-table guard.
string isoPath = CreateIso(src =>
{
File.WriteAllText(Path.Combine(src, "a.txt"), "hello");
File.WriteAllText(Path.Combine(src, "b.txt"), "world");
File.WriteAllText(Path.Combine(src, "c.txt"), "!");
}, "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long header = FindEntryHeader(img, rootAbs, rootSize, "c.txt");
Array.Clear(img, (int)header, 14);
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
XisoFormatException ex = Assert.Throws<XisoFormatException>(() =>
XisoReader.UnpackImage(bad, CreateTempDir("xiso_cov_dest")));
// Either the pad-rounding guard or the entry-position guard must name
// the outside-table failure (both are "invalid TOC entry" errors).
Assert.Contains("outside the directory table", ex.Message, StringComparison.Ordinal);
}
// ------------------------------------------------------------------
// Sibling/child pointer guards via the traverse path
// ------------------------------------------------------------------
[Fact]
public void Extract_LeftChildOutsideTable_ThrowsNamed()
{
string isoPath = CreateIso(src =>
{
File.WriteAllText(Path.Combine(src, "a.txt"), "hello");
File.WriteAllText(Path.Combine(src, "b.txt"), "world");
}, "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long header = FindEntryHeader(img, rootAbs, rootSize, "a.txt");
BinaryPrimitives.WriteUInt16LittleEndian(img.AsSpan((int)header), (ushort)(rootSize / 4));
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
XisoFormatException ex = Assert.Throws<XisoFormatException>(() =>
XisoReader.UnpackImage(bad, CreateTempDir("xiso_cov_dest")));
Assert.Contains("left child offset", ex.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("outside the directory table", ex.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void ContinueOnError_CorruptRoot_RecordsSummary()
{
string isoPath = CreateIso(src =>
{
File.WriteAllText(Path.Combine(src, "a.txt"), "hello");
File.WriteAllText(Path.Combine(src, "b.txt"), "world");
}, "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long header = FindEntryHeader(img, rootAbs, rootSize, "a.txt");
BinaryPrimitives.WriteUInt16LittleEndian(img.AsSpan((int)header), (ushort)(rootSize / 4));
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
UnpackOptions options = new() { ContinueOnError = true };
ExtractErrorException ex = Assert.Throws<ExtractErrorException>(() =>
XisoReader.UnpackImage(bad, CreateTempDir("xiso_cov_dest"), options: options));
Assert.Equal(ExtractError.ErrExtractFailed, ex.ErrorCode);
Assert.Contains("Failed to unpack image", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void ContinueOnError_CorruptLeftSubtree_SkipsAndContinues()
{
string isoPath = CreateIso(src =>
{
File.WriteAllText(Path.Combine(src, "a.txt"), "hello");
File.WriteAllText(Path.Combine(src, "b.txt"), "world");
File.WriteAllText(Path.Combine(src, "c.txt"), "!");
}, "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long headerA = FindEntryHeader(img, rootAbs, rootSize, "a.txt");
// a.left -> a itself (valid, in-table): the revisit throws inside the
// recursive call, hitting the left-subtree continue-on-error catch
// while the entry itself and all siblings still extract.
ushort selfA = (ushort)((headerA - rootAbs) / 4);
Assert.NotEqual(0, selfA);
BinaryPrimitives.WriteUInt16LittleEndian(img.AsSpan((int)headerA), selfA);
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
string dest = CreateTempDir("xiso_cov_dest");
UnpackOptions options = new() { ContinueOnError = true };
ExtractErrorException ex = Assert.Throws<ExtractErrorException>(() =>
XisoReader.UnpackImage(bad, dest, options: options));
Assert.Equal(ExtractError.ErrExtractFailed, ex.ErrorCode);
Assert.Equal("hello", File.ReadAllText(Path.Combine(dest, "a.txt")));
Assert.Equal("world", File.ReadAllText(Path.Combine(dest, "b.txt")));
Assert.Equal("!", File.ReadAllText(Path.Combine(dest, "c.txt")));
}
// ------------------------------------------------------------------
// DecodeXisoCore scaffolding guards
// ------------------------------------------------------------------
[Fact]
public void DecodeXiso_Stream_EmptyImageName_ReturnsOne()
{
using MemoryStream stream = new(new byte[1024]);
int rc = XisoReader.DecodeXiso(stream, "somedir\\", CreateTempDir("xiso_cov_dest"),
ExtractMode.List, out string? outPath, false);
Assert.Equal(1, rc);
Assert.Null(outPath);
}
[Fact]
public void Extract_OutputPathIsFile_ThrowsIOException()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
string blocker = Path.Combine(CreateTempDir("xiso_cov_dest"), "blocker");
File.WriteAllText(blocker, "in the way");
IOException ex = Assert.Throws<IOException>(() => XisoReader.Extract(isoPath, blocker, false));
Assert.Contains("already exists", ex.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Extract_IsoNameBlockedByFile_ThrowsIOException()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "other.iso");
string runDir = CreateTempDir("xiso_cov_rundir");
File.WriteAllText(Path.Combine(runDir, "other"), "in the way");
string savedCwd = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(runDir);
try
{
IOException ex = Assert.Throws<IOException>(() => XisoReader.Extract(isoPath, null, false));
Assert.Contains("already exists", ex.Message, StringComparison.OrdinalIgnoreCase);
}
finally
{
Directory.SetCurrentDirectory(savedCwd);
}
}
[Fact]
public void Extract_SystemUpdateSkippedWhenFlagSetAfterCreate()
{
string isoPath = CreateIso(src =>
{
string updateDir = Path.Combine(src, "$SystemUpdate");
Directory.CreateDirectory(updateDir);
File.WriteAllText(Path.Combine(updateDir, "update.bin"), "update data");
File.WriteAllText(Path.Combine(src, "game.txt"), "game data");
}, "game.iso");
// Flag off at create time (update IS in the image), on at extract time.
Logger.RemoveSystemUpdate = true;
try
{
string dest = CreateTempDir("xiso_cov_dest");
Assert.Equal(0, XisoReader.Extract(isoPath, dest, false));
Assert.True(File.Exists(Path.Combine(dest, "game.txt")));
Assert.False(File.Exists(Path.Combine(dest, "$SystemUpdate", "update.bin")),
"$SystemUpdate should be skipped at extract time");
}
finally
{
Logger.RemoveSystemUpdate = false;
}
}
// ------------------------------------------------------------------
// Block-device overloads (MemoryBlockDevice doubles)
// ------------------------------------------------------------------
private string CreateIsoBytes(Action<string> populate, string isoName) => CreateIso(populate, isoName);
[Fact]
public void VerifyXiso_Device_SkipZeroValid()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
using MemoryBlockDevice dev = new(File.ReadAllBytes(isoPath));
(uint sector, uint size, long lseek) = XisoReader.VerifyXiso(dev, "game.iso", skipSectors: 0);
Assert.True(sector > 0);
Assert.True(size > 0);
Assert.Equal(0, lseek);
}
[Fact]
public void VerifyXiso_Device_NegativeSkip_Throws()
{
using MemoryBlockDevice dev = new(new byte[1024]);
Assert.Throws<ArgumentOutOfRangeException>(() => XisoReader.VerifyXiso(dev, "x.iso", skipSectors: -1));
}
[Fact]
public void VerifyXiso_Device_SkipGarbage_ThrowsNoHeader()
{
using MemoryBlockDevice dev = new(new byte[Constants.HeaderOffset + 1024]);
XisoFormatException ex =
Assert.Throws<XisoFormatException>(() => XisoReader.VerifyXiso(dev, "x.iso", skipSectors: 0));
Assert.Contains("no header at sector 0", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void VerifyXiso_Device_SkipTiny_ThrowsReadHeader()
{
using MemoryBlockDevice dev = new(new byte[10]);
Assert.Throws<IOException>(() => XisoReader.VerifyXiso(dev, "x.iso", skipSectors: 0));
}
[Fact]
public void VerifyXiso_Device_Garbage_ThrowsInvalid()
{
using MemoryBlockDevice dev = new(new byte[Constants.HeaderOffset + 1024]);
Assert.Throws<XisoFormatException>(() => XisoReader.VerifyXiso(dev, "x.iso"));
}
[Fact]
public void VerifyXiso_Device_CutBeforeRootSector_Throws()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
byte[] bytes = File.ReadAllBytes(isoPath)[..(Constants.HeaderOffset + Constants.HeaderDataLength)];
using MemoryBlockDevice dev = new(bytes);
Assert.Throws<IOException>(() => XisoReader.VerifyXiso(dev, "game.iso"));
}
[Fact]
public void VerifyXiso_Device_CutBeforeRootSize_Throws()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
byte[] bytes = File.ReadAllBytes(isoPath)[..(Constants.HeaderOffset + Constants.HeaderDataLength + 4)];
using MemoryBlockDevice dev = new(bytes);
Assert.Throws<IOException>(() => XisoReader.VerifyXiso(dev, "game.iso"));
}
[Fact]
public void VerifyXiso_Device_CutBeforeTail_Throws()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
byte[] bytes = File.ReadAllBytes(isoPath)[..(Constants.HeaderOffset + Constants.HeaderDataLength + 8)];
using MemoryBlockDevice dev = new(bytes);
IOException ex = Assert.Throws<IOException>(() => XisoReader.VerifyXiso(dev, "game.iso"));
Assert.Contains("trailing magic", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void VerifyXiso_Device_TailCorrupt_ThrowsCorrupt()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
byte[] bytes = File.ReadAllBytes(isoPath);
Array.Clear(bytes,
Constants.HeaderOffset + Constants.HeaderDataLength + 4 + 4 + Constants.FileTimeSize +
Constants.UnusedSize, Constants.HeaderDataLength);
using MemoryBlockDevice dev = new(bytes);
XisoFormatException ex = Assert.Throws<XisoFormatException>(() => XisoReader.VerifyXiso(dev, "game.iso"));
Assert.Contains("Corrupt XISO", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void Extract_LargeTable_PadOffsetsDoNotWrap()
{
// BUG-LIB-028: past ~64K DWORDs of table, sector-pad rounding used to
// wrap through (ushort) and mis-walk valid images. A 3500-file table
// forces pads beyond that range: it must pack, audit, and extract whole.
const int fileCount = 3500;
string isoPath = CreateIso(src =>
{
for (int i = 0; i < fileCount; i++)
File.WriteAllText(Path.Combine(src, $"f{i:0000}.txt"), "x");
}, "big.iso");
Assert.True(XisoReader.AuditXiso(isoPath).IsValid);
string dest = CreateTempDir("xiso_cov_bigdest");
Assert.Equal(0, XisoReader.UnpackImage(isoPath, dest));
Assert.Equal(fileCount, Directory.GetFiles(dest, "*", SearchOption.AllDirectories).Length);
}
[Fact]
public void VerifyXiso_Device_EmptyRoot_ThrowsEmpty()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
byte[] bytes = File.ReadAllBytes(isoPath);
Array.Clear(bytes, Constants.HeaderOffset + Constants.HeaderDataLength, 8);
using MemoryBlockDevice dev = new(bytes);
Assert.Throws<XisoEmptyException>(() => XisoReader.VerifyXiso(dev, "game.iso"));
}
[Fact]
public void VerifyXiso_Device_RootBeyondEnd_Throws()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
byte[] bytes = File.ReadAllBytes(isoPath);
BinaryPrimitives.WriteUInt32LittleEndian(
bytes.AsSpan(Constants.HeaderOffset + Constants.HeaderDataLength), 0x00FFFFFFu);
using MemoryBlockDevice dev = new(bytes);
XisoFormatException ex = Assert.Throws<XisoFormatException>(() => XisoReader.VerifyXiso(dev, "game.iso"));
Assert.Contains("beyond end", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void AuditXiso_Device_Valid_ReturnsValid()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
using MemoryBlockDevice dev = new(File.ReadAllBytes(isoPath));
AuditResult result = XisoReader.AuditXiso(dev, "game.iso");
Assert.True(result.IsValid);
// Deep walk, not header-only (BUG-LIB-012): the file must be counted.
Assert.True(result.FilesChecked > 0);
Assert.True(result.IsOptimized);
Assert.Empty(result.Issues);
}
[Fact]
public void AuditXiso_Device_EmptyRoot_ReportsTag()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
byte[] bytes = File.ReadAllBytes(isoPath);
Array.Clear(bytes, Constants.HeaderOffset + Constants.HeaderDataLength, 8);
using MemoryBlockDevice dev = new(bytes);
AuditResult result = XisoReader.AuditXiso(dev, "game.iso");
Assert.True(result.IsValid);
Assert.True(result.IsOptimized);
Assert.Empty(result.Issues);
}
[Fact]
public void AuditXiso_Device_CorruptTree_ReturnsInvalid()
{
// Same valid image, but the root entry name gets a path separator:
// header probes pass, so only a real tree walk can fail this.
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
byte[] bytes = File.ReadAllBytes(isoPath);
uint rootSector = BinaryPrimitives.ReadUInt32LittleEndian(
bytes.AsSpan(Constants.HeaderOffset + Constants.HeaderDataLength));
long rootAbs = (long)rootSector * Constants.SectorSize;
bytes[rootAbs + 14] = (byte)'/';
using MemoryBlockDevice dev = new(bytes);
AuditResult result = XisoReader.AuditXiso(dev, "game.iso");
Assert.False(result.IsValid);
Assert.NotEmpty(result.Issues);
}
[Fact]
public void AuditXiso_Device_Garbage_ReturnsInvalid()
{
using MemoryBlockDevice dev = new(new byte[Constants.HeaderOffset + 1024]);
AuditResult result = XisoReader.AuditXiso(dev, "x.iso");
Assert.False(result.IsValid);
Assert.NotEmpty(result.Issues);
}
[Fact]
public void GetFileTime_Device_ReturnsStamp()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
DateTimeOffset expected = XisoReader.GetFileTime(isoPath);
using MemoryBlockDevice dev = new(File.ReadAllBytes(isoPath));
Assert.Equal(expected, XisoReader.GetFileTime(dev, "game.iso"));
}
[Fact]
public void GetFileTimeRaw_Device_ShortFileTime_Throws()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
byte[] bytes = File.ReadAllBytes(isoPath)[..(Constants.HeaderOffset + Constants.HeaderDataLength + 8)];
using MemoryBlockDevice dev = new(bytes);
Assert.Throws<IOException>(() => XisoReader.GetFileTimeRaw(dev, "game.iso"));
}
[Fact]
public void GetFileTimeRaw_Device_SkipNegative_Throws()
{
using MemoryBlockDevice dev = new(new byte[1024]);
Assert.Throws<ArgumentOutOfRangeException>(() =>
XisoReader.GetFileTimeRaw(dev, "x.iso", skipSectors: -1));
}
[Fact]
public void GetFileTimeRaw_Device_SkipZero_Valid()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
ulong expected = XisoReader.GetFileTimeRaw(isoPath);
using MemoryBlockDevice dev = new(File.ReadAllBytes(isoPath));
Assert.Equal(expected, XisoReader.GetFileTimeRaw(dev, "game.iso", skipSectors: 0));
}
[Fact]
public void GetFileTimeRaw_Device_SkipBadMagic_Throws()
{
using MemoryBlockDevice dev = new(new byte[Constants.HeaderOffset + 1024]);
Assert.Throws<XisoFormatException>(() => XisoReader.GetFileTimeRaw(dev, "x.iso", skipSectors: 0));
}
[Fact]
public void GetFileTimeRaw_Device_Garbage_ThrowsInvalid()
{
using MemoryBlockDevice dev = new(new byte[Constants.HeaderOffset + 1024]);
Assert.Throws<XisoFormatException>(() => XisoReader.GetFileTimeRaw(dev, "x.iso"));
}
// ------------------------------------------------------------------
// FILETIME stream-probe gaps
// ------------------------------------------------------------------
[Fact]
public void GetFileTimeRaw_NegativeSkip_Throws()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
Assert.Throws<ArgumentOutOfRangeException>(() => XisoReader.GetFileTimeRaw(isoPath, skipSectors: -1));
}
[Fact]
public void GetFileTimeRaw_SkipZero_ReturnsStamp()
{
string isoPath = CreateIsoBytes(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
Assert.Equal(XisoReader.GetFileTimeRaw(isoPath), XisoReader.GetFileTimeRaw(isoPath, skipSectors: 0));
}
[Fact]
public void GetFileTimeRaw_SkipBadMagic_Throws()
{
string path = Path.Combine(CreateTempDir("xiso_cov_bad"), "bad.iso");
File.WriteAllBytes(path, new byte[Constants.HeaderOffset + 1024]);
XisoFormatException ex =
Assert.Throws<XisoFormatException>(() => XisoReader.GetFileTimeRaw(path, skipSectors: 0));
Assert.Contains("no header at sector 0", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void GetFileTimeRaw_TruncatedProbes_ThrowsInvalid()
{
string path = Path.Combine(CreateTempDir("xiso_cov_bad"), "short.iso");
File.WriteAllBytes(path, new byte[Constants.HeaderOffset + 10]);
Assert.Throws<XisoFormatException>(() => XisoReader.GetFileTimeRaw(path));
}
// ------------------------------------------------------------------
// GetVolumeInfo disc-layout probe ladder (sparse files, NTFS only:
// SetLength is metadata-only there, reads are tiny 20-byte probes)
// ------------------------------------------------------------------
[RequiresNtfsTheory]
[InlineData(0x0FD90000L)]
[InlineData(0x02080000L)]
[InlineData(0x89D80000L)]
[InlineData(0x18300000L)]
public void GetVolumeInfo_DiscOffsetMagic_Detected(long discOffset)
{
// RequiresNtfsTheory already skipped non-NTFS at discovery (BUG-TEST-017):
// SetLength stays metadata-only sparse here; no runtime probe needed.
string dir = CreateTempDir("xiso_cov_bad");
string path = Path.Combine(dir, "offset.iso");
// Every earlier probe must read (zeros) rather than throw, so all
// files are sized past the largest probe (Xgd2Hybrid).
const long minLength = 0x89D80000L + Constants.HeaderOffset + 1024;
using (FileStream fs = new(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
fs.SetLength(minLength);
fs.Seek(discOffset + Constants.HeaderOffset, SeekOrigin.Begin);
fs.Write(Encoding.ASCII.GetBytes(Constants.HeaderData));
}
VolumeInfo vol = XisoReader.GetVolumeInfo(path);
Assert.True(vol.IsValid);
Assert.Equal(discOffset, vol.DiscLseek);
}
[Fact]
public void GetVolumeInfo_BigGarbage_ReturnsNotValid()
{
string path = Path.Combine(CreateTempDir("xiso_cov_bad"), "garbage.iso");
byte[] data = new byte[Constants.HeaderOffset + 1024];
new Random(42).NextBytes(data);
File.WriteAllBytes(path, data);
Assert.False(XisoReader.GetVolumeInfo(path).IsValid);
}
[RequiresNtfsFact]
public void GetVolumeInfo_BigZeros_ReturnsNotValid()
{
// All probes read (zeros) but none match: the no-match return, not
// the short-read catch. Sparse file (NTFS only), reads are tiny.
// RequiresNtfsFact already skipped non-NTFS at discovery (BUG-TEST-017).
string dir = CreateTempDir("xiso_cov_bad");
string path = Path.Combine(dir, "zeros.iso");
using (FileStream fs = new(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
fs.SetLength(0x89D80000L + Constants.HeaderOffset + 1024);
}
Assert.False(XisoReader.GetVolumeInfo(path).IsValid);
}
// ------------------------------------------------------------------
// Empty-root image (sector 0 / size 0)
// ------------------------------------------------------------------
private string CreateEmptyIso()
{
string src = CreateTempDir("xiso_cov_empty");
string dir = CreateTempDir("xiso_cov_iso");
int result = XisoWriter.CreateXiso(src, dir, null, null, out string? created, "empty", null);
Assert.Equal(0, result);
Assert.NotNull(created);
return created;
}
[Fact]
public void EmptyRoot_ListDirectory_ReturnsEmpty() => Assert.Empty(XisoReader.ListDirectory(CreateEmptyIso(), "/"));
[Fact]
public void EmptyRoot_GetSectorLayout_ReturnsHeaderOnly()
{
SectorLayout layout = XisoReader.GetSectorLayout(CreateEmptyIso());
Assert.DoesNotContain(layout.Entries, static e => !e.IsDirectory);
}
[Fact]
public void EmptyRoot_Audit_ReturnsValid()
{
AuditResult result = XisoReader.AuditXiso(CreateEmptyIso());
Assert.True(result.IsValid);
}
// ------------------------------------------------------------------
// ListDirectory / GetSectorLayout / GetEntryInfo walker gaps
// ------------------------------------------------------------------
[Fact]
public void GetEntryInfo_SlashesOnly_ReturnsNull()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
Assert.Null(XisoReader.GetEntryInfo(isoPath, "///"));
}
[Fact]
public void ListDirectory_LeftBeyondImage_Throws()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long header = FindEntryHeader(img, rootAbs, rootSize, "a.txt");
BinaryPrimitives.WriteUInt16LittleEndian(img.AsSpan((int)header), 0xFFFE);
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
XisoFormatException ex = Assert.Throws<XisoFormatException>(() => XisoReader.ListDirectory(bad, "/"));
Assert.Contains("outside the image", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void GetSectorLayout_LeftBeyondImage_Throws()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long header = FindEntryHeader(img, rootAbs, rootSize, "a.txt");
BinaryPrimitives.WriteUInt16LittleEndian(img.AsSpan((int)header), 0xFFFE);
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
XisoFormatException ex = Assert.Throws<XisoFormatException>(() => XisoReader.GetSectorLayout(bad));
Assert.Contains("outside the image", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void GetSectorLayout_LeftSelfCycle_Throws()
{
string isoPath = CreateIso(src =>
{
File.WriteAllText(Path.Combine(src, "a.txt"), "hello");
File.WriteAllText(Path.Combine(src, "b.txt"), "world");
}, "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long header = FindEntryHeader(img, rootAbs, rootSize, "b.txt");
ushort self = (ushort)((header - rootAbs) / 4);
Assert.NotEqual(0, self);
BinaryPrimitives.WriteUInt16LittleEndian(img.AsSpan((int)header), self);
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
XisoFormatException ex = Assert.Throws<XisoFormatException>(() => XisoReader.GetSectorLayout(bad));
Assert.Contains("cycle", ex.Message, StringComparison.OrdinalIgnoreCase);
}
private string CreateDotEntryIso()
{
string isoPath = CreateIso(src =>
{
File.WriteAllText(Path.Combine(src, "a.txt"), "hello");
File.WriteAllText(Path.Combine(src, "b.txt"), "world");
}, "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long header = FindEntryHeader(img, rootAbs, rootSize, "a.txt");
img[header + 13] = 1;
img[header + 14] = (byte)'.';
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
return bad;
}
[Fact]
public void ListDirectory_DotEntry_SkippedButSiblingsListed()
{
IReadOnlyList<EntryInfo> entries = XisoReader.ListDirectory(CreateDotEntryIso(), "/");
Assert.DoesNotContain(entries, static e => string.Equals(e.Name, ".", StringComparison.OrdinalIgnoreCase));
Assert.Contains(entries, static e => string.Equals(e.Name, "b.txt", StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void GetSectorLayout_DotEntry_Skipped()
{
SectorLayout layout = XisoReader.GetSectorLayout(CreateDotEntryIso());
Assert.DoesNotContain(layout.Entries,
static e => string.Equals(e.Path, "/.", StringComparison.OrdinalIgnoreCase));
Assert.Contains(layout.Entries,
static e => string.Equals(e.Path, "/b.txt", StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void GetSectorLayout_ReservesTagAndIso9660Descriptors()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
SectorLayout layout = XisoReader.GetSectorLayout(isoPath);
// Regression (Todo item 2): in-place patching must not allocate over the
// optimized tag (partition sector 15) or the ISO9660 descriptor pair
// (sectors 16-17).
Assert.Contains(layout.UsedRanges,
static r => r.StartSector <= 15 && 15 < r.StartSector + r.SectorCount);
Assert.Contains(layout.UsedRanges,
static r => r.StartSector <= 16 && 17 < r.StartSector + r.SectorCount);
}
[Fact]
public void GetFileEntries_AllZeroTable_YieldsNoPhantomEntry()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
(_, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
Array.Clear(img, (int)rootAbs, Constants.SectorSize);
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
// Regression (Todo item 15): the xdvdfs all-zero empty table must not
// parse as a phantom file entry.
Assert.Empty(XisoRanges.GetFileEntries(bad));
}
[Fact]
public void GetFileEntries_DotEntry_SkippedButSiblingsListed()
{
List<(string Path, long Offset, uint Size)> entries = XisoRanges.GetFileEntries(CreateDotEntryIso());
Assert.DoesNotContain(entries, static e => string.Equals(e.Path, ".", StringComparison.OrdinalIgnoreCase));
Assert.Contains(entries, static e => string.Equals(e.Path, "b.txt", StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void Rewrite_ShortImageName_DoesNotThrow()
{
string isoPath = CreateIso(src => File.WriteAllText(Path.Combine(src, "a.txt"), "hello"), "game.iso");
string dir = CreateTempDir("xiso_cov_short");
string shortPath = Path.Combine(dir, "ab");
File.Copy(isoPath, shortPath);
string outDir = CreateTempDir("xiso_cov_short_out");
// Regression (Todo #49): the legacy last-4 strip used to throw on names
// shorter than four characters instead of returning them as-is.
Assert.Equal(0, XisoReader.Rewrite(shortPath, outDir, out string? rewritten));
Assert.NotNull(rewritten);
Assert.True(File.Exists(rewritten));
}
[Fact]
public void CreateXiso_DotSourceDirectory_PacksFromThatDirectory()
{
string src = CreateTempDir("xiso_cov_dot_src");
File.WriteAllText(Path.Combine(src, "dot.txt"), "dotted");
string outDir = CreateTempDir("xiso_cov_dot_iso");
string cwd = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(src);
// Regression (Todo item 3): `-c .` must pack the current directory,
// not its parent (the write phase re-enters the source by name).
int rc = XisoWriter.CreateXiso(".", outDir, null, null, out string? isoPath, null, null);
Assert.Equal(0, rc);
Assert.NotNull(isoPath);
string dest = CreateTempDir("xiso_cov_dot_dest");
XisoReader.UnpackImage(isoPath, dest);
Assert.Equal("dotted", File.ReadAllText(Path.Combine(dest, "dot.txt")));
}
finally
{
Directory.SetCurrentDirectory(cwd);
}
}
[Fact]
public void GetSectorLayout_SubSizeZero_SkipsTable()
{
string isoPath = CreateIso(src =>
{
File.WriteAllText(Path.Combine(src, "top.txt"), "top");
Directory.CreateDirectory(Path.Combine(src, "sub"));
File.WriteAllText(Path.Combine(src, "sub", "inner.txt"), "inner");
}, "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long header = FindEntryHeader(img, rootAbs, rootSize, "sub");
BinaryPrimitives.WriteUInt32LittleEndian(img.AsSpan((int)header + 8), 0u);
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
SectorLayout layout = XisoReader.GetSectorLayout(bad);
Assert.Contains(layout.Entries,
static e => string.Equals(e.Path, "/sub", StringComparison.OrdinalIgnoreCase) && e.FileSize == 0);
}
[Fact]
public void GetSectorLayout_EmptyFile_MergesRanges()
{
string isoPath = CreateIso(src =>
{
File.WriteAllText(Path.Combine(src, "empty.txt"), "");
File.WriteAllText(Path.Combine(src, "full.txt"), "data");
}, "game.iso");
SectorLayout layout = XisoReader.GetSectorLayout(isoPath);
Assert.Contains(layout.Entries,
static e => string.Equals(e.Path, "/empty.txt", StringComparison.OrdinalIgnoreCase) && e.SectorCount == 0);
}
[Fact]
public void GetSectorLayout_SubSizeHuge_Throws()
{
string isoPath = CreateIso(src =>
{
File.WriteAllText(Path.Combine(src, "top.txt"), "top");
Directory.CreateDirectory(Path.Combine(src, "sub"));
File.WriteAllText(Path.Combine(src, "sub", "inner.txt"), "inner");
}, "game.iso");
(uint rootSize, long rootAbs) = RootLayout(isoPath);
byte[] img = File.ReadAllBytes(isoPath);
long header = FindEntryHeader(img, rootAbs, rootSize, "sub");
BinaryPrimitives.WriteUInt32LittleEndian(img.AsSpan((int)header + 8), 0xFFFFFF00u);
string bad = CopyIso(isoPath, "xiso_cov_bad");
File.WriteAllBytes(bad, img);
XisoFormatException ex = Assert.Throws<XisoFormatException>(() => XisoReader.GetSectorLayout(bad));
Assert.Contains("outside the image", ex.Message, StringComparison.Ordinal);
}
private static string CreateDeepTree(string baseDir, int depth)
{
string dir = baseDir;
for (int i = 0; i < depth; i++)
{
dir = Path.Combine(dir, "a");
Directory.CreateDirectory(dir);
}
File.WriteAllText(Path.Combine(dir, "leaf.txt"), "leaf\n");
return baseDir;
}
[Fact]
public void GetSectorLayout_DeepTree_ThrowsDepth()
{
string src = CreateDeepTree(CreateTempDir("xiso_cov_deep"), 70);
string dir = CreateTempDir("xiso_cov_iso");
Assert.Equal(0, XisoWriter.CreateXiso(src, dir, null, null, out string? isoPath, "deep", null));
Assert.NotNull(isoPath);
XisoFormatException ex = Assert.Throws<XisoFormatException>(() => XisoReader.GetSectorLayout(isoPath));