-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXtafProgram.cs
More file actions
1720 lines (1508 loc) · 72.9 KB
/
Copy pathXtafProgram.cs
File metadata and controls
1720 lines (1508 loc) · 72.9 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Fsp;
using Microsoft.Win32;
namespace Xtaf
{
internal sealed class CommandLineUsageException : Exception
{
public CommandLineUsageException(string message = null) : base(message)
{
}
}
internal sealed class WinFspRuntimeException : Exception
{
public WinFspRuntimeException(string message, Exception innerException = null) : base(message, innerException)
{
}
}
internal sealed class MountSession : IDisposable
{
readonly List<FileSystemHost> hosts = new List<FileSystemHost>();
readonly List<MountedVolumeInfo> volumes = new List<MountedVolumeInfo>();
readonly List<SkippedPartitionInfo> skippedPartitions = new List<SkippedPartitionInfo>();
public MountSession(Stream stream)
{
Stream = stream;
}
public Stream Stream { get; private set; }
public IList<MountedVolumeInfo> Volumes { get { return volumes.AsReadOnly(); } }
public IList<SkippedPartitionInfo> SkippedPartitions { get { return skippedPartitions.AsReadOnly(); } }
public void Add(FileSystemHost host, string fsType, string logicalName)
{
hosts.Add(host);
volumes.Add(new MountedVolumeInfo
{
FileSystemType = fsType,
LogicalName = logicalName,
MountPoint = host.MountPoint()
});
}
public void AddSkippedPartition(PartitionCandidate partition, string reason)
{
skippedPartitions.Add(new SkippedPartitionInfo
{
Name = partition == null ? "Unknown" : partition.Name,
Offset = partition == null ? 0 : partition.Offset,
Reason = string.IsNullOrWhiteSpace(reason) ? "mount failed" : reason
});
}
public void Dispose()
{
for (int i = hosts.Count - 1; i >= 0; i--)
{
Program.DisposeHost(hosts[i]);
}
hosts.Clear();
if (Stream != null)
{
Stream.Dispose();
Stream = null;
}
}
}
internal static class Program
{
const string ProgramName = "xtaf";
const int AutoScanStep = 0x1000;
const int MaxRecoveredPartitions = 32;
internal delegate bool PartitionMountAttempt(
MountSession session,
MountOptions options,
PartitionCandidate partition,
string mountPoint,
object streamLock,
bool continueOnFailure,
out string failureReason);
static Program()
{
AppDomain.CurrentDomain.AssemblyResolve += ResolveWinFspAssembly;
}
static readonly PartitionProfileEntry[] KnownPartitions = new[]
{
new PartitionProfileEntry("cache0", "Cache Partition 0", 0x00080000L, 0x80000000L),
new PartitionProfileEntry("cache1", "Cache Partition 1", 0x80080000L, 0x80000000L),
new PartitionProfileEntry("recoveryaux", "Recovery Partition (Aux)", 0x10C080000L, 0x0CE30000L),
new PartitionProfileEntry("recovery", "Recovery Partition (Ext)", 0x118EB0000L, 0x08000000L),
new PartitionProfileEntry("backcompat", "Backward Compatibility", 0x120EB0000L, 0x10000000L),
new PartitionProfileEntry("content", "Content", 0x130EB0000L, 0),
new PartitionProfileEntry("systemext", "System Extended", 0x10000000L, 0x04000000L),
new PartitionProfileEntry("systemaux", "System Auxiliary", 0x14000000L, 0x10000000L),
new PartitionProfileEntry("backcompat", "Compatibility", 0x24000000L, 0x20C000000L),
new PartitionProfileEntry("content", "Content", 0x230000000L, 0x2D0000000L),
new PartitionProfileEntry("systempartition", "SystemPartition", 0x2A0EB0000L, 0x10000000L),
new PartitionProfileEntry("content", "Content", 0x2B0EB0000L, 0x183DAC6000L),
new PartitionProfileEntry("mucache", "MU Cache", 0x00000000L, 0x007FF000L),
new PartitionProfileEntry("mucontent", "MU Content", 0x007FF000L, 0)
};
static readonly string[] DefaultPriority = new[]
{
"content", "mucontent", "backcompat", "systemext", "systemaux", "recovery", "recoveryaux", "cache0", "cache1", "mucache"
};
static int Main(string[] args)
{
try
{
MountOptions options = ParseArgs(args);
bool recoveryRequested = XtafRecoveryEngine.IsRecoveryRequested(options);
bool sizeAuditRequested = options.AnalyzeImageSize || !string.IsNullOrWhiteSpace(options.TrimImageOutputPath);
bool volumeOpsRequested = options.VolumeStats || !string.IsNullOrWhiteSpace(options.ExtractVolumePath);
if (options.ShowHelp)
{
PrintUsage();
return 0;
}
if (!File.Exists(options.ImagePath))
throw new CommandLineUsageException("Image file was not found.");
bool assistOnly = options.DiskpartAssist &&
!options.ListPartitions &&
!options.MountAllPartitions &&
string.IsNullOrWhiteSpace(options.PartitionSelector) &&
string.IsNullOrWhiteSpace(options.MountPoint) &&
string.IsNullOrWhiteSpace(options.MountRoot);
if (options.ListPartitions || options.DiskpartAssist || recoveryRequested)
{
using (Stream scan = OpenImageStream(options.ImagePath, options.Features))
{
List<PartitionCandidate> partitions = DiscoverPartitions(scan, options.Features);
if (options.ListPartitions || options.DiskpartAssist)
PrintPartitions(partitions, options.ImagePath);
if (options.DiskpartAssist)
PrintDiskpartAssist(options.ImagePath, partitions);
if (recoveryRequested)
{
XtafRecoveryEngine.Run(options, scan, partitions);
return 0;
}
}
if ((options.ListPartitions || assistOnly) && !sizeAuditRequested && !volumeOpsRequested)
return 0;
}
if (sizeAuditRequested)
{
RunImageAuditAndTrim(options);
return 0;
}
if (volumeOpsRequested)
{
RunVolumeOperations(options);
return 0;
}
PrepareWinFspRuntime(options.DebugLogFile);
using (MountSession session = Mount(options))
{
PrintMounts(options.ImagePath, session);
WaitForCtrlC();
}
return 0;
}
catch (CommandLineUsageException ex)
{
if (!string.IsNullOrWhiteSpace(ex.Message))
{
Console.Error.WriteLine("Error: {0}", ex.Message);
Console.Error.WriteLine();
}
PrintUsage();
return 2;
}
catch (WinFspRuntimeException ex)
{
Console.Error.WriteLine("Error: {0}", ex.Message);
return 2;
}
catch (Exception ex)
{
string winFspMessage;
if (TryFormatWinFspInteropError(ex, out winFspMessage))
{
Console.Error.WriteLine("Error: {0}", winFspMessage);
return 2;
}
Console.Error.WriteLine("Error: {0}", ex.Message);
return 1;
}
}
static MountOptions ParseArgs(string[] args)
{
var options = new MountOptions();
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
if (arg == "-?" || arg == "--help" || arg == "/?")
{
options.ShowHelp = true;
return options;
}
if (!arg.StartsWith("-", StringComparison.Ordinal))
throw new CommandLineUsageException(string.Format("Unknown positional argument '{0}'.", arg));
switch (arg)
{
case "-d":
{
int parsed;
if (!int.TryParse(NextArg(args, ref i, arg), out parsed))
throw new CommandLineUsageException("Debug flags must be an integer.");
options.DebugFlags = unchecked((uint)parsed);
break;
}
case "-D": options.DebugLogFile = NextArg(args, ref i, arg); break;
case "-i": options.ImagePath = NextArg(args, ref i, arg); break;
case "-m": options.MountPoint = NextArg(args, ref i, arg); break;
case "-p":
case "--partition": options.PartitionSelector = NextArg(args, ref i, arg); break;
case "-a":
case "--all-partitions": options.MountAllPartitions = true; break;
case "-l":
case "--list-partitions": options.ListPartitions = true; break;
case "--mount-root": options.MountRoot = NextArg(args, ref i, arg); break;
case "--diskpart": options.DiskpartAssist = true; break;
case "--read-only": options.Features.ReadOnly = true; break;
case "--recovery-mode": options.Features.RecoveryMode = true; break;
case "--f-takes-all-override": options.Features.FTakesAllOverride = true; break;
case "--disable-disk-cache": options.Features.DisableDiskCache = true; break;
case "--ignore-security-sector": options.Features.IgnoreSecuritySector = true; break;
case "--restore-partition-table": options.Features.RestorePartitionTable = true; break;
case "--metadata-scan": options.ScanMetadata = true; break;
case "--metadata-scan-limit": options.MetadataScanLimitBytes = ParseByteCountOption(NextArg(args, ref i, arg), arg); break;
case "--recover-deleted": options.RecoverDeletedFiles = true; break;
case "--carve-files": options.CarveFiles = true; break;
case "--carve-deep": options.CarveDeepScan = true; break;
case "--recovery-output": options.RecoveryOutputPath = NextArg(args, ref i, arg); break;
case "--carve-interval": options.CarveInterval = ParseCarveInterval(NextArg(args, ref i, arg)); break;
case "--analyze-image-size": options.AnalyzeImageSize = true; break;
case "--trim-image": options.TrimImageOutputPath = NextArg(args, ref i, arg); break;
case "--trim-block-mib":
{
int parsed;
if (!int.TryParse(NextArg(args, ref i, arg), out parsed))
throw new CommandLineUsageException("Trim block size must be an integer number of MiB.");
options.TrimBlockMiB = parsed;
break;
}
case "--volume-offset":
options.VolumeOffset = ParseLongOption(NextArg(args, ref i, arg), "--volume-offset");
break;
case "--volume-length":
options.VolumeLength = ParseLongOption(NextArg(args, ref i, arg), "--volume-length");
break;
case "--volume-stats":
options.VolumeStats = true;
break;
case "--extract-volume":
options.ExtractVolumePath = NextArg(args, ref i, arg);
break;
default: throw new CommandLineUsageException(string.Format("Unknown option '{0}'.", arg));
}
}
if (string.IsNullOrWhiteSpace(options.ImagePath))
throw new CommandLineUsageException("Image path is required.");
if (options.MountAllPartitions && !string.IsNullOrWhiteSpace(options.PartitionSelector))
throw new CommandLineUsageException("Use either --all-partitions or --partition.");
if (options.CarveDeepScan)
options.CarveFiles = true;
if (options.RecoverDeletedFiles)
options.ScanMetadata = true;
if (options.MetadataScanLimitBytes > 0 && !options.ScanMetadata && !options.RecoverDeletedFiles && !options.CarveFiles)
throw new CommandLineUsageException("--metadata-scan-limit requires --metadata-scan, --recover-deleted, or --carve-files.");
if (!string.IsNullOrWhiteSpace(options.TrimImageOutputPath))
options.AnalyzeImageSize = true;
if (options.TrimBlockMiB < 1 || options.TrimBlockMiB > 256)
throw new CommandLineUsageException("--trim-block-mib must be between 1 and 256.");
if (!string.IsNullOrWhiteSpace(options.TrimImageOutputPath) &&
string.Equals(Path.GetFullPath(options.TrimImageOutputPath), Path.GetFullPath(options.ImagePath), StringComparison.OrdinalIgnoreCase))
throw new CommandLineUsageException("--trim-image output path must be different from input image path.");
if (options.VolumeLength < 0)
throw new CommandLineUsageException("--volume-length must be non-negative.");
if (options.VolumeLength > 0 && options.VolumeOffset < 0)
throw new CommandLineUsageException("--volume-length requires --volume-offset.");
if (!string.IsNullOrWhiteSpace(options.ExtractVolumePath) &&
string.Equals(Path.GetFullPath(options.ExtractVolumePath), Path.GetFullPath(options.ImagePath), StringComparison.OrdinalIgnoreCase))
throw new CommandLineUsageException("--extract-volume output path must be different from input image path.");
bool recoveryRequested = XtafRecoveryEngine.IsRecoveryRequested(options);
bool sizeAuditRequested = options.AnalyzeImageSize || !string.IsNullOrWhiteSpace(options.TrimImageOutputPath);
bool volumeOpsRequested = options.VolumeStats || !string.IsNullOrWhiteSpace(options.ExtractVolumePath);
bool assistOnly = options.DiskpartAssist &&
!options.ListPartitions &&
!options.MountAllPartitions &&
string.IsNullOrWhiteSpace(options.PartitionSelector) &&
string.IsNullOrWhiteSpace(options.MountPoint) &&
string.IsNullOrWhiteSpace(options.MountRoot);
if (!options.ListPartitions && !assistOnly && !recoveryRequested && !sizeAuditRequested && !volumeOpsRequested)
{
if (options.MountAllPartitions && string.IsNullOrWhiteSpace(options.MountPoint) && string.IsNullOrWhiteSpace(options.MountRoot))
options.MountPoint = "*";
if (!options.MountAllPartitions && string.IsNullOrWhiteSpace(options.MountPoint))
throw new CommandLineUsageException("Mount point is required.");
}
if (!string.IsNullOrWhiteSpace(options.MountRoot) && !options.MountAllPartitions)
throw new CommandLineUsageException("--mount-root requires --all-partitions.");
return options;
}
static string NextArg(string[] args, ref int index, string option)
{
if (index + 1 >= args.Length)
throw new CommandLineUsageException(string.Format("Missing value for {0}.", option));
index++;
return args[index];
}
static RecoveryCarveInterval ParseCarveInterval(string token)
{
if (string.IsNullOrWhiteSpace(token))
throw new CommandLineUsageException("Carve interval value is required.");
switch (token.Trim().ToLowerInvariant())
{
case "byte":
case "1":
return RecoveryCarveInterval.Byte;
case "align":
case "0x10":
case "16":
return RecoveryCarveInterval.Align;
case "sector":
case "0x200":
case "512":
return RecoveryCarveInterval.Sector;
case "page":
case "0x1000":
case "4096":
return RecoveryCarveInterval.Page;
case "cluster":
case "0x4000":
case "16384":
return RecoveryCarveInterval.Cluster;
default:
throw new CommandLineUsageException("Invalid carve interval. Use byte|align|sector|page|cluster.");
}
}
static long ParseLongOption(string token, string option)
{
if (string.IsNullOrWhiteSpace(token))
throw new CommandLineUsageException(string.Format("Missing value for {0}.", option));
string trimmed = token.Trim();
long value;
if (trimmed.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
if (!long.TryParse(trimmed.Substring(2), System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out value))
throw new CommandLineUsageException(string.Format("Invalid hex value for {0}.", option));
}
else
{
if (!long.TryParse(trimmed, out value))
throw new CommandLineUsageException(string.Format("Invalid numeric value for {0}.", option));
}
if (value < 0)
throw new CommandLineUsageException(string.Format("{0} must be non-negative.", option));
return value;
}
static long ParseByteCountOption(string token, string option)
{
if (string.IsNullOrWhiteSpace(token))
throw new CommandLineUsageException(string.Format("Missing value for {0}.", option));
string trimmed = token.Trim();
int suffixStart = trimmed.Length;
while (suffixStart > 0 && char.IsLetter(trimmed[suffixStart - 1]))
suffixStart--;
string number = trimmed.Substring(0, suffixStart).Trim();
string suffix = trimmed.Substring(suffixStart).Trim().ToLowerInvariant();
if (string.IsNullOrWhiteSpace(number))
throw new CommandLineUsageException(string.Format("Invalid byte count for {0}.", option));
long multiplier;
switch (suffix)
{
case "":
case "b":
case "byte":
case "bytes":
multiplier = 1;
break;
case "k":
case "kb":
case "kib":
multiplier = 1024L;
break;
case "m":
case "mb":
case "mib":
multiplier = 1024L * 1024L;
break;
case "g":
case "gb":
case "gib":
multiplier = 1024L * 1024L * 1024L;
break;
default:
throw new CommandLineUsageException(string.Format("Invalid byte-count suffix for {0}. Use bytes, KiB, MiB, or GiB.", option));
}
long value;
if (number.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
if (!long.TryParse(number.Substring(2), System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out value))
throw new CommandLineUsageException(string.Format("Invalid hex value for {0}.", option));
}
else
{
if (!long.TryParse(number, out value))
throw new CommandLineUsageException(string.Format("Invalid numeric value for {0}.", option));
}
if (value <= 0)
throw new CommandLineUsageException(string.Format("{0} must be positive.", option));
if (value > long.MaxValue / multiplier)
throw new CommandLineUsageException(string.Format("{0} is too large.", option));
return value * multiplier;
}
static void RunImageAuditAndTrim(MountOptions options)
{
int blockBytes = options.TrimBlockMiB * 1024 * 1024;
ImageSizeAuditResult audit = AnalyzeImageSize(options.ImagePath, blockBytes);
PrintImageSizeAudit(options.ImagePath, audit);
if (string.IsNullOrWhiteSpace(options.TrimImageOutputPath))
return;
if (audit.TrailingZeroBytes <= 0)
{
Console.WriteLine("No trailing-zero bloat detected. Trim output was not created.");
Console.WriteLine();
return;
}
string outputPath = Path.GetFullPath(options.TrimImageOutputPath);
string outputDir = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrWhiteSpace(outputDir))
Directory.CreateDirectory(outputDir);
TrimImageToSize(options.ImagePath, outputPath, audit.SuggestedTrimSize, blockBytes);
Console.WriteLine("Trimmed image written: {0}", outputPath);
Console.WriteLine("Trimmed bytes: {0:N0}", audit.TrailingZeroBytes);
Console.WriteLine();
}
static ImageSizeAuditResult AnalyzeImageSize(string imagePath, int blockSizeBytes)
{
var result = new ImageSizeAuditResult
{
BlockSizeBytes = blockSizeBytes
};
using (var stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1024 * 1024, FileOptions.SequentialScan))
{
result.LogicalSize = stream.Length;
if (result.LogicalSize == 0)
{
result.SuggestedTrimSize = 0;
result.TrailingZeroBytes = 0;
return result;
}
result.TotalBlocks = (result.LogicalSize + blockSizeBytes - 1) / blockSizeBytes;
byte[] buffer = new byte[blockSizeBytes];
long offset = 0;
long blockIndex = 0;
while (offset < result.LogicalSize)
{
int toRead = (int)Math.Min(blockSizeBytes, result.LogicalSize - offset);
if (!ReadFully(stream, buffer, 0, toRead))
throw new IOException("Unexpected end-of-stream while analyzing image size.");
bool allZero = true;
int lastNonZero = -1;
for (int i = 0; i < toRead; i++)
{
if (buffer[i] != 0)
{
allZero = false;
lastNonZero = i;
}
}
if (allZero)
{
result.ZeroBlocks++;
}
else
{
result.LastNonZeroOffset = offset + lastNonZero;
}
blockIndex++;
offset += toRead;
if ((blockIndex % 512) == 0 || offset >= result.LogicalSize)
{
double percent = result.LogicalSize == 0 ? 100.0 : (100.0 * offset / result.LogicalSize);
Console.WriteLine("Size audit progress: {0:N1}% ({1:N0}/{2:N0} bytes)", percent, offset, result.LogicalSize);
}
}
}
result.SuggestedTrimSize = result.LastNonZeroOffset >= 0 ? result.LastNonZeroOffset + 1 : 0;
result.TrailingZeroBytes = Math.Max(0, result.LogicalSize - result.SuggestedTrimSize);
return result;
}
static void PrintImageSizeAudit(string imagePath, ImageSizeAuditResult audit)
{
Console.WriteLine();
Console.WriteLine("Image size audit: {0}", imagePath);
Console.WriteLine("Logical size: {0:N0} bytes ({1:N2} GiB)", audit.LogicalSize, audit.LogicalSize / 1024.0 / 1024.0 / 1024.0);
Console.WriteLine("Block size: {0:N0} bytes ({1} MiB)", audit.BlockSizeBytes, audit.BlockSizeBytes / 1024 / 1024);
Console.WriteLine("Total blocks: {0:N0}", audit.TotalBlocks);
Console.WriteLine("Zero blocks: {0:N0} ({1:N2}%)",
audit.ZeroBlocks,
audit.TotalBlocks == 0 ? 0.0 : (100.0 * audit.ZeroBlocks / audit.TotalBlocks));
Console.WriteLine("Last non-zero: {0}", audit.LastNonZeroOffset >= 0 ? string.Format("0x{0:X}", audit.LastNonZeroOffset) : "none");
Console.WriteLine("Trim candidate: {0:N0} bytes ({1:N2} GiB)",
audit.SuggestedTrimSize,
audit.SuggestedTrimSize / 1024.0 / 1024.0 / 1024.0);
Console.WriteLine("Trailing zeros: {0:N0} bytes ({1:N2} GiB)",
audit.TrailingZeroBytes,
audit.TrailingZeroBytes / 1024.0 / 1024.0 / 1024.0);
Console.WriteLine();
}
static void TrimImageToSize(string sourcePath, string outputPath, long length, int bufferBytes)
{
using (var source = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1024 * 1024, FileOptions.SequentialScan))
using (var output = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024, FileOptions.SequentialScan))
{
byte[] buffer = new byte[Math.Max(1024 * 1024, bufferBytes)];
long remaining = length;
while (remaining > 0)
{
int toRead = (int)Math.Min(buffer.Length, remaining);
int read = source.Read(buffer, 0, toRead);
if (read <= 0)
throw new IOException("Unexpected end-of-stream while trimming image.");
output.Write(buffer, 0, read);
remaining -= read;
}
output.SetLength(length);
}
}
static bool ReadFully(Stream stream, byte[] buffer, int offset, int count)
{
int total = 0;
while (total < count)
{
int read = stream.Read(buffer, offset + total, count - total);
if (read <= 0)
return false;
total += read;
}
return true;
}
static void RunVolumeOperations(MountOptions options)
{
using (Stream stream = OpenImageStream(options.ImagePath, options.Features))
{
List<PartitionCandidate> discovered = DiscoverPartitions(stream, options.Features);
PartitionCandidate target = ResolveVolumeTarget(options, discovered, stream.Length);
if (target == null)
throw new CommandLineUsageException("No volume target was found. Use --volume-offset or --partition.");
long maxLength = Math.Max(0, stream.Length - target.Offset);
if (target.Size <= 0 || target.Size > maxLength)
target.Size = maxLength;
Console.WriteLine();
Console.WriteLine("Volume target:");
Console.WriteLine(" Name: {0}", target.Name);
Console.WriteLine(" Offset: 0x{0:X}", target.Offset);
Console.WriteLine(" Length: 0x{0:X} ({1:N2} GiB)", target.Size, target.Size / 1024.0 / 1024.0 / 1024.0);
PrintVolumeStats(stream, target, options.Features);
if (!string.IsNullOrWhiteSpace(options.ExtractVolumePath))
{
string outputPath = Path.GetFullPath(options.ExtractVolumePath);
string outputDir = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrWhiteSpace(outputDir))
Directory.CreateDirectory(outputDir);
ExtractVolume(stream, target, outputPath);
}
Console.WriteLine();
}
}
static PartitionCandidate ResolveVolumeTarget(MountOptions options, List<PartitionCandidate> discovered, long streamLength)
{
if (options.VolumeOffset >= 0)
{
if (options.VolumeOffset >= streamLength)
throw new CommandLineUsageException("--volume-offset is outside the image.");
long size = options.VolumeLength > 0 ? options.VolumeLength : (streamLength - options.VolumeOffset);
if (size < 0)
size = 0;
return new PartitionCandidate
{
Index = 1,
Key = "custom-volume",
Name = "Custom Volume",
Offset = options.VolumeOffset,
Size = size,
IsRecovered = false
};
}
if (!string.IsNullOrWhiteSpace(options.PartitionSelector))
return ResolvePartitionSelector(options.PartitionSelector, discovered);
if (discovered != null && discovered.Count > 0)
return ChooseDefaultPartition(discovered);
return null;
}
static void PrintVolumeStats(Stream stream, PartitionCandidate target, MountFeatureOptions features)
{
FatxRecoveryPartitionContext context;
if (!FatxRecoveryPartitionContext.TryCreate(stream, target, features, out context))
{
Console.WriteLine(" FATX stats: unavailable (target range is not recognized as FATX).");
return;
}
long maxClusters = context.MaxScannableClusters;
long freeClusters = 0;
for (uint cluster = 1; cluster <= maxClusters; cluster++)
if (context.ChainMap[cluster] == FatxFileSystem.kClusterFree)
freeClusters++;
long usedClusters = Math.Max(0, maxClusters - freeClusters);
long totalBytes = maxClusters * context.ClusterSize;
long freeBytes = freeClusters * context.ClusterSize;
long usedBytes = usedClusters * context.ClusterSize;
Console.WriteLine(" FATX stats:");
Console.WriteLine(" Cluster size: {0:N0} bytes", context.ClusterSize);
Console.WriteLine(" Total space: {0:N2} GiB", totalBytes / 1024.0 / 1024.0 / 1024.0);
Console.WriteLine(" Used space: {0:N2} GiB", usedBytes / 1024.0 / 1024.0 / 1024.0);
Console.WriteLine(" Free space: {0:N2} GiB", freeBytes / 1024.0 / 1024.0 / 1024.0);
}
static void ExtractVolume(Stream stream, PartitionCandidate target, string outputPath)
{
Console.WriteLine(" Extracting volume to: {0}", outputPath);
const int BufferSize = 8 * 1024 * 1024;
byte[] buffer = new byte[BufferSize];
stream.Position = target.Offset;
long remaining = target.Size;
long copied = 0;
using (var output = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None, BufferSize, FileOptions.SequentialScan))
{
while (remaining > 0)
{
int toRead = (int)Math.Min(BufferSize, remaining);
int read = stream.Read(buffer, 0, toRead);
if (read <= 0)
throw new IOException("Unexpected end-of-stream while extracting volume.");
output.Write(buffer, 0, read);
remaining -= read;
copied += read;
if ((copied % (512L * 1024 * 1024)) == 0 || remaining == 0)
{
double pct = target.Size == 0 ? 100.0 : (100.0 * copied / target.Size);
Console.WriteLine(" Extract progress: {0:N1}% ({1:N0}/{2:N0} bytes)", pct, copied, target.Size);
}
}
}
Console.WriteLine(" Extract complete: {0:N0} bytes", target.Size);
}
static Assembly ResolveWinFspAssembly(object sender, ResolveEventArgs args)
{
AssemblyName requested;
try
{
requested = new AssemblyName(args.Name);
}
catch
{
return null;
}
if (!string.Equals(requested.Name, "winfsp-msil", StringComparison.OrdinalIgnoreCase))
return null;
string installedMsil = FindInstalledWinFspMsilPath();
if (string.IsNullOrWhiteSpace(installedMsil))
return null;
try
{
return Assembly.LoadFrom(installedMsil);
}
catch
{
return null;
}
}
static void PrepareWinFspRuntime(string debugLogFile)
{
PreflightWinFspRuntime();
ConfigureWinFspDebugLog(debugLogFile);
}
static void PreflightWinFspRuntime()
{
string appLocalMsil = GetAppLocalWinFspMsilPath();
string installedMsil = FindInstalledWinFspMsilPath();
if (string.IsNullOrWhiteSpace(installedMsil))
{
throw new WinFspRuntimeException(
"WinFsp runtime was not found. Install or repair WinFsp 2.x, then run Xtaf again. " +
"Xtaf loads WinFsp's installed winfsp-msil.dll so it matches the installed driver. " +
DescribeWinFspInteropState());
}
if (File.Exists(appLocalMsil) && WinFspMsilMajorMinorDiffer(appLocalMsil, installedMsil))
{
throw new WinFspRuntimeException(
"WinFsp DLL version mismatch before mount. Remove app-local winfsp-msil.dll from the Xtaf build/release folder, or rebuild so Xtaf loads the WinFsp-installed MSIL. " +
DescribeWinFspInteropState());
}
}
static void ConfigureWinFspDebugLog(string debugLogFile)
{
if (string.IsNullOrEmpty(debugLogFile))
return;
try
{
if (FileSystemHost.SetDebugLogFile(debugLogFile) < 0)
throw new CommandLineUsageException("Could not open debug log file.");
}
catch (CommandLineUsageException)
{
throw;
}
catch (Exception ex)
{
string message;
if (TryFormatWinFspInteropError(ex, out message))
throw new WinFspRuntimeException(message, ex);
throw;
}
}
static bool TryFormatWinFspInteropError(Exception ex, out string message)
{
Exception cause = FindWinFspInteropCause(ex);
if (cause == null)
{
message = null;
return false;
}
if (cause is TypeLoadException && ContainsIgnoreCase(cause.Message, "incorrect dll version"))
{
message = "WinFsp DLL version mismatch: " + cause.Message +
". Use the winfsp-msil.dll installed with WinFsp; remove app-local copies from the Xtaf build/release folder. " +
DescribeWinFspInteropState();
return true;
}
if (cause is DllNotFoundException)
{
message = "WinFsp native runtime could not be loaded: " + cause.Message +
". Install or repair WinFsp. " + DescribeWinFspInteropState();
return true;
}
if (cause is EntryPointNotFoundException)
{
message = "WinFsp native runtime is missing an expected entry point: " + cause.Message +
". Install or repair the matching WinFsp runtime and MSIL files. " + DescribeWinFspInteropState();
return true;
}
if (cause is FileLoadException && ContainsIgnoreCase(cause.Message, "manifest definition does not match"))
{
message = "WinFsp .NET interop assembly version mismatch: " + cause.Message +
". Use the winfsp-msil.dll installed with WinFsp; remove app-local copies from the Xtaf build/release folder. " +
DescribeWinFspInteropState();
return true;
}
message = "WinFsp .NET interop assembly could not be loaded: " + cause.Message +
". Install or repair WinFsp, then rebuild/run Xtaf with the matching installed MSIL. " +
DescribeWinFspInteropState();
return true;
}
static Exception FindWinFspInteropCause(Exception ex)
{
for (Exception current = ex; current != null; current = current.InnerException)
{
string text = current.Message ?? string.Empty;
if (current is TypeLoadException && ContainsIgnoreCase(text, "incorrect dll version"))
return current;
if (current is DllNotFoundException && ContainsIgnoreCase(text, "winfsp"))
return current;
if (current is EntryPointNotFoundException && ContainsIgnoreCase(text, "Fsp"))
return current;
if ((current is FileNotFoundException || current is FileLoadException) && ContainsIgnoreCase(text, "winfsp-msil"))
return current;
if (current is TypeInitializationException && ContainsIgnoreCase(text, "Fsp.Interop.Api") && current.InnerException == null)
return current;
}
return null;
}
static bool ContainsIgnoreCase(string value, string search)
{
return value != null && value.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0;
}
static bool WinFspMsilMajorMinorDiffer(string leftPath, string rightPath)
{
try
{
FileVersionInfo left = FileVersionInfo.GetVersionInfo(leftPath);
FileVersionInfo right = FileVersionInfo.GetVersionInfo(rightPath);
return left.FileMajorPart != right.FileMajorPart || left.FileMinorPart != right.FileMinorPart;
}
catch
{
return false;
}
}
static string DescribeWinFspInteropState()
{
return "App-local winfsp-msil: " + DescribeWinFspMsilFile(GetAppLocalWinFspMsilPath()) +
"; installed winfsp-msil: " + DescribeWinFspMsilFile(FindInstalledWinFspMsilPath()) + ".";
}
static string DescribeWinFspMsilFile(string path)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return "not found";
try
{
FileVersionInfo version = FileVersionInfo.GetVersionInfo(path);
AssemblyName assemblyName = AssemblyName.GetAssemblyName(path);
return path + " (file " + version.FileVersion + ", assembly " + assemblyName.Version + ")";
}
catch
{
return path;
}
}
static string GetAppLocalWinFspMsilPath()
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "winfsp-msil.dll");
}
static string FindInstalledWinFspMsilPath()
{
var candidates = new List<string>();
foreach (string installDir in GetWinFspInstallDirectories())
{
AddWinFspMsilCandidate(candidates, Path.Combine(Path.Combine(installDir, "bin"), "winfsp-msil.dll"));
AddWinFspMsilCandidate(candidates, Path.Combine(installDir, "winfsp-msil.dll"));
AddWinFspSxsMsilCandidates(candidates, Path.Combine(installDir, "SxS"));
}
foreach (string sxsDir in GetWinFspSxsDirectories())
AddWinFspSxsMsilCandidates(candidates, sxsDir);
foreach (string candidate in candidates)
{
if (File.Exists(candidate))
return candidate;
}
return null;
}
static IEnumerable<string> GetWinFspInstallDirectories()
{
var directories = new List<string>();
AddWinFspInstallDirectory(directories, Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\WinFsp", "InstallDir", null) as string);
AddWinFspInstallDirectory(directories, Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WinFsp", "InstallDir", null) as string);
AddWinFspInstallDirectory(directories, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "WinFsp"));
AddWinFspInstallDirectory(directories, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WinFsp"));
AddWinFspInstallDirectory(directories, Path.Combine(Environment.GetEnvironmentVariable("ProgramW6432") ?? string.Empty, "WinFsp"));
AddWinFspInstallDirectory(directories, Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles") ?? string.Empty, "WinFsp"));
return directories;
}
static IEnumerable<string> GetWinFspSxsDirectories()
{
var directories = new List<string>();
AddWinFspInstallDirectory(directories, Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\WinFsp", "SxsDir", null) as string);
AddWinFspInstallDirectory(directories, Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WinFsp", "SxsDir", null) as string);
return directories;
}
static void AddWinFspSxsMsilCandidates(List<string> candidates, string sxsDir)
{
if (string.IsNullOrWhiteSpace(sxsDir) || !Directory.Exists(sxsDir))
return;
AddWinFspMsilCandidate(candidates, Path.Combine(Path.Combine(sxsDir, "bin"), "winfsp-msil.dll"));
AddWinFspMsilCandidate(candidates, Path.Combine(sxsDir, "winfsp-msil.dll"));
string[] children;
try
{
children = Directory.GetDirectories(sxsDir, "sxs.*");
}
catch
{
return;
}
Array.Sort(children, StringComparer.OrdinalIgnoreCase);
for (int i = children.Length - 1; i >= 0; i--)
{
AddWinFspMsilCandidate(candidates, Path.Combine(Path.Combine(children[i], "bin"), "winfsp-msil.dll"));
AddWinFspMsilCandidate(candidates, Path.Combine(children[i], "winfsp-msil.dll"));
}
}