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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
//! The reader: parse an exFAT volume back into a geometry, a directory tree, and file
//! contents.
//!
//! It reads volumes other implementations wrote, not only the ones this crate writes. Both
//! run shapes the format defines are followed through one implementation — a stream that
//! declares `NoFatChain` is read as consecutive clusters and the allocation table is not
//! consulted for it, and a stream that does not is followed through the table — and the two
//! coalesce into one answer, because which of them a file uses is a property of how it was
//! written rather than of what it holds.
//!
//! One shape the format permits is outside what this reads: a volume recording two allocation
//! tables, which is the transaction-safe variant. It is refused by name below the policy
//! threshold, so it is refused under [`ReadPolicy::Lenient`] as well as under `Strict` — see
//! [`ReadError::TexFat`]. Misreading one as an ordinary volume would follow the wrong table on
//! a volume whose whole point is that there are two.
//!
//! # Robustness and strictness
//!
//! Two properties are kept apart. *Robustness* is always on: every on-disk field is
//! bounds-checked and every fallible step returns a [`ReadError`] rather than panicking or
//! reading out of range, on any input — including one built to break it.
//!
//! *Conformance strictness* is a policy: a threshold over the [`Severity`] of the
//! [`Anomaly`] a deviation carries. [`ReadPolicy::Strict`], the default, is fatal at any
//! deviation an exFAT volume this crate writes would not carry, so a strict read either
//! yields the filesystem the image describes or names the deviation that stopped it.
//!
//! **A strict read accepts every volume this crate's own writer produces, and every state a
//! conformant driver can leave behind.** The first half is the line the severities are drawn
//! against, and it is what makes the two halves of the family one thing rather than two: a
//! format followed by a strict open is a round trip at every input the writer accepts. The
//! second half is what keeps that from refusing ordinary images — a volume a driver had open
//! and did not put down, and a stream whose written length trails its allocated length, are
//! both states this crate's writer never produces and every driver produces routinely. Each
//! is reported at [`Severity::Cosmetic`], so a strict read of a card someone pulled out of a
//! reader still succeeds and still says what it found.
//!
//! [`ReadPolicy::Lenient`] moves the threshold above every severity, so nothing is fatal. A
//! whole-volume [`scan`](Reader::scan) checks both boot regions, the allocation table's
//! reserved entries, the three residents of the cluster heap, every directory entry set, and
//! every cluster the tree reaches against the allocation bitmap — including the clusters the
//! bitmap says are in use and nothing reaches — collecting each deviation as an [`Anomaly`]
//! into a [`ScanReport`] instead of stopping at the first.
//!
//! # The volume's own case folding
//!
//! exFAT compares names case-insensitively, and what that means is a mapping the volume
//! carries in its cluster heap rather than a property of Unicode. So the table is read at
//! open, its checksum verified, its run compression decoded, and every lookup and every
//! `NameHash` check goes through it. A reader that folded through its own copy would resolve
//! names a driver does not and miss names a driver finds.
//!
//! # What an exFAT volume does not tell you
//!
//! There is no owner, no permission bits beyond a read-only flag, no symbolic link, no second
//! name for a file, and no extended attribute. Each is filled from the caller's [`Synthesis`]
//! on the extraction surface and named there.
//!
//! The handle opens over any [`Read`] + [`Seek`] source at an arbitrary byte offset, so it
//! reads a volume inside a partitioned disk image as readily as a bare one.
use std::io::{Read, Seek, SeekFrom, Write};
use std::ops::ControlFlow;
use crate::bytes::{get_u16, get_u32, get_u64};
use crate::fidelity::Synthesis;
use crate::finding::{Family, Finding, Findings, Severity};
use crate::io::{Bounded, offset_of, read_exact_at};
use crate::path::{is_hostile_component, is_reserved_name_char};
use crate::policy::{Limits, MAX_PATH, OpenOptions, ReadPolicy};
use crate::time::Timestamp;
use crate::tree::{Attributes, Bound, Child, FsTree, NodeKind, TreeEntry, TreeError, Usage};
use super::geometry::{ExfatLayout, FIRST_CLUSTER, layout_from_boot};
use super::model::MAX_DIRECTORY_BYTES;
use super::ondisk::{
AllocationBitmapEntry, BAD_CLUSTER, BITMAP_IDENTIFIER, BOOT_REGION_SECTORS, CHECKSUM_SECTOR,
DIR_ENTRY_SIZE, EXTENDED_BOOT_FIRST_SECTOR, EXTENDED_BOOT_SECTORS, EXTENDED_BOOT_SIGNATURE,
EntryType, FAT_ENTRY_MEDIA, FAT_ENTRY_RESERVED, FILE_SYSTEM_MINOR_REVISION, FileAttributes,
FileEntry, FileNameEntry, MAIN_BOOT_REGION_SECTOR, MAX_LABEL_UNITS, MainBootSector,
NAME_UNITS_PER_ENTRY, PERCENT_IN_USE_MAX, PERCENT_IN_USE_UNKNOWN, ParseError,
SECONDARY_ALLOCATION_POSSIBLE, SECONDARY_NO_FAT_CHAIN, StreamExtensionEntry, UpcaseTable,
UpcaseTableEntry, VOLUME_FLAG_MEDIA_FAILURE, VOLUME_FLAG_VOLUME_DIRTY, VolumeLabelEntry,
boot_checksum, checksum_sector_value, entry_set_checksum, extended_boot_signature, name_hash,
percent_in_use, unpack_timestamp, upcase_checksum, utc_offset_minutes,
};
/// The most bytes of an up-case table this reader loads.
///
/// A table maps the Basic Multilingual Plane and nothing beyond it, so 65536 units — 131072
/// bytes — is every mapping one could state, and the run-compressed form every implementation
/// writes is a twentieth of that. A declared length past this is not a table length, and
/// loading it would be an allocation an image chose.
const MAX_UPCASE_BYTES: u64 = 2 * 0x1_0000;
/// The subsystem a deviation was found in.
///
/// exFAT has five, and they are neither ext's nor FAT's: there is no superblock and no group
/// descriptor, and the two things FAT keeps in one allocation table are two structures here —
/// the table says what chains where and the bitmap says what is in use, and a volume can be
/// wrong about either alone.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum Category {
/// A boot region — the Main Boot Sector, the sectors behind it, or its checksum.
BootRegion,
/// The allocation table, or a chain it records.
AllocationTable,
/// The allocation bitmap, or the allocation it records.
AllocationBitmap,
/// The up-case table, or the entry describing it.
UpcaseTable,
/// A directory, an entry set in it, or a name one carries.
Directory,
/// The source the filesystem is read from, rather than the filesystem: a read the
/// source failed for a reason other than ending. A scan holds these apart from its
/// findings, as [`source_failures`](crate::ScanReport::source_failures).
Source,
}
impl Category {
/// The lowercase name of this subsystem, for a rendered report.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Category::BootRegion => "boot region",
Category::AllocationTable => "allocation table",
Category::AllocationBitmap => "allocation bitmap",
Category::UpcaseTable => "up-case table",
Category::Directory => "directory",
Category::Source => "source",
}
}
}
crate::naming::serialize_as_name!(Category);
/// Where in the volume a deviation sits. Every field is optional: a deviation carries only
/// the coordinates that locate it.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Location {
/// Sector number within the volume, when the deviation is sector-addressed. This is what
/// becomes the byte offset a [`Finding`] carries.
///
/// Sixty-four bits wide, unlike the cluster beside it: an exFAT volume's length is
/// recorded in sectors as a 64-bit field, so a sector number is the one coordinate here
/// that a 32-bit value would truncate on a large volume.
pub sector: Option<u64>,
/// Cluster number, when the deviation is cluster-addressed.
pub cluster: Option<u32>,
/// Index of a directory entry within its directory, counting 32-byte slots from zero.
pub entry: Option<u32>,
}
impl Location {
/// This location with any coordinate `other` carries that this one does not.
///
/// A deviation knows where it is in its own terms — a table entry knows its cluster — and
/// the walk that met it knows the rest. Merging rather than replacing is what keeps the
/// more specific of the two.
fn or(self, other: Self) -> Self {
Self {
sector: self.sector.or(other.sector),
cluster: self.cluster.or(other.cluster),
entry: self.entry.or(other.entry),
}
}
/// A location naming the directory entry at `index`, and nothing else.
const fn at_entry(index: u32) -> Self {
Self {
sector: None,
cluster: None,
entry: Some(index),
}
}
/// A location naming `cluster`, and nothing else.
const fn at_cluster(cluster: u32) -> Self {
Self {
sector: None,
cluster: Some(cluster),
entry: None,
}
}
/// A location naming `sector`, and nothing else.
const fn at_sector(sector: u64) -> Self {
Self {
sector: Some(sector),
cluster: None,
entry: None,
}
}
}
/// A typed deviation from what this crate would emit, carrying its severity, the subsystem it
/// was found in, where it sits, and a human description.
///
/// This is exFAT's structured value, and it stays exFAT's: the subsystem is a [`Category`]
/// rather than a word, and the place is a cluster, a sector, and an entry index, because
/// those are what a consumer reasoning about an exFAT volume acts on.
///
/// Rendering goes through [`to_finding`](Self::to_finding), which projects into the crate's
/// [`Finding`] — the frame every family shares and every renderer consumes.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Anomaly {
/// How serious the deviation is.
pub severity: Severity,
/// The subsystem it was found in.
pub category: Category,
/// Where it sits in the volume.
pub location: Location,
/// A human-readable description.
pub detail: String,
}
impl crate::Deviation for Anomaly {
fn severity(&self) -> Severity {
self.severity
}
fn is_source_failure(&self) -> bool {
self.category == Category::Source
}
/// The sector size is the addressing unit an exFAT location is stated in.
fn to_finding(&self, unit: u32) -> Finding {
Anomaly::to_finding(self, unit)
}
}
impl Anomaly {
/// Project this anomaly into the crate's family-agnostic [`Finding`], resolving a
/// sector-addressed location to the byte offset that sector sits at under
/// `bytes_per_sector`.
///
/// The coordinates carry exFAT's own words, outermost first — `cluster`, then `sector`,
/// then `entry` — which is the order a person reads a location in. A cluster number is
/// not converted to an offset, because where it sits depends on the layout rather than on
/// the number alone, so an anomaly located only by one carries no offset.
#[must_use]
pub fn to_finding(&self, bytes_per_sector: u32) -> Finding {
// Destructured exhaustively on purpose: a field added to `Anomaly` is a compile error
// here, which forces a decision about what the projection carries rather than letting
// a new fact about a finding go silently unreported.
let Self {
severity,
category,
location,
detail,
} = self;
let Location {
sector,
cluster,
entry,
} = *location;
crate::finding::project(
*severity,
Family::ExFat,
category.as_str(),
&[
("cluster", cluster.map(u64::from)),
("sector", sector),
("entry", entry.map(u64::from)),
],
// The sector is what addresses bytes. A cluster number does not: where it sits
// depends on the layout rather than on the number alone.
sector,
bytes_per_sector,
detail,
)
}
}
/// A failure reading an exFAT volume.
///
/// The variants divide into three kinds. A few are the source's rather than the image's
/// ([`Io`](Self::Io)) or a caller's bound being reached ([`FileTooLarge`](Self::FileTooLarge),
/// [`WalkTooLarge`](Self::WalkTooLarge)). Most are deviations from what an exFAT volume this
/// crate writes carries, each of which projects to a typed [`Anomaly`] through
/// [`anomaly`](Self::anomaly) — so the same fault is an error under [`ReadPolicy::Strict`] and
/// a collected finding under a scan, described the same way either time. The rest are a
/// caller asking for something that is not there.
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ReadError {
/// The underlying source could not be read or sought.
///
/// Carried as [`TreeError::Io`] describes, which is where the rule this crate records an
/// i/o failure by is written out: the kind beside the message, so a caller tells a
/// truncated image from an environment failure without matching on text.
#[error("i/o error: {message}")]
#[non_exhaustive]
Io {
/// How the underlying [`std::io::Error`] classified itself.
kind: std::io::ErrorKind,
/// The error rendered as text, for a message a person reads.
message: String,
},
/// An on-disk structure could not be recovered from its bytes.
#[error(transparent)]
Parse(#[from] ParseError),
/// The Main Boot Sector does not describe an exFAT volume: a field holds a value no such
/// volume carries, or the fields do not agree with each other.
///
/// This is what detection answers "not ours" to. The reader names what is wrong instead,
/// because a caller who reached the reader has already been told the image is an exFAT
/// volume and needs to know why it is not readable as one.
#[error("the boot sector does not describe an exFAT volume: {detail}")]
#[non_exhaustive]
BadBootSector {
/// Which of the sector's fields does not agree with the others.
detail: String,
},
/// The volume records two allocation tables, which is the transaction-safe variant of the
/// format.
///
/// A second table is not a mirror. It is the other half of a transaction mechanism, and
/// which of the two is live is `VolumeFlags` bit 0 — so a reader that treated the volume
/// as an ordinary one would follow whichever table it picked and be right half the time.
/// Refusing by name is the only answer that does not silently misread it.
#[error("this volume records two allocation tables, which is the transaction-safe variant")]
TexFat,
/// The volume records a count of allocation tables the format does not define.
#[error("a volume with {count} allocation tables is not one the format defines")]
#[non_exhaustive]
FatCount {
/// The count found on disk.
count: u8,
},
/// A boot region's stored checksum is not the checksum of the region's own bytes.
///
/// The checksum covers the region's first eleven sectors, two fields of the first
/// excepted, so a mismatch means those bytes have changed since a formatter wrote them —
/// and every geometry field a reader depends on is among them.
#[error(
"the boot region at sector {sector} checksums to {computed:#010x} and records \
{stored:#010x}"
)]
#[non_exhaustive]
BootChecksumMismatch {
/// The region's first sector: 0 for the main region, 12 for its backup.
sector: u64,
/// The checksum the region's bytes make.
computed: u32,
/// The value its checksum sector records.
stored: u32,
},
/// A boot region's checksum sector does not hold one value repeated for its whole length.
///
/// The repetition is the format's, and a sector whose words disagree is not a checksum
/// with a stale tail — it is a sector this reader cannot say the intended value of.
#[error("the checksum sector of the boot region at sector {sector} does not repeat one value")]
#[non_exhaustive]
BootChecksumSectorSplit {
/// The region's first sector.
sector: u64,
},
/// The backup boot region does not describe the same volume as the main one.
///
/// It exists to be used when the main region cannot be read, so a copy that has drifted is
/// worse than none: it would restore a geometry the volume does not have. The two fields
/// outside the region's checksum are not compared — a mounted driver rewrites those in the
/// main region alone, and a volume in ordinary use has them differing by design.
#[error(
"the backup boot region at sector {sector} does not describe the same volume: {detail}"
)]
#[non_exhaustive]
BackupBootRegionDiffers {
/// Where the backup region begins.
sector: u64,
/// Which field differs.
detail: String,
},
/// The volume records a minor revision of the format this reader does not know.
///
/// The format asks an implementation to honour a minor revision above zero rather than
/// refuse it, so this is a remark: every structure is the one this reader knows, and
/// something in the volume may mean more than it appears to. A *major* revision other
/// than 1 is the refusal, and it is [`BadBootSector`](Self::BadBootSector), raised where
/// the rest of the boot sector is judged.
#[error(
"this volume records minor revision {minor} of the format, which this reader does not know"
)]
#[non_exhaustive]
UnknownMinorRevision {
/// The minor revision found on disk.
minor: u8,
},
/// An extended boot sector does not end with the signature the format requires.
///
/// The region's checksum covers whatever is in the sector, so a region whose eight
/// signatures are all missing and whose checksum agrees with its bytes is self-consistent
/// and still not the region the format defines.
#[error(
"the extended boot sector at sector {sector} ends with {found:#010x} and the format \
requires {expected:#010x}"
)]
#[non_exhaustive]
BadExtendedBootSignature {
/// The sector, counted from the volume's start.
sector: u64,
/// The value found in the sector's last four bytes.
found: u32,
/// [`EXTENDED_BOOT_SIGNATURE`].
expected: u32,
},
/// A structure names a cluster the volume does not have.
#[error("cluster {cluster} is not a cluster this volume has")]
#[non_exhaustive]
ClusterOutOfRange {
/// The cluster named.
cluster: u32,
},
/// A chain reaches a cluster the allocation table marks as one the medium could not be
/// relied on for.
///
/// A bad cluster is not part of any chain: it is a number the format sets aside so that
/// nothing allocates it. A chain reaching one is a chain into storage a driver was told
/// to leave alone, which is why it is named rather than followed.
#[error("the chain reaches cluster {cluster}, which the allocation table marks bad")]
#[non_exhaustive]
BadClusterInChain {
/// The cluster the table marks bad.
cluster: u32,
},
/// A chain's table entry holds a value no chain may contain: free, reserved, or the
/// bad-cluster mark.
#[error("the table entry for cluster {cluster} is {entry:#010x}, which no chain may contain")]
#[non_exhaustive]
BadChainEntry {
/// The cluster whose entry was read.
cluster: u32,
/// The value found there.
entry: u32,
},
/// A chain did not end within the clusters the volume has, so it repeats one.
#[error("the chain from cluster {start} does not end within the volume's {clusters} clusters")]
#[non_exhaustive]
ChainTooLong {
/// The chain's first cluster.
start: u32,
/// Clusters the volume has, which bounds any chain in it.
clusters: u32,
},
/// A stream's allocation ends before the length its entry records.
///
/// A length is a claim about clusters, and one that stops short means the length and the
/// allocation disagree. Handing back a short buffer would report success for a file that
/// is not all there.
#[error("a stream from cluster {start} holds {held} bytes and its entry records {declared}")]
#[non_exhaustive]
StreamTooShort {
/// The stream's first cluster.
start: u32,
/// The length the stream extension records.
declared: u64,
/// Bytes the allocation actually holds.
held: u64,
},
/// A reserved entry of the allocation table does not hold the value the format defines
/// for it.
#[error("table entry {index} is {found:#010x} where the format defines {expected:#010x}")]
#[non_exhaustive]
BadReservedEntry {
/// The entry's index: 0 carries the media descriptor, 1 is reserved.
index: u32,
/// The value found.
found: u32,
/// The value the format defines.
expected: u32,
},
/// The root directory does not describe one of the residents every volume must carry.
///
/// The allocation bitmap and the up-case table are found by reading the root directory and
/// nowhere else, so a volume missing one is a volume in which nothing can be allocated or
/// nothing can be looked up — and a reader that answered with an empty tree would report a
/// working filesystem.
#[error("the root directory describes no {resident}, which every volume carries")]
#[non_exhaustive]
MissingResident {
/// Which resident, in the format's own words.
resident: &'static str,
},
/// The up-case table's bytes are not the mapping its entry advertises.
///
/// The checksum is the only thing standing between "the table this volume folds through"
/// and "whatever bytes are at that cluster", so a mismatch means every name comparison on
/// the volume is being made through a mapping nobody wrote.
#[error("the up-case table checksums to {computed:#010x} and its entry records {stored:#010x}")]
#[non_exhaustive]
UpcaseChecksumMismatch {
/// The checksum the table's bytes make.
computed: u32,
/// The value the describing entry records.
stored: u32,
},
/// The up-case table's entry records a length no mapping of the Basic Multilingual Plane
/// reaches.
#[error("an up-case table of {bytes} bytes is longer than the {limit} a mapping can need")]
#[non_exhaustive]
UpcaseTooLong {
/// The length the describing entry records.
bytes: u64,
/// The most bytes a mapping of the plane occupies.
limit: u64,
},
/// The allocation bitmap is not one bit per cluster.
#[error(
"an allocation bitmap of {bytes} bytes does not hold one bit for each of {clusters} clusters"
)]
#[non_exhaustive]
BitmapWrongSize {
/// The length the describing entry records.
bytes: u64,
/// Clusters the volume has.
clusters: u32,
},
/// A directory entry set's stored checksum is not the checksum of the set's own bytes.
///
/// The checksum covers every entry of the set, which is what makes a half-written one
/// detectable: a set is a file's whole record, and half of one is not a file.
#[error(
"the entry set at entry {index} checksums to {computed:#06x} and records {stored:#06x}"
)]
#[non_exhaustive]
SetChecksumMismatch {
/// The set's first entry index within its directory.
index: u32,
/// The checksum the set's bytes make.
computed: u16,
/// The value the file entry records.
stored: u16,
},
/// A file entry's set does not hold the entries it says it does, or is not followed by
/// them.
///
/// A set is one file entry, one stream extension, and the name entries behind them. A set
/// that ends early, or one whose secondary entries are not marked as secondary, describes
/// a file whose record is incomplete.
#[error("the entry set at entry {index} is not complete: {detail}")]
#[non_exhaustive]
IncompleteEntrySet {
/// The set's first entry index within its directory.
index: u32,
/// What is missing from it.
detail: String,
},
/// An entry marked as continuing a set sits where no set is open.
#[error("entry {index} continues a set that no entry opened")]
#[non_exhaustive]
StraySecondaryEntry {
/// The entry's index within its directory.
index: u32,
},
/// A directory holds an entry of a type this reader does not recognize and the format does
/// not permit it to ignore.
///
/// The type byte says whether an implementation that does not know an entry may carry on.
/// A *benign* one it does not know is carried through untouched; a *critical* one means it
/// cannot claim to understand the volume, which is what this reports.
#[error("entry {index} is of critical type {entry_type:#04x}, which this reader does not know")]
#[non_exhaustive]
UnknownCriticalEntry {
/// The entry's index within its directory.
index: u32,
/// The type byte found there.
entry_type: u8,
},
/// A name's code units are not well-formed UTF-16: it carries a surrogate with no partner,
/// which stands for no character.
///
/// The name is still read, with each such unit replaced by U+FFFD, so a tree carrying one
/// is still enumerable under a lenient read.
#[error("the name at entry {index} is not well-formed UTF-16")]
#[non_exhaustive]
IllFormedName {
/// The set's first entry index within its directory.
index: u32,
},
/// A name's hash is not the hash of the name behind it.
///
/// The hash is a lookup accelerator: a driver compares it to skip a set without
/// reassembling the name in it. So a wrong one costs no data and makes the file invisible
/// to every driver that trusts it — a failure a reader is uniquely placed to name and no
/// checksum covers, since the set's own checksum is satisfied by a hash and a name that
/// disagree.
#[error(
"the name at entry {index} hashes to {computed:#06x} and its entry records {stored:#06x}"
)]
#[non_exhaustive]
NameHashMismatch {
/// The set's first entry index within its directory.
index: u32,
/// The hash of the up-cased name the set carries.
computed: u16,
/// The hash the stream extension records.
stored: u16,
},
/// An entry's name carries a character the format reserves in a name: a control code or
/// one of `" * / : < > ? \ |` (documented) — the set this crate's writer refuses in a name
/// and in a label.
///
/// The name is still read and, where the policy allows, handed back as it is stored.
#[error("the name at entry {index} carries {code:#06x}, a character the format reserves in it")]
#[non_exhaustive]
ReservedCharacter {
/// The entry set's index within its directory.
index: u32,
/// The character, as a UTF-16 code point.
code: u32,
},
/// Two entry sets of one directory carry names the volume compares as one: equal once
/// folded through its own up-case table, which is how every driver compares a name.
///
/// A lookup reaches the first of the two, and the second cannot be reached by its own
/// name. This crate's writer refuses such a pair.
#[error(
"entry {index} carries a name entry {first} carries too, once folded through the \
volume's up-case table, so a lookup reaches only the first"
)]
#[non_exhaustive]
IndistinguishableNames {
/// The entry set's index within its directory.
index: u32,
/// The index of the earlier set it cannot be told from.
first: u32,
},
/// A directory's written length is not its length, where the format makes the two one
/// number for a directory (documented).
///
/// A directory is read to its length, which is its allocation: every slot it holds is an
/// entry or free, and none is a region nothing was written to. The pinned `fsck.exfat`
/// accepts the pair and reads the directory to its length (observed), so a scan's default
/// verdict agrees with it, and a strict read, which holds the volume to the format,
/// refuses it.
#[error(
"the directory at entry {index} records {valid} bytes written of its {declared}, \
where a directory's two lengths are one"
)]
#[non_exhaustive]
DirectoryValidLength {
/// The entry set's index within its directory.
index: u32,
/// The written length the stream extension records.
valid: u64,
/// The length the stream extension records.
declared: u64,
},
/// A chain the allocation table records runs on past the length of the stream it holds.
///
/// The clusters past the length are allocated and hold nothing the stream reads, and
/// another implementation following the bitmap could hand them out while the chain still
/// runs through them. Each is claimed by the scan all the same, so one another stream
/// also claims is named as cross-linked. FAT's reader holds a chain to its length the
/// same way.
#[error(
"the chain from cluster {start} holds {held} bytes of clusters and its stream records \
{declared}"
)]
#[non_exhaustive]
ChainPastLength {
/// The chain's first cluster.
start: u32,
/// The length the stream records.
declared: u64,
/// The bytes the chain's clusters hold.
held: u64,
},
/// A volume GUID entry carries secondary entries, where the format gives it none
/// (documented).
///
/// They are read as its set all the same, as the generic template for a primary entry
/// says, so none of them is a stray.
#[error(
"the volume GUID entry at entry {index} declares {count} secondary entries, and it has none"
)]
#[non_exhaustive]
VolumeGuidWithSecondaries {
/// The entry's index within the root directory.
index: u32,
/// The secondary count it records.
count: u8,
},
/// An entry's name is one no directory can hold: `.` or `..`, empty, or a name carrying a
/// path separator or a NUL.
///
/// The first two name a directory rather than something inside it, an empty name names
/// nothing, a separator would traverse out of the tree, and a NUL would truncate the path
/// a consumer forms from the name. The field a name arrives in can encode any of them, being
/// UTF-16 of any content; the format reserves a wider set, which
/// [`ReservedCharacter`](Self::ReservedCharacter) reports, and these are the ones no
/// directory can hold whatever its format says, and so the ones never handed back.
///
/// The name itself is not repeated in the message. It is the image's, an image is
/// untrusted input, and a name built to be one a directory cannot hold is equally free to
/// carry the control bytes that would rewrite the line it is printed on.
#[error("the name at entry {index} is one no directory can hold")]
#[non_exhaustive]
HostileName {
/// The set's first entry index within its directory.
index: u32,
},
/// A directory entry set names a directory the tree already reaches by another name, or
/// one of its own ancestors: two sets share the cluster a directory begins at. An exFAT
/// directory has one name, so the volume contradicts itself. A walk never descends into
/// such a directory twice; a strict read refuses the volume for it, and a lenient one
/// passes the repeat over.
#[error(
"a directory entry names the directory at cluster {cluster}, which the tree reaches \
by another name as well"
)]
#[non_exhaustive]
RepeatedDirectory {
/// The first cluster both names lead to.
cluster: u32,
},
/// An entry set carries more name entries than its name needs.
///
/// The secondary count is defined as one plus the entries the name occupies, so a set
/// carrying one the name does not reach into is a set the format does not describe. The
/// name is still the one `NameLength` states — no implementation reads past it — so this
/// is a remark about bytes nothing reads rather than a name in doubt.
#[error("the entry set at entry {index} carries {have} name entries and its name needs {want}")]
#[non_exhaustive]
ExcessNameEntries {
/// Name entries the length the stream extension records occupies.
want: usize,
/// Name entries the set carries.
have: usize,
/// The set's first entry index within its directory.
index: u32,
},
/// A volume label entry sits somewhere other than the root directory, where it is the one
/// place the format defines for it.
#[error("a {entry_type} entry sits at entry {index} of a directory that is not the root")]
#[non_exhaustive]
MisplacedRootEntry {
/// The entry's index within its directory.
index: u32,
/// What kind of entry it is, in the format's own words.
entry_type: &'static str,
},
/// The root directory carries a second entry of a kind the format defines one of.
///
/// There is one allocation bitmap, one up-case table and one volume label on a volume
/// outside the transaction-safe variant, which this reader refuses by name anyway. A
/// reader takes the first of each and steps over the rest, so a second is storage nothing
/// reads and a second answer to a question with one.
#[error("a second {entry_type} entry sits at entry {index} of the root directory")]
#[non_exhaustive]
DuplicateRootEntry {
/// The entry's index within the root directory.
index: u32,
/// What kind of entry it is, in the format's own words.
entry_type: &'static str,
},
/// The volume label entry records more characters than the field holds.
///
/// `CharacterCount` runs 0 to 11 and the field is eleven code units wide, so a larger
/// count names units that are not there. Reading the field to its end is the only thing a
/// reader can do with one, and what lies past the label is the field's zero padding.
#[error("a volume label of {count} characters is longer than the {limit} the field holds")]
#[non_exhaustive]
LabelTooLong {
/// The count found on disk.
count: u8,
/// [`MAX_LABEL_UNITS`].
limit: usize,
},
/// The volume label carries `U+0000`, which is what the field's padding is.
///
/// A label holding one is a label every implementation that reads the field as terminated
/// rather than counted would read differently, so this crate's writer refuses to produce
/// one and this answers [`volume_label`](Reader::volume_label) with `None` rather than
/// handing back a name that is not one.
#[error("the volume label carries a NUL, which is what the field's padding is")]
LabelNulUnit,
/// The volume label carries a character a name may not hold.
///
/// A label reserves the characters a file name does: the control codes and the nine a
/// path or a pattern gives a meaning to.
#[error("the volume label carries {ch:?}, which a label may not hold")]
#[non_exhaustive]
LabelForbiddenCharacter {
/// The first such character.
ch: char,
},
/// The allocation bitmap's entry names itself the second bitmap, on a volume with one
/// allocation table and so one bitmap.
#[error(
"the allocation bitmap's entry names itself the second bitmap, and the volume has one \
allocation table"
)]
SecondBitmap,
/// The allocation bitmap's entry sets flag bits the format reserves.
#[error("the allocation bitmap's entry sets reserved flag bits {bits:#04x}")]
#[non_exhaustive]
BitmapReservedFlags {
/// The reserved bits that are set.
bits: u8,
},
/// The up-case table maps one of the 128 characters whose mapping the format fixes to
/// something else.
///
/// A volume may fold every other character its own way. These 128 fold as the format
/// says — `a` through `z` to `A` through `Z`, and every other one to itself — on every
/// exFAT volume, which is what makes an ASCII name compare alike everywhere.
#[error(
"the up-case table maps U+{character:04X} to U+{maps_to:04X}, and the format fixes that \
mapping"
)]
#[non_exhaustive]
UpcaseMandatoryMapping {
/// The character.
character: u16,
/// What the table maps it to.
maps_to: u16,
},
/// A directory holds entries after the one that marks its end, which no reader will reach.
#[error("directory entry {index} follows the end marker and no reader reaches it")]
#[non_exhaustive]
EntriesAfterEnd {
/// The index of the first entry past the marker.
index: u32,
},
/// A directory's entry records no allocation, so it holds not even the byte that ends it.
#[error("the directory at entry {index} records no clusters, so it holds no entries at all")]
#[non_exhaustive]
DirectoryWithoutAllocation {
/// The set's first entry index within its parent.
index: u32,
},
/// A stream records a length and no first cluster.
///
/// The format states the constraint in both directions: a first cluster of zero means the
/// stream owns nothing, and the only length a stream owning nothing has is zero. An entry
/// claiming bytes it has nowhere to keep describes a file whose contents no read can
/// reach, and the incoherence surfaces halfway through an extraction rather than at the
/// entry that carries it.
#[error("the stream at entry {index} records {declared} bytes and no first cluster")]
#[non_exhaustive]
StreamWithoutAllocation {
/// The set's first entry index within its directory.
index: u32,
/// The length the stream extension records.
declared: u64,
},
/// A stream records a first cluster and no length.
///
/// The converse of [`StreamWithoutAllocation`](Self::StreamWithoutAllocation), and the
/// other half of the same constraint: a stream owning nothing has a first cluster of zero,
/// so a stream naming a cluster and claiming no bytes has an allocation nothing reaches.
/// The clusters behind it are spent and hold nothing a read can find, which a scan
/// otherwise meets only at the far end, as clusters in use and reached by no stream.
#[error("the stream at entry {index} records no bytes and a first cluster of {first_cluster}")]
#[non_exhaustive]
AllocationWithoutLength {
/// The set's first entry index within its directory.
index: u32,
/// The cluster the stream extension names.
first_cluster: u32,
},
/// A stream records a length longer than the whole cluster heap.
///
/// exFAT has no holes, so a stream's bytes are its allocation and the heap is what bounds
/// it. The bound refuses no conformant volume — the whole heap is the most anything in it
/// could occupy — and without it a 64-bit field turns any volume into an unbounded source
/// of the zeros an unwritten tail reads as.
#[error("a stream of {declared} bytes is longer than the {limit} bytes the cluster heap holds")]
#[non_exhaustive]
StreamPastHeap {
/// The length the stream extension records.
declared: u64,
/// Bytes the cluster heap holds.
limit: u64,
},
/// A directory records a length past the cap the format puts on one.
///
/// It is the one capacity limit exFAT puts on a tree's shape, and it is what keeps the
/// cost of reading a directory a property of the format rather than of the number the
/// entry happens to carry: every slot the length covers is read, so an unbounded length
/// is an unbounded read per directory.
#[error(
"the directory at entry {index} records {declared} bytes, more than the {limit} the \
format allows one"
)]
#[non_exhaustive]
DirectoryTooLong {
/// The set's first entry index within its parent.
index: u32,
/// The length the stream extension records.
declared: u64,
/// [`MAX_DIRECTORY_BYTES`].
limit: u64,
},
/// A directory's length is not a whole number of clusters.
///
/// The format states a directory's `DataLength` as the entire size of its allocation, and
/// an allocation is clusters — so every conformant volume's is a multiple of the cluster
/// size. A directory is enumerated by the clusters its length covers, so a length that is
/// not one is a number neither honoured nor meaningful.
#[error(
"the directory at entry {index} records {declared} bytes, which is not whole clusters \
of {bytes_per_cluster}"
)]
#[non_exhaustive]
DirectoryLengthNotClusters {
/// The set's first entry index within its parent.
index: u32,
/// The length the stream extension records.
declared: u64,
/// The volume's cluster size.
bytes_per_cluster: u32,
},
/// An entry sets attribute bits the format reserves.
///
/// Eleven of the sixteen are reserved and zero on a conformant volume, bit 3 among them —
/// which is FAT's volume-label attribute, and is reserved here because exFAT gives the
/// label an entry type of its own.
#[error(
"the entry at entry {index} sets attribute bits {bits:#06x}, which the format reserves"
)]
#[non_exhaustive]
ReservedAttributes {
/// The set's first entry index within its directory.
index: u32,
/// The reserved bits that are set.
bits: u16,
},
/// A stream extension does not declare an allocation possible.
///
/// The format requires the flag on every stream extension, whether or not the stream
/// currently addresses a cluster — so a clear one is a secondary entry saying it can
/// address nothing, which no stream extension is.
#[error("the stream at entry {index} does not declare an allocation possible")]
#[non_exhaustive]
AllocationNotPossible {
/// The set's first entry index within its directory.
index: u32,
},
/// A stream extension that addresses no cluster declares its clusters contiguous.
///
/// `NoFatChain` says the allocation table holds no chain for a stream's clusters, which
/// describes an allocation; a stream with none has nothing for it to describe.
#[error(
"the stream at entry {index} addresses no cluster and declares its clusters contiguous"
)]
#[non_exhaustive]
NoFatChainWithoutAllocation {
/// The set's first entry index within its directory.
index: u32,
},
/// One of an entry's three times holds a value the encoding does not define.
///
/// A month of zero, a day of 31 in February, a twenty-fifth hour, or a hundredths byte
/// past 199. A read reports the instant the arithmetic reaches, which is what every driver
/// does; this is the judgment that says the field was never an instant.
#[error("the {field} at entry {index} holds a value the encoding does not define")]
#[non_exhaustive]
MalformedTimestamp {
/// The set's first entry index within its directory.
index: u32,
/// Which of the three times, in the format's own words.
field: &'static str,
},
/// A file records more written bytes than it has bytes.
///
/// The two lengths are a claim about the same allocation, and the written one being the
/// larger is not a state any sequence of writes reaches. A directory is
/// [`DirectoryValidLength`](Self::DirectoryValidLength) for either direction.
#[error("a stream records {valid} bytes written of a length of {declared}")]
#[non_exhaustive]
ValidLengthPastEnd {
/// The written length the stream extension records.
valid: u64,
/// The length the stream extension records.
declared: u64,
},
/// A file's written length trails its length, so the bytes between them were allocated
/// and never written.
///
/// This is a state a driver leaves behind and this crate's writer never produces, since a
/// format writes every byte it allocates. The volume is conformant and the region is
/// defined: a read yields zeros there, as every driver does, rather than whatever the
/// medium last held. A directory's two lengths are one number, and a directory recording
/// them differently is [`DirectoryValidLength`](Self::DirectoryValidLength) instead.
#[error("a stream of {declared} bytes has {valid} of them written; the rest reads as zeros")]
#[non_exhaustive]
ValidLengthTrails {
/// The written length the stream extension records.
valid: u64,
/// The length the stream extension records.
declared: u64,
},
/// A cluster a stream occupies is one the allocation bitmap says is free.
///
/// The bitmap is the volume's record of what is in use, and a stream that occupies a
/// cluster it calls free is a volume in which the next allocation overwrites a file.
#[error("cluster {cluster} is occupied and the allocation bitmap says it is free")]
#[non_exhaustive]
ClusterNotAllocated {
/// The cluster.
cluster: u32,
},
/// Clusters are marked in use in the allocation bitmap and no stream reaches them, so the
/// space is spent and holds nothing a reader can find.
#[error("{count} clusters are marked in use and reached by nothing, the first at {first}")]
#[non_exhaustive]
LostClusters {
/// How many.
count: u64,
/// The lowest-numbered one.
first: u32,
},
/// Two streams both occupy one cluster.
#[error("cluster {cluster} is occupied by more than one stream")]
#[non_exhaustive]
CrossLinkedCluster {
/// The cluster.
cluster: u32,
},
/// `PercentInUse` holds a value the field does not define.
///
/// The field is a percentage, 0 through 100, or `0xFF` for "not known". A value between
/// the two is not a stale percentage — it is a byte that was never one.
#[error(
"the volume records a PercentInUse of {stated}, and the field holds 0 to 100 or 255 \
for not known"
)]
#[non_exhaustive]
PercentInUseOutOfRange {
/// The value found on disk.
stated: u8,
},
/// `PercentInUse` does not say how full the volume actually is.
///
/// The field sits outside the boot region's checksum precisely so a driver can keep it
/// current, so a stale value is a remark about a number nobody is obliged to have updated
/// rather than a fault in the volume.
#[error(
"the volume records that it is {stated}% in use and {in_use} of its {clusters} \
clusters are, which is {actual}%"
)]
#[non_exhaustive]
PercentInUseStale {
/// The value the boot sector records.
stated: u8,
/// Clusters the allocation bitmap marks in use.
in_use: u64,
/// Clusters the volume has.
clusters: u32,
/// The percentage those clusters are.
actual: u8,
},
/// The volume was not cleanly put down by the driver that last had it open.
///
/// The format records this, and it is the format working rather than failing: every field
/// is what a driver is supposed to have written. It is the one condition under which what
/// the metadata says and what the volume contains are allowed to differ.
#[error("{}", crate::finding::NOT_CLEANLY_UNMOUNTED)]
VolumeDirty,
/// The driver that last had the volume open recorded a failure of the underlying medium.
#[error("{}", crate::finding::MEDIUM_FAILURE)]
MediaFailure,
/// A path names nothing in the volume.
#[error("no such path: {}", crate::escape::printable(.path))]
#[non_exhaustive]
NotFound {
/// The path as given.
path: Vec<u8>,
},
/// A path traverses through something that is not a directory.
#[error("not a directory: {}", crate::escape::printable(.path))]
#[non_exhaustive]
NotADirectory {
/// The path as given.
path: Vec<u8>,
},
/// A whole-file read would exceed [`Limits::max_file_bytes`].
#[error("a file of {size} bytes exceeds the {limit}-byte read limit")]
#[non_exhaustive]
FileTooLarge {
/// The length the entry records.
size: u64,
/// The limit in force.
limit: u64,
},
/// A walk reached a name whose path is longer than the longest a walk builds, 4,096
/// bytes, which is Linux's `PATH_MAX`.
///
/// Nothing in the format bounds how deep a tree nests, and a walk's entry cap counts
/// *names* rather than the bytes their paths occupy — so a caterpillar tree of directories
/// each holding one entry naming the next stays under every count while its paths grow by
/// one component each and cost the walk their sum. A walk hands out every name's whole
/// path, so it holds each to this bound.
///
/// The tree is well-formed, so this is a limit rather than damage: the shared surface
/// reports it as [`TreeError::LimitExceeded`] with [`Bound::PathBytes`], and a
/// [`scan`](Reader::scan) reads the tree whole.
#[error("a walked path is longer than the {limit} bytes a walk builds")]
#[non_exhaustive]
PathTooLong {
/// The longest path a walk builds.
limit: usize,
},
/// A whole-tree walk would gather more names than the bounds allow.
#[error("the tree holds more than {limit} names")]
#[non_exhaustive]
WalkTooLarge {
/// The bound that applied.
limit: usize,
},
}
crate::io::io_error!(ReadError);
impl ReadError {
/// How this failure classifies as a deviation from what this crate emits.
///
/// Every variant answers, so a scan describes a fault exactly as a strict read would have.
/// A source that failed a read for a reason other than ending is not the image's, and
/// files under [`Category::Source`], which a scan holds apart from its findings. A
/// caller's own bound is not the image's either, and classifies as
/// [`Severity::Structural`] all the same: from a scan's point of view the volume could not
/// be followed past that point.
#[must_use]
pub fn anomaly(&self) -> Anomaly {
let (severity, category, location) = match self {
ReadError::Io {
kind: std::io::ErrorKind::UnexpectedEof,
..
} => (
Severity::Structural,
Category::BootRegion,
Location::default(),
),
ReadError::Io { .. } => (Severity::Structural, Category::Source, Location::default()),
ReadError::Parse(_) | ReadError::BadBootSector { .. } => (
Severity::Structural,
Category::BootRegion,
Location::at_sector(MAIN_BOOT_REGION_SECTOR),
),
// Not a deviation from the format at all — a volume the format defines and this
// reader does not follow. It is structural because nothing past it can be read.
ReadError::TexFat | ReadError::FatCount { .. } => (
Severity::Structural,
Category::BootRegion,
Location::at_sector(MAIN_BOOT_REGION_SECTOR),
),
// The region's own bytes disagree with the answer stored beside them, which is
// self-inconsistency rather than a matter of form.
ReadError::BootChecksumMismatch { sector, .. }
| ReadError::BootChecksumSectorSplit { sector } => (
Severity::Integrity,
Category::BootRegion,
Location::at_sector(*sector),
),
ReadError::BackupBootRegionDiffers { sector, .. }
| ReadError::BadExtendedBootSignature { sector, .. } => (
Severity::Conformance,
Category::BootRegion,
Location::at_sector(*sector),
),
// The structures are the ones this reader knows — a minor revision says so — and
// something in the volume may mean more than it appears to.
ReadError::UnknownMinorRevision { .. } => (
Severity::Conformance,
Category::BootRegion,
Location::at_sector(MAIN_BOOT_REGION_SECTOR),
),
ReadError::ClusterOutOfRange { cluster }
| ReadError::BadChainEntry { cluster, .. }
| ReadError::BadClusterInChain { cluster }
| ReadError::ChainTooLong { start: cluster, .. }
| ReadError::StreamTooShort { start: cluster, .. } => (
Severity::Structural,
Category::AllocationTable,
Location::at_cluster(*cluster),
),
// No cluster coordinate: the index is a slot of the table, and the heap's
// clusters begin at two — projecting a table slot through the cluster field
// would name heap cluster 0 or 1, which no volume has. The message names the
// slot itself.
ReadError::BadReservedEntry { .. } => (
Severity::Conformance,
Category::AllocationTable,
Location::default(),
),
// A volume with no bitmap or no up-case table is one nothing can allocate in or
// look a name up in, whatever else reads back.
ReadError::MissingResident { .. } => (
Severity::Structural,
Category::Directory,
Location::default(),
),
ReadError::UpcaseChecksumMismatch { .. } => (
Severity::Integrity,
Category::UpcaseTable,
Location::default(),
),
// The table reads and folds; what it folds ASCII to is not what the format says,
// which is a field outside the range the format states for it.
ReadError::UpcaseMandatoryMapping { .. } => (
Severity::Conformance,
Category::UpcaseTable,
Location::default(),
),
// The bitmap reads and is the volume's only one; the entry describing it says
// something the boot sector contradicts, or sets bits nothing defines.
ReadError::SecondBitmap | ReadError::BitmapReservedFlags { .. } => (
Severity::Conformance,
Category::AllocationBitmap,
Location::default(),
),
ReadError::UpcaseTooLong { .. } => (
Severity::Structural,
Category::UpcaseTable,
Location::default(),
),
ReadError::BitmapWrongSize { .. } => (
Severity::Structural,
Category::AllocationBitmap,
Location::default(),
),
ReadError::SetChecksumMismatch { index, .. }
| ReadError::NameHashMismatch { index, .. }
// Two names a lookup cannot tell apart: every set parses, and the directory answers
// one name with two sets.
| ReadError::IndistinguishableNames { index, .. } => (
Severity::Integrity,
Category::Directory,
Location::at_entry(*index),
),
// A name no directory can hold is not a matter of form: no driver creates one and
// this crate's writer refuses one, so an entry carrying it describes a tree that
// does not exist rather than one written to a different convention.
ReadError::HostileName { index }
| ReadError::IncompleteEntrySet { index, .. }
| ReadError::StraySecondaryEntry { index }
| ReadError::DirectoryWithoutAllocation { index }
// A length with no allocation behind it and a length no allocation could hold are
// the same fault at two scales: an entry describing bytes that are not there.
| ReadError::StreamWithoutAllocation { index, .. }
| ReadError::DirectoryTooLong { index, .. } => (
Severity::Structural,
Category::Directory,
Location::at_entry(*index),
),
ReadError::UnknownCriticalEntry { index, .. }
| ReadError::IllFormedName { index }
| ReadError::MisplacedRootEntry { index, .. }
| ReadError::DuplicateRootEntry { index, .. }
| ReadError::ExcessNameEntries { index, .. }
| ReadError::EntriesAfterEnd { index }
// Each is a recovered field outside the range the format states for it. The
// volume reads back whole and a field in it means nothing.
| ReadError::DirectoryLengthNotClusters { index, .. }
| ReadError::ReservedAttributes { index, .. }
| ReadError::AllocationNotPossible { index }
| ReadError::NoFatChainWithoutAllocation { index }
// The clusters are there and the entry does not claim them, so the volume reads
// back whole and the space is spent — a conformance fault rather than a structural
// one, which is the call FAT makes for the same shape.
| ReadError::AllocationWithoutLength { index, .. }
| ReadError::MalformedTimestamp { index, .. }
| ReadError::ReservedCharacter { index, .. }
| ReadError::DirectoryValidLength { index, .. }
| ReadError::VolumeGuidWithSecondaries { index, .. } => (
Severity::Conformance,
Category::Directory,
Location::at_entry(*index),
),
// Clusters allocated past what the stream reads: the space is spent and the volume
// reads back whole, the call FAT makes for the same shape.
ReadError::ChainPastLength { start, .. } => (
Severity::Conformance,
Category::AllocationTable,
Location::at_cluster(*start),
),
ReadError::ValidLengthPastEnd { .. } | ReadError::StreamPastHeap { .. } => (
Severity::Structural,
Category::Directory,
Location::default(),
),
// Both are the root directory's label entry, which is found once at open and has
// no index a later report could carry.
ReadError::LabelTooLong { .. }
| ReadError::LabelNulUnit
| ReadError::LabelForbiddenCharacter { .. } => (
Severity::Conformance,
Category::Directory,
Location::default(),
),
// A written length behind a declared one is what every driver leaves behind and
// this crate's writer never produces. The volume is conformant, so the remark
// says what the region holds and stops no read.
ReadError::ValidLengthTrails { .. } => {
(Severity::Cosmetic, Category::Directory, Location::default())
}
ReadError::ClusterNotAllocated { cluster }
| ReadError::CrossLinkedCluster { cluster } => (
Severity::Integrity,
Category::AllocationBitmap,
Location::at_cluster(*cluster),
),
// Two names for one directory: every set parses, and the sets disagree about the
// tree they make.
ReadError::RepeatedDirectory { cluster } => (
Severity::Integrity,
Category::Directory,
Location::at_cluster(*cluster),
),
ReadError::LostClusters { first, .. } => (
Severity::Conformance,
Category::AllocationBitmap,
Location::at_cluster(*first),
),
// Both are the format correctly recording a state a driver put it in, so the
// volume is well-formed and a strict read carries on. A stale fullness is the
// same shape: the field is outside the region's checksum so a driver may keep it
// current, and nothing obliges one to.
ReadError::VolumeDirty
| ReadError::MediaFailure
| ReadError::PercentInUseStale { .. } => (
Severity::Cosmetic,
Category::BootRegion,
Location::at_sector(MAIN_BOOT_REGION_SECTOR),
),
// A value the field cannot hold is a different remark from one that is merely
// stale: no driver wrote it, whatever it had been doing.
ReadError::PercentInUseOutOfRange { .. } => (
Severity::Conformance,
Category::BootRegion,
Location::at_sector(MAIN_BOOT_REGION_SECTOR),
),
ReadError::NotFound { .. }
| ReadError::NotADirectory { .. }
| ReadError::FileTooLarge { .. }
| ReadError::PathTooLong { .. }
| ReadError::WalkTooLarge { .. } => (
Severity::Structural,
Category::Directory,
Location::default(),
),
};
Anomaly {
severity,
category,
location,
detail: self.to_string(),
}
}
}
/// How a read failure classifies in the crate's family-agnostic frame.
impl From<ReadError> for TreeError {
fn from(err: ReadError) -> Self {
match err {
ReadError::Io { kind, message } => TreeError::Io { kind, message },
ReadError::FileTooLarge { .. } => {
TreeError::limit(Family::ExFat, Bound::FileBytes, &err)
}
ReadError::PathTooLong { .. } => {
TreeError::limit(Family::ExFat, Bound::PathBytes, &err)
}
ReadError::WalkTooLarge { .. } => TreeError::limit(Family::ExFat, Bound::Entries, &err),
// A shape the format defines and this reader does not follow, which is what the
// shared frame calls unsupported rather than malformed.
ReadError::TexFat | ReadError::FatCount { .. } => TreeError::Unsupported {
family: Family::ExFat,
detail: err.to_string(),
},
other => TreeError::Malformed {
family: Family::ExFat,
detail: other.to_string(),
},
}
}
}
/// What a whole-volume [`scan`](Reader::scan) found, in exFAT's own taxonomy.
///
/// This is the crate's [`ScanReport`](crate::ScanReport) over exFAT's [`Anomaly`]: an anomaly
/// names the subsystem as a [`Category`] value and its place as a [`Location`] of cluster,
/// sector, and entry. The addressing unit is the volume's sector size, so a sector-addressed
/// anomaly projects to the byte offset that sector sits at.
pub type ScanReport = crate::ScanReport<Anomaly>;
/// Where a node's bytes are, and how to follow them.
///
/// The domain is closed and the type is exhaustive: an exFAT stream is a run of consecutive
/// clusters the allocation table says nothing about, or a chain through that table, or no
/// allocation at all. There is no fourth, and a fifth arriving *should* break a caller that
/// switches on it.
///
/// Which of the first two a stream uses is declared by its own entry rather than discovered,
/// and the declaration is binding: the format defines the table entries of a consecutive run
/// as meaningless, so a reader that consulted them would follow whatever happened to be there.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Storage {
/// The stream owns no cluster: an empty file, whose entry records a first cluster of zero.
None,
/// A run of consecutive clusters beginning here, declared by `NoFatChain`. How many is the
/// stream's length rounded up to whole clusters.
Contiguous(u32),
/// A chain through the allocation table beginning at this cluster.
Chain(u32),
}
impl Storage {
/// The first cluster, or `None` for a stream with no allocation.
#[must_use]
pub const fn first_cluster(self) -> Option<u32> {
match self {
Storage::None => None,
Storage::Contiguous(first) | Storage::Chain(first) => Some(first),
}
}
}
/// The three times a directory entry records, and the zone each was recorded in.
///
/// The instants are absolute: exFAT stores a local time beside the offset it is local to, so
/// the offset has already been applied here and two volumes written in two zones compare
/// directly. The offsets are kept beside them because "no offset was recorded" is a fact about
/// the volume — a reader has no choice but to read such a time as UTC, and a caller that cares
/// which times were qualified can ask.
///
/// The root directory has none — the format stores no entry for it — which is why
/// [`Node::times`] is an [`Option`] rather than fields that would have to hold something
/// invented.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Times {
/// When the entry was created, to ten milliseconds.
pub create: Timestamp,
/// When it was last accessed. The format gives this field no hundredths, so it is granular
/// to two seconds.
pub access: Timestamp,
/// When it was last written, to ten milliseconds.
pub modify: Timestamp,
/// The offset from UTC recorded beside the creation time, in minutes, or `None` where the
/// entry recorded none.
pub create_offset: Option<i32>,
/// The offset from UTC recorded beside the access time, in minutes, or `None` where the
/// entry recorded none.
pub access_offset: Option<i32>,
/// The offset from UTC recorded beside the modification time, in minutes, or `None` where
/// the entry recorded none.
pub modify_offset: Option<i32>,
}
/// A handle to one node: where its bytes are, what it is, how long it is, and when.
///
/// This is what a walk hands back and what every by-node operation takes. There is no number
/// in it, and deliberately: exFAT has no inodes, so there is nothing that distinguishes a file
/// from a second name for it — the format has no second names.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Node {
/// Where the node's bytes are.
pub storage: Storage,
/// The attribute word the file entry carries.
pub attributes: FileAttributes,
/// How long the stream is, in bytes.
///
/// For the root directory this is the length of the chain the boot sector names, since the
/// format records no entry for it and so no length: the root is as long as its allocation.
pub data_length: u64,
/// How many of those bytes have been written. Equal to
/// [`data_length`](Self::data_length) on a volume this crate wrote, since a format writes
/// every byte it allocates.
pub valid_data_length: u64,
/// The times the entry records, or `None` for the root directory, which has no entry.
///
/// It is also how the root is told from anything else. Every other node here was built
/// from a directory entry and carries that entry's times, so "no entry behind it" is a
/// property the node carries rather than one recomputed from where its bytes are — and a
/// subdirectory whose stream extension names the root's own first cluster is still a
/// subdirectory.
pub times: Option<Times>,
}
impl Node {
/// Whether the node is a directory.
#[must_use]
pub const fn is_dir(&self) -> bool {
self.attributes.contains(FileAttributes::DIRECTORY)
}
}
/// One resolved directory entry: the name it is found under, and a handle to what it points
/// at.
///
/// There is one name and no second: exFAT stores the name whole, in UTF-16, with no shortened
/// legacy form beside it.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Entry {
/// The name the entry is found under, as UTF-8.
///
/// Always a name a directory can hold. An entry whose name is `.` or `..`, is empty, or
/// carries a path separator or a NUL, is [`HostileName`](ReadError::HostileName) rather
/// than an [`Entry`], so a path built by joining this onto its directory's stays inside the
/// tree.
pub name: Vec<u8>,
/// A handle to what the entry points at.
pub node: Node,
}
/// One name a [`walk`](Reader::walk) reached: its path, and a handle to what is there.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct WalkEntry {
/// Absolute path from the volume root, `/`-joined, always beginning with `/`.
pub path: Vec<u8>,
/// A handle to what is at the path.
pub node: Node,
}
/// A read-only handle over an exFAT volume on any [`Read`] + [`Seek`] source.
///
/// The volume may sit at an arbitrary byte offset within the source — a partition inside a
/// whole-disk image — fixed at open time. Reads seek relative to that offset and return owned
/// buffers, so nothing is borrowed from the source between calls.
///
/// It is opened under the crate's own [`OpenOptions`] rather than options of its own: this
/// family takes where the volume begins, how strictly it is read, and what one read may
/// allocate, and nothing else. A knob it does not have would be a knob to keep in step for
/// nothing.
pub struct Reader<R> {
/// The source, ending where the caller's region does.
src: Bounded<R>,
base: u64,
/// The Main Boot Sector as it was parsed.
///
/// Boxed because 390 of its 512 bytes are boot code a reader never looks at, and the
/// reader itself is a variant of the enum the crate's own `open` hands back — where an
/// outsized variant is a cost every caller of every family pays.
boot: Box<MainBootSector>,
layout: ExfatLayout,
policy: ReadPolicy,
limits: Limits,
/// The volume's own case folding, decoded from the table its root directory names.
///
/// Read at open because every name comparison goes through it, and folding through
/// anything else would resolve names a driver does not and miss names a driver finds.
upcase: UpcaseTable,
/// Where the allocation bitmap is, as the root directory's describing entry gives it.
bitmap: Resident,
/// The name in the root directory's volume label entry, or `None` where the volume carries
/// none — which the format records as an entry with a character count of zero.
label: Option<Vec<u8>>,
/// How long the root directory's chain is, in bytes. The format records no entry for the
/// root and so no length, so it is measured once at open rather than at every walk.
root_bytes: u64,
/// The deviations found while opening, kept so a scan reports them without re-deriving the
/// geometry and a lenient caller can see them without one.
///
/// Bounded by [`Limits::max_findings`], as a scan's report is, with reaching the bound
/// recorded: a root directory is the volume's to fill, and how many deviations it holds is
/// its claim rather than this reader's budget.
open_anomalies: Findings<Anomaly>,
/// A one-sector window on the allocation table.
///
/// Following a chain reads one entry at a time and the entries of a chain are usually near
/// each other, so a window turns a walk of a large file from one seek per cluster into one
/// per sector. One sector rather than FAT's two, because an entry here is four bytes at a
/// four-byte-aligned offset and cannot straddle a boundary. The image is read-only, so a
/// cached window can never go stale.
fat_window: Option<(u64, Vec<u8>)>,
/// A one-sector window on the allocation bitmap, for the same reason.
bitmap_window: Option<(u64, Vec<u8>)>,
/// Where the bitmap's own chain walk left off: an index into its stream, and the cluster
/// at that index.
bitmap_at: Option<(u64, u32)>,
/// Where a chain walk left off: the chain's first cluster, the index within it, and the
/// cluster at that index.
///
/// A read at an offset has to skip to the cluster holding it, and skipping from the start
/// every time makes a sequential read of one file quadratic in its length.
chain_cursor: Option<(u32, u64, u32)>,
}
/// One of the cluster heap's format-time residents, as the root directory describes it.
///
/// Both of the two a reader must find — the allocation bitmap and the up-case table — are
/// described by a primary entry carrying a first cluster and a length, and neither has a flags
/// field to declare a consecutive run with, so both are chains through the allocation table.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Resident {
first_cluster: u32,
bytes: u64,
}
/// What a directory parse does with a deviation it meets.
///
/// One parser serves both dispositions, which is what makes a scan describe a fault exactly as
/// the read that stops at it would have.
enum OnDeviation<'a> {
/// An ordinary read: fatal under the policy, and otherwise passed over.
Policy(ReadPolicy),
/// A scan: every deviation collected, none fatal, and every allocation an entry this
/// reader does not interpret describes gathered for the scan to claim.
Collect {
findings: &'a mut Findings<Anomaly>,
allocations: &'a mut Vec<BenignAllocation>,
},
}
/// The allocation a benign entry describes: a primary or secondary entry this reader does not
/// interpret, carrying `AllocationPossible` in the generic template's flags (documented). A
/// scan claims its clusters as it claims a stream's, so they are neither lost nor free to
/// another stream.
struct BenignAllocation {
/// The index, within its directory, of the set the entry belongs to.
index: u32,
/// Where its clusters are.
storage: Storage,
/// The length it records.
bytes: u64,
}
impl OnDeviation<'_> {
/// Record `err`, having happened at `at`. Returns it as an error where the policy in force
/// makes it fatal.
fn record(&mut self, at: Location, err: ReadError) -> Result<(), ReadError> {
match self {
OnDeviation::Policy(policy) => {
if policy.is_fatal(err.anomaly().severity) {
Err(err)
} else {
Ok(())
}
}
OnDeviation::Collect { findings, .. } => {
let mut anomaly = err.anomaly();
anomaly.location = anomaly.location.or(at);
findings.push(anomaly);
Ok(())
}
}
}
/// Hand the scan an allocation a benign entry describes. An ordinary read claims nothing.
fn claim(&mut self, allocation: BenignAllocation) {
if let OnDeviation::Collect { allocations, .. } = self {
allocations.push(allocation);
}
}
}
/// `anomaly` with its detail led by `path`, where there is one: what a finding about a
/// stream's clusters names the stream by.
fn named(mut anomaly: Anomaly, path: &[u8]) -> Anomaly {
if !path.is_empty() {
anomaly.detail = format!("{}: {}", crate::escape::printable(path), anomaly.detail);
}
anomaly
}
/// The allocation one entry in the generic template describes, where its flags say it may
/// address clusters: `AllocationPossible` and `NoFatChain` are bits 0 and 1 of a 16-bit field at
/// byte 4 of a primary entry and of an 8-bit one at byte 1 of a secondary, and both keep
/// `FirstCluster` at byte 20 and `DataLength` at byte 24 (documented).
fn generic_allocation(slot: &[u8], primary: bool) -> Option<(Storage, u64)> {
let flags = if primary {
get_u16(slot, 4).to_le_bytes()[0]
} else {
*slot.get(1)?
};
if flags & SECONDARY_ALLOCATION_POSSIBLE == 0 {
return None;
}
let first = get_u32(slot, 20);
let bytes = get_u64(slot, 24);
if first == 0 || bytes == 0 {
return None;
}
let storage = if flags & SECONDARY_NO_FAT_CHAIN != 0 {
Storage::Contiguous(first)
} else {
Storage::Chain(first)
};
Some((storage, bytes))
}
/// One 32-byte slot of a directory, as it sits on disk.
///
/// The bytes are handed over raw rather than parsed, because a set's checksum is taken over
/// exactly these and a parsed entry has already lost the reserved runs the answer covers.
struct Slot {
bytes: [u8; DIR_ENTRY_SIZE],
/// Which slot of the directory this is, counting from zero.
index: u32,
/// The cluster it sits in.
cluster: u32,
/// The sector it sits in, counted from the volume's start.
sector: u64,
}
impl Slot {
/// The entry's type byte.
const fn entry_type(&self) -> EntryType {
EntryType(self.bytes[0])
}
/// Where this slot is, in the coordinates a deviation carries.
const fn location(&self) -> Location {
Location {
sector: Some(self.sector),
cluster: Some(self.cluster),
entry: Some(self.index),
}
}
}
impl<R: Read + Seek> Reader<R> {
/// Open the exFAT volume at the start of `src` under the default options.
///
/// # Errors
///
/// [`ReadError::BadBootSector`] when the boot sector does not describe an exFAT volume,
/// [`ReadError::TexFat`] for the transaction-safe variant, [`ReadError::Io`] when the
/// source cannot be read, and — under [`ReadPolicy::Strict`] — whichever deviation the
/// boot regions or the root directory's residents carry.
pub fn open(src: R) -> Result<Self, ReadError> {
Self::open_with(src, &OpenOptions::new())
}
/// Open the exFAT volume `src` holds, under `options`.
///
/// The boot sector is validated through the same function detection classifies with, so a
/// volume it does not claim is one this refuses, and what the reader adds is a reason. A
/// volume it claims is one this opens, but for one: a volume recording other than one
/// allocation table is an exFAT volume, which detection names, and this refuses it by name
/// as [`ReadError::TexFat`] or [`ReadError::FatCount`], a variant it does not read.
///
/// Opening reads more than the boot sector, and it has to: the allocation bitmap and the
/// up-case table are found by reading the root directory and nowhere else, and a name
/// cannot be compared or hashed until the table a volume folds through is in hand.
///
/// # Errors
///
/// As [`open`](Self::open).
pub fn open_with(src: R, options: &OpenOptions) -> Result<Self, ReadError> {
let mut src = Bounded::new(src, options.base, options.len);
let end = src.seek(SeekFrom::End(0))?;
let available = end.saturating_sub(options.base);
let sector = read_exact_at(&mut src, options.base, MainBootSector::SIZE)?;
let boot = MainBootSector::read_from(§or)?;
let layout = layout_from_boot(&boot, available).map_err(|d| ReadError::BadBootSector {
detail: d.to_string(),
})?;
// Refused before anything else is read, and below the policy threshold: which of a
// TexFAT volume's two tables is live is a flag rather than a convention, so there is no
// lenient reading of one — only a coin toss dressed as an answer.
match boot.number_of_fats {
1 => {}
2 => return Err(ReadError::TexFat),
count => return Err(ReadError::FatCount { count }),
}
let mut reader = Self {
src,
base: options.base,
boot: Box::new(boot),
layout,
policy: options.policy,
limits: options.limits,
// Replaced below by the volume's own, once the root directory has been read. The
// placeholder folds nothing, so a name resolved before it is replaced is resolved
// case-sensitively — which nothing does, the replacement happening inside `open`.
upcase: UpcaseTable::new(&[]),
bitmap: Resident {
first_cluster: FIRST_CLUSTER,
bytes: 0,
},
label: None,
root_bytes: 0,
open_anomalies: Findings::new(options.limits.max_findings),
fat_window: None,
bitmap_window: None,
bitmap_at: None,
chain_cursor: None,
};
// Bounded as a scan's report is, so what an open holds of the deviations it meets is
// the caller's limit and not the volume's to choose.
let mut deviations = Findings::new(options.limits.max_findings);
reader.check_boot_regions(&mut deviations)?;
reader.check_revision(&mut deviations);
reader.check_volume_state(&mut deviations);
reader.root_bytes = reader.measure_root()?;
reader.load_residents(&mut deviations)?;
// The policy is applied once, after everything an open reads has been read, so a
// strict open reports the first deviation in the order the volume is laid out rather
// than in the order this happens to check.
let (deviations, truncated) = deviations.into_parts();
for err in deviations {
let anomaly = err.anomaly();
if options.policy.is_fatal(anomaly.severity) {
return Err(err);
}
reader.open_anomalies.push(anomaly);
}
if truncated {
reader.open_anomalies.is_full();
}
Ok(reader)
}
/// The volume's geometry, as its boot sector describes it and its root directory completes
/// it.
///
/// This is the same type the planner produces, recovered rather than computed — so a
/// layout planned and a layout read back from the image it produced compare equal, which
/// is what makes a format-then-read a round trip rather than two descriptions that happen
/// to agree. The four fields no boot sector records — where the allocation bitmap and the
/// up-case table are, and how long each is — are what the root directory said rather than
/// what a conformant volume would have.
#[must_use]
pub const fn layout(&self) -> &ExfatLayout {
&self.layout
}
/// The Main Boot Sector exactly as it was parsed.
#[must_use]
pub fn boot_sector(&self) -> &MainBootSector {
&self.boot
}
/// The strictness this reader was opened under.
#[must_use]
pub const fn policy(&self) -> ReadPolicy {
self.policy
}
/// The case folding this volume compares and hashes names through, decoded from the table
/// its root directory names.
#[must_use]
pub const fn upcase(&self) -> &UpcaseTable {
&self.upcase
}
/// The volume label, or `None` for a volume that carries none.
///
/// The authority is the root directory's `0x83` entry, which is what a driver and
/// `exfatlabel` both read and what a rename updates. A volume with no name carries that
/// entry with a character count of zero rather than no entry at all, and this answers
/// `None` for it.
#[must_use]
pub fn volume_label(&self) -> Option<&[u8]> {
self.label.as_deref()
}
/// Whether a driver had this volume open and did not put it down.
///
/// The volume is well-formed either way — the bit is the format recording a state, not a
/// departure from it — and it is the one condition under which what the metadata says and
/// what the volume contains are allowed to differ.
#[must_use]
pub const fn volume_dirty(&self) -> bool {
self.boot.volume_flags & VOLUME_FLAG_VOLUME_DIRTY != 0
}
/// Whether a driver recorded a failure of the medium this volume is on.
#[must_use]
pub const fn media_failure(&self) -> bool {
self.boot.volume_flags & VOLUME_FLAG_MEDIA_FAILURE != 0
}
/// The root directory.
///
/// Its storage is the chain the boot sector names, and it carries no times, because the
/// format records no entry for it. Its length is its chain's, measured when the volume was
/// opened.
#[must_use]
pub const fn root(&self) -> Node {
Node {
storage: Storage::Chain(self.layout.first_cluster_of_root),
attributes: FileAttributes::DIRECTORY,
data_length: self.root_bytes,
valid_data_length: self.root_bytes,
times: None,
}
}
// -- opening ------------------------------------------------------------------------
/// Verify both boot regions: each against its own checksum, and the backup against the
/// main one.
///
/// The main region is preferred whatever the backup says. A reader that fell back to the
/// backup would open a volume under a geometry no driver uses, and every driver reads
/// sector 0.
fn check_boot_regions(&mut self, out: &mut Findings<ReadError>) -> Result<(), ReadError> {
for region in [MAIN_BOOT_REGION_SECTOR, BOOT_REGION_SECTORS] {
// The eleven sectors the checksum covers, then the sector holding it.
let covered = self.read_sectors(region, CHECKSUM_SECTOR)?;
let stored_sector = self.read_sectors(region + CHECKSUM_SECTOR, 1)?;
let Some(stored) = checksum_sector_value(&stored_sector) else {
out.push(ReadError::BootChecksumSectorSplit { sector: region });
continue;
};
let computed = boot_checksum(&covered);
if computed != stored {
out.push(ReadError::BootChecksumMismatch {
sector: region,
computed,
stored,
});
}
self.check_extended_boot_sectors(region, &covered, out);
}
let backup = self.read_sectors(BOOT_REGION_SECTORS, 1)?;
match MainBootSector::read_from(&backup) {
Ok(copy) => {
if let Some(detail) = self.backup_differs(©) {
out.push(ReadError::BackupBootRegionDiffers {
sector: BOOT_REGION_SECTORS,
detail,
});
}
}
Err(e) => out.push(ReadError::BackupBootRegionDiffers {
sector: BOOT_REGION_SECTORS,
detail: e.to_string(),
}),
}
Ok(())
}
/// Check the eight extended boot sectors of the region beginning at `region`, whose bytes
/// are already in `covered`.
///
/// Each ends with [`EXTENDED_BOOT_SIGNATURE`] in its last four bytes, at the end of the
/// sector rather than at a fixed offset — so where to look is a function of the sector
/// size. The region's checksum covers whatever is there and says nothing about what it
/// should be, which is what leaves a region with all eight signatures missing
/// self-consistent and still not the region the format defines.
///
/// One report per region rather than one per sector: eight sectors that were zeroed
/// together are one fact about the region, and a scan that spent eight findings on it
/// would have that much less room for the rest of the volume.
fn check_extended_boot_sectors(
&self,
region: u64,
covered: &[u8],
out: &mut Findings<ReadError>,
) {
let bytes_per_sector = self.layout.bytes_per_sector as usize;
for n in 0..EXTENDED_BOOT_SECTORS {
let at = (EXTENDED_BOOT_FIRST_SECTOR + n) as usize * bytes_per_sector;
// A short slice is a region the read did not cover, which is the read's to
// report rather than this function's.
let Some(found) = covered
.get(at..at + bytes_per_sector)
.and_then(extended_boot_signature)
else {
return;
};
if found != EXTENDED_BOOT_SIGNATURE {
out.push(ReadError::BadExtendedBootSignature {
sector: region + EXTENDED_BOOT_FIRST_SECTOR + n,
found,
expected: EXTENDED_BOOT_SIGNATURE,
});
return;
}
}
}
/// Which field of the backup boot sector describes a different volume from the main one,
/// or `None` where the two agree.
///
/// The two fields outside the region's checksum are excluded, and that exclusion is the
/// whole reason this compares fields rather than bytes: a mounted driver marks the volume
/// dirty and updates how full it is in the main region alone, so a byte comparison would
/// report every volume that has ever been written to.
fn backup_differs(&self, copy: &MainBootSector) -> Option<String> {
let main = &self.boot;
// Compared exhaustively through a destructure, so a field added to the boot sector is
// a compile error here rather than a field the backup is silently allowed to differ in.
let MainBootSector {
jump_boot,
file_system_name,
partition_offset,
volume_length,
fat_offset,
fat_length,
cluster_heap_offset,
cluster_count,
first_cluster_of_root,
volume_serial,
file_system_revision,
volume_flags: _,
bytes_per_sector_shift,
sectors_per_cluster_shift,
number_of_fats,
drive_select,
percent_in_use: _,
boot_code,
} = copy;
let fields: [(&'static str, bool); 15] = [
("JumpBoot", *jump_boot == main.jump_boot),
("FileSystemName", *file_system_name == main.file_system_name),
(
"PartitionOffset",
*partition_offset == main.partition_offset,
),
("VolumeLength", *volume_length == main.volume_length),
("FatOffset", *fat_offset == main.fat_offset),
("FatLength", *fat_length == main.fat_length),
(
"ClusterHeapOffset",
*cluster_heap_offset == main.cluster_heap_offset,
),
("ClusterCount", *cluster_count == main.cluster_count),
(
"FirstClusterOfRootDirectory",
*first_cluster_of_root == main.first_cluster_of_root,
),
("VolumeSerialNumber", *volume_serial == main.volume_serial),
(
"FileSystemRevision",
*file_system_revision == main.file_system_revision,
),
(
"BytesPerSectorShift",
*bytes_per_sector_shift == main.bytes_per_sector_shift,
),
(
"SectorsPerClusterShift",
*sectors_per_cluster_shift == main.sectors_per_cluster_shift,
),
("NumberOfFats", *number_of_fats == main.number_of_fats),
("DriveSelect", *drive_select == main.drive_select),
];
if let Some((field, _)) = fields.iter().find(|(_, same)| !*same) {
return Some(format!("{field} differs from the main region's"));
}
(*boot_code != main.boot_code)
.then(|| "BootCode differs from the main region's".to_string())
}
/// Record the two states a driver leaves in `VolumeFlags`.
///
/// Both are cosmetic. The bits are the format correctly recording something that happened
/// to the volume, so the message says what each means rather than which field held it: a
/// caller told "the volume was not cleanly unmounted" knows what to do, and one told that
/// a flag word is `0x0002` does not.
fn check_volume_state(&self, out: &mut Findings<ReadError>) {
if self.volume_dirty() {
out.push(ReadError::VolumeDirty);
}
if self.media_failure() {
out.push(ReadError::MediaFailure);
}
}
/// Record a minor revision of the format this reader does not know.
///
/// The major half is the refusal, and it is applied where the rest of the boot sector is
/// judged, so the classifier and the reader answer together. The minor half is the weaker
/// case the format asks an implementation to honour: every structure is the one this
/// reader knows, and something in the volume may mean more than it appears to.
fn check_revision(&self, out: &mut Findings<ReadError>) {
let minor = self.boot.minor_revision();
if minor != FILE_SYSTEM_MINOR_REVISION {
out.push(ReadError::UnknownMinorRevision { minor });
}
}
/// How long the root directory's chain is, in bytes.
///
/// The format records no entry for the root, so there is no length field to read: the root
/// is exactly as long as the chain the boot sector's first cluster begins. Measured at open
/// so every later question about the root has a length to answer with.
fn measure_root(&mut self) -> Result<u64, ReadError> {
let start = self.layout.first_cluster_of_root;
let mut clusters = 0u64;
let mut current = start;
// A step counter bounds the walk, the idiom `chain_cluster` uses: a chain of
// distinct clusters cannot be longer than the heap, so a walk still going past
// that count has revisited one. A set answering the same question would cost a
// bit per heap cluster — half a gigabyte of zeros on the largest volumes — at
// every open, to detect a cycle the count detects for free.
loop {
if clusters >= u64::from(self.layout.cluster_count) {
return Err(ReadError::ChainTooLong {
start,
clusters: self.layout.cluster_count,
});
}
clusters += 1;
match self.next_cluster(current)? {
Some(next) => current = next,
None => break,
}
}
Ok(clusters * u64::from(self.layout.bytes_per_cluster))
}
/// Read the root directory's describing entries and load what they name.
///
/// Three entries are found here and nowhere else: the allocation bitmap's, the up-case
/// table's, and the volume label's. The first two are what a driver must have before it can
/// allocate anything or compare any name, which is why a volume missing either is refused
/// rather than reported as an empty tree.
fn load_residents(&mut self, out: &mut Findings<ReadError>) -> Result<(), ReadError> {
let root = self.root();
let mut bitmap: Option<AllocationBitmapEntry> = None;
let mut upcase: Option<UpcaseTableEntry> = None;
let mut label: Option<VolumeLabelEntry> = None;
// Only the critical primary entries are looked at. A set's secondary entries can never
// be one of these — the type byte's secondary bit says so — so stepping over them by
// that bit alone finds the residents without assembling a single name.
//
// The first of each kind is what a driver takes, so it is what this takes; a second
// is storage nothing reads, and is reported rather than stepped over in silence. The
// reports go straight into `out`, whose bound is the caller's: a root directory can
// hold a duplicate in nearly every slot it has.
//
// A duplicate is a deviation a strict open refuses, and the open would refuse on it
// whatever followed, so a strict open stops at the first one rather than reading the
// rest of the directory for a verdict already reached. A lenient open reads on, since
// the residents it needs may sit after any number of them.
let stops = self.policy.is_fatal(
ReadError::DuplicateRootEntry {
index: 0,
entry_type: "",
}
.anomaly()
.severity,
);
let mut refused = false;
self.for_each_slot::<ReadError>(&root, |_, slot| {
let entry_type = slot.entry_type();
if entry_type.is_end_of_directory() {
return Ok(ControlFlow::Break(()));
}
if !entry_type.in_use() || entry_type.is_secondary() {
return Ok(ControlFlow::Continue(()));
}
let named = match entry_type {
EntryType::ALLOCATION_BITMAP => match bitmap {
None => {
bitmap = Some(AllocationBitmapEntry::read_from(&slot.bytes)?);
None
}
Some(_) => Some("allocation bitmap"),
},
EntryType::UPCASE_TABLE => match upcase {
None => {
upcase = Some(UpcaseTableEntry::read_from(&slot.bytes)?);
None
}
Some(_) => Some("up-case table"),
},
EntryType::VOLUME_LABEL => match label {
None => {
label = Some(VolumeLabelEntry::read_from(&slot.bytes)?);
None
}
Some(_) => Some("volume label"),
},
_ => None,
};
if let Some(named) = named {
out.push(ReadError::DuplicateRootEntry {
index: slot.index,
entry_type: named,
});
if stops {
refused = true;
return Ok(ControlFlow::Break(()));
}
}
Ok(ControlFlow::Continue(()))
})?;
if refused {
return Ok(());
}
let bitmap = bitmap.ok_or(ReadError::MissingResident {
resident: "allocation bitmap",
})?;
let upcase = upcase.ok_or(ReadError::MissingResident {
resident: "up-case table",
})?;
// The identifier says which of two bitmaps an entry is, and a volume has two only
// where it has two allocation tables. This reader reads the one-table volume alone,
// whose one bitmap is the first, so an entry naming itself the second contradicts the
// boot sector's table count. The seven bits above it are reserved, a separate remark.
if bitmap.bitmap_flags & BITMAP_IDENTIFIER != 0 {
out.push(ReadError::SecondBitmap);
}
let reserved = bitmap.bitmap_flags & !BITMAP_IDENTIFIER;
if reserved != 0 {
out.push(ReadError::BitmapReservedFlags { bits: reserved });
}
// A bitmap is one bit per cluster. A shorter one addresses fewer clusters than the
// volume has, and a longer one is a length that is not this bitmap's.
let want = u64::from(self.layout.cluster_count).div_ceil(8);
if bitmap.data_length != want {
out.push(ReadError::BitmapWrongSize {
bytes: bitmap.data_length,
clusters: self.layout.cluster_count,
});
}
self.bitmap = Resident {
first_cluster: bitmap.first_cluster,
bytes: bitmap.data_length,
};
self.layout.bitmap_cluster = bitmap.first_cluster;
self.layout.bitmap_bytes = bitmap.data_length;
self.layout.upcase_cluster = upcase.first_cluster;
self.layout.upcase_bytes = upcase.data_length;
self.upcase = self.load_upcase(&upcase, out)?;
self.label = label.and_then(|entry| self.label_of(&entry, out));
Ok(())
}
/// The name a volume label entry carries, or `None` where it carries none.
///
/// Two fields are judged rather than taken. `CharacterCount` runs 0 to 11, and a larger
/// one names units the field does not have — so it is reported and the field is read to
/// its end, which is the only thing there is to read. A label carrying `U+0000` is one
/// every implementation that reads the field as terminated rather than counted would read
/// differently, so it is reported and answered `None`. A label carrying a character a name
/// may not hold is reported and handed back. This crate's writer refuses to produce
/// either, so the two ends of each rule match.
///
/// An over-long count on an unnamed volume is what makes the second check earn its place.
/// The field of an unnamed volume is eleven zero units, so clamping alone would turn "no
/// name" into a name of eleven NULs.
fn label_of(&self, entry: &VolumeLabelEntry, out: &mut Findings<ReadError>) -> Option<Vec<u8>> {
let mut count = usize::from(entry.character_count);
if count > MAX_LABEL_UNITS {
out.push(ReadError::LabelTooLong {
count: entry.character_count,
limit: MAX_LABEL_UNITS,
});
count = MAX_LABEL_UNITS;
}
if count == 0 {
return None;
}
let units = &entry.label[..count];
if units.contains(&0) {
out.push(ReadError::LabelNulUnit);
return None;
}
// A label reserves the characters a name does. One holding them is the volume's
// own statement of its name, so it is handed back, and the character is reported.
if let Some(ch) = char::decode_utf16(units.iter().copied())
.filter_map(Result::ok)
.find(|ch| is_reserved_name_char(*ch))
{
out.push(ReadError::LabelForbiddenCharacter { ch });
}
Some(decode_utf16(units).0)
}
/// The folding the volume's up-case table describes.
///
/// The checksum is verified and a mismatch reported, and the table is decoded either way.
/// That is the honest answer to a table whose checksum fails under a lenient read: the
/// bytes are still the volume's own statement about how its names compare, and folding
/// through a table this crate happens to carry would answer a question about *this* volume
/// with a fact about another one. A table that cannot be read at all folds nothing, which
/// is the conformant extreme rather than an invention.
fn load_upcase(
&mut self,
entry: &UpcaseTableEntry,
out: &mut Findings<ReadError>,
) -> Result<UpcaseTable, ReadError> {
if entry.data_length > MAX_UPCASE_BYTES {
out.push(ReadError::UpcaseTooLong {
bytes: entry.data_length,
limit: MAX_UPCASE_BYTES,
});
return Ok(UpcaseTable::new(&[]));
}
let bytes = self.read_chain(entry.first_cluster, entry.data_length)?;
let computed = upcase_checksum(&bytes);
if computed != entry.table_checksum {
out.push(ReadError::UpcaseChecksumMismatch {
computed,
stored: entry.table_checksum,
});
}
// A trailing odd byte is half a code unit and states nothing, so it is dropped rather
// than paired with whatever follows the table.
let units: Vec<u16> = (0..bytes.len() / 2)
.map(|n| get_u16(&bytes, n * 2))
.collect();
let table = UpcaseTable::new(&units);
// A volume may carry its own folding for every character but the first 128, whose
// mappings the format fixes. A checksum that holds says the table is the one recorded,
// not that it folds ASCII as every exFAT does, so the mappings are held to that as
// well — and the table is kept as the volume's own either way, which is the folding a
// lenient read of this volume answers with.
if let Some((character, maps_to)) = table.mandatory_deviation() {
out.push(ReadError::UpcaseMandatoryMapping { character, maps_to });
}
Ok(table)
}
// -- byte-level access --------------------------------------------------------------
/// `count` sectors from `first`, refusing a range the volume does not describe.
///
/// The bound is the volume's own length, so a structure naming a sector past the
/// filesystem is answered rather than read out of whatever follows it in the source.
fn read_sectors(&mut self, first: u64, count: u64) -> Result<Vec<u8>, ReadError> {
let out_of_range = || ReadError::BadBootSector {
detail: format!("sector {first} is past the volume's {} sectors", {
self.layout.volume_length
}),
};
let end = first
.checked_add(count)
.filter(|end| *end <= self.layout.volume_length)
.ok_or_else(out_of_range)?;
debug_assert!(end <= self.layout.volume_length);
let bytes_per_sector = u64::from(self.layout.bytes_per_sector);
let offset = offset_of(self.base, first, bytes_per_sector).ok_or_else(out_of_range)?;
let len = usize::try_from(count * bytes_per_sector).map_err(|_| out_of_range())?;
Ok(read_exact_at(&mut self.src, offset, len)?)
}
/// Cluster `n`'s bytes.
fn read_cluster(&mut self, n: u32) -> Result<Vec<u8>, ReadError> {
let first = self
.layout
.cluster_start_sector(n)
.ok_or(ReadError::ClusterOutOfRange { cluster: n })?;
self.read_sectors(first, u64::from(self.layout.sectors_per_cluster()))
}
/// The allocation table's entry for `cluster`.
///
/// Read through a one-sector window, so a chain walk pays one read per table sector rather
/// than one per cluster.
fn table_entry(&mut self, cluster: u32) -> Result<u32, ReadError> {
// The table has an entry for every cluster and for the two reserved numbers ahead of
// them, and `layout_from_boot` has already established it is long enough for that.
if cluster < FIRST_CLUSTER || cluster - FIRST_CLUSTER >= self.layout.cluster_count {
return Err(ReadError::ClusterOutOfRange { cluster });
}
let bytes_per_sector = u64::from(self.layout.bytes_per_sector);
let offset = u64::from(cluster) * 4;
let sector = u64::from(self.layout.fat_offset) + offset / bytes_per_sector;
// An entry is four bytes at a four-byte-aligned offset, so it lies wholly within one
// sector however large the sector is.
let within = (offset % bytes_per_sector) as usize;
let stale = match &self.fat_window {
Some((at, _)) => *at != sector,
None => true,
};
if stale {
let buf = self.read_sectors(sector, 1)?;
self.fat_window = Some((sector, buf));
}
let (_, buf) = self.fat_window.as_ref().expect("just loaded");
// Bounded before the accessor, which indexes: a sector shorter than the offset the
// arithmetic reached is a volume whose sector size and table length disagree.
if within + 4 > buf.len() {
return Err(ReadError::ClusterOutOfRange { cluster });
}
Ok(get_u32(buf, within))
}
/// Whether the allocation bitmap says `cluster` is in use.
///
/// A cluster the bitmap does not cover — one past its length — is answered `false`, which
/// is the bitmap saying nothing rather than saying no. The length is checked at open, so a
/// volume that reaches this is one already reported.
fn is_allocated(&mut self, cluster: u32) -> Result<bool, ReadError> {
if cluster < FIRST_CLUSTER || cluster - FIRST_CLUSTER >= self.layout.cluster_count {
return Err(ReadError::ClusterOutOfRange { cluster });
}
let bit = u64::from(cluster - FIRST_CLUSTER);
let at = bit / 8;
if at >= self.bitmap.bytes {
return Ok(false);
}
let bytes_per_cluster = u64::from(self.layout.bytes_per_cluster);
let bytes_per_sector = u64::from(self.layout.bytes_per_sector);
let index = at / bytes_per_cluster;
// The bitmap's own place in its chain, remembered. The chain cursor beside it is the
// one a *stream* walk uses, and a scan interleaves the two — claim a file's cluster,
// ask the bitmap about it, claim the next — so sharing one cursor would restart the
// bitmap's walk at every question and make a scan quadratic in the bitmap's length.
// One entry is enough, because both callers ask about a run of adjacent clusters.
let holding = match self.bitmap_at {
Some((cached, cluster)) if cached == index => cluster,
_ => {
let Some(holding) = self.chain_cluster(self.bitmap.first_cluster, index)? else {
return Err(ReadError::StreamTooShort {
start: self.bitmap.first_cluster,
declared: self.bitmap.bytes,
held: index * bytes_per_cluster,
});
};
self.bitmap_at = Some((index, holding));
holding
}
};
let within_cluster = at % bytes_per_cluster;
let Some(cluster_sector) = self.layout.cluster_start_sector(holding) else {
return Err(ReadError::ClusterOutOfRange { cluster: holding });
};
let sector = cluster_sector + within_cluster / bytes_per_sector;
let within = (within_cluster % bytes_per_sector) as usize;
let stale = match &self.bitmap_window {
Some((cached, _)) => *cached != sector,
None => true,
};
if stale {
let buf = self.read_sectors(sector, 1)?;
self.bitmap_window = Some((sector, buf));
}
let (_, buf) = self.bitmap_window.as_ref().expect("just loaded");
let byte = buf.get(within).copied().unwrap_or(0);
Ok(byte & (1 << (bit % 8)) != 0)
}
/// The cluster that follows `cluster` in its chain, or `None` where the chain ends.
///
/// The bad-cluster mark is named rather than left to the range test that would also
/// refuse it: a chain reaching one is a chain into storage a driver was told to leave
/// alone, and the number it holds is not a cluster that happens to be too high.
fn next_cluster(&mut self, cluster: u32) -> Result<Option<u32>, ReadError> {
let entry = self.table_entry(cluster)?;
if entry == super::ondisk::END_OF_CHAIN {
return Ok(None);
}
if entry == BAD_CLUSTER {
return Err(ReadError::BadClusterInChain { cluster: entry });
}
if entry < FIRST_CLUSTER || entry - FIRST_CLUSTER >= self.layout.cluster_count {
return Err(ReadError::BadChainEntry { cluster, entry });
}
Ok(Some(entry))
}
/// The cluster at `index` in the chain beginning at `start`, or `None` where the chain is
/// shorter than that.
///
/// Resumes from [`chain_cursor`](Self::chain_cursor) where it can, so reading one file in
/// order costs one pass over its chain rather than one per call.
fn chain_cluster(&mut self, start: u32, index: u64) -> Result<Option<u32>, ReadError> {
if start < FIRST_CLUSTER || start - FIRST_CLUSTER >= self.layout.cluster_count {
return Err(ReadError::ClusterOutOfRange { cluster: start });
}
let (mut at, mut current) = match self.chain_cursor {
Some((cursor_start, cursor_index, cursor_cluster))
if cursor_start == start && cursor_index <= index =>
{
(cursor_index, cursor_cluster)
}
_ => (0, start),
};
while at < index {
match self.next_cluster(current)? {
Some(next) => {
current = next;
at += 1;
}
None => return Ok(None),
}
// A chain longer than the volume has clusters must repeat one, so the bound is the
// geometry's rather than a limit a caller sets.
if at > u64::from(self.layout.cluster_count) {
return Err(ReadError::ChainTooLong {
start,
clusters: self.layout.cluster_count,
});
}
}
self.chain_cursor = Some((start, at, current));
Ok(Some(current))
}
/// The cluster holding byte `index * bytes_per_cluster` of `storage`, or `None` where the
/// stream is shorter than that.
///
/// This is the one place the two run shapes become one answer: a declared consecutive run
/// is arithmetic and a chain is a walk, and every read above here asks this rather than
/// asking which shape it has.
fn stream_cluster(&mut self, storage: Storage, index: u64) -> Result<Option<u32>, ReadError> {
match storage {
Storage::None => Ok(None),
Storage::Contiguous(first) => {
// A run that leaves the heap is refused rather than wrapped: the sum is
// computed in 64 bits and the bound is the heap's own last cluster.
let n = u64::from(first) + index;
match u32::try_from(n) {
Ok(n)
if n >= FIRST_CLUSTER && n - FIRST_CLUSTER < self.layout.cluster_count =>
{
Ok(Some(n))
}
_ => Err(ReadError::ClusterOutOfRange {
cluster: u32::try_from(n).unwrap_or(u32::MAX),
}),
}
}
Storage::Chain(start) => self.chain_cluster(start, index),
}
}
/// `len` bytes from the chain beginning at `first`.
///
/// For the two residents, whose lengths a caller has already bounded. Everything else
/// streams.
fn read_chain(&mut self, first: u32, len: u64) -> Result<Vec<u8>, ReadError> {
let bytes_per_cluster = u64::from(self.layout.bytes_per_cluster);
let mut out = Vec::new();
let mut index = 0u64;
while (out.len() as u64) < len {
let Some(cluster) = self.chain_cluster(first, index)? else {
return Err(ReadError::StreamTooShort {
start: first,
declared: len,
held: index * bytes_per_cluster,
});
};
let bytes = self.read_cluster(cluster)?;
let take = bytes
.len()
.min(usize::try_from(len - out.len() as u64).unwrap_or(usize::MAX));
out.extend_from_slice(&bytes[..take]);
index += 1;
}
Ok(out)
}
// -- directories --------------------------------------------------------------------
/// Hand every 32-byte slot of a directory's storage to `visit`, in order.
///
/// One cluster is held at a time, so what this allocates is the volume's cluster size and
/// not the directory's own length. That is the difference between a bound the *structure*
/// implies and one a caller can rely on: a crafted directory whose chain spans the volume
/// is the volume's size, and reading it whole would be an allocation the size of the image
/// however tight a [`Limits`] the caller set.
///
/// `visit` says whether to keep going, so a caller that has found what it came for stops
/// rather than reading the rest of the chain.
fn for_each_slot<E: From<ReadError>>(
&mut self,
node: &Node,
mut visit: impl FnMut(&mut Self, Slot) -> Result<ControlFlow<()>, E>,
) -> Result<(), E> {
let Some(start) = node.storage.first_cluster() else {
return Ok(());
};
let bytes_per_cluster = u64::from(self.layout.bytes_per_cluster);
let slots_per_sector = u64::from(self.layout.bytes_per_sector) / DIR_ENTRY_SIZE as u64;
// How many clusters the directory's length covers. The root's length was measured from
// its chain at open, so every directory here has one. It is the length and not the
// written length that bounds the slots: the format makes them one for a directory, and
// where an image records them differently the allocation is what holds the entries,
// as the pinned `fsck.exfat` reads it (observed).
let clusters = node.data_length.div_ceil(bytes_per_cluster.max(1));
let mut index = 0u32;
// Clusters this walk has already read. The step count alone bounds it at the volume's
// cluster count, which for a cycling chain means re-reading the same cluster that many
// times before the refusal — and a scan absorbs that error and moves on, so the cost is
// paid afresh for every directory. A repeat is a cycle whatever it costs, so it ends
// the chain the moment it is seen.
//
// The set is the volume's own domain, one bit per cluster, which is the answer this
// file gives that question everywhere it is asked.
let mut visited = ClusterSet::new(self.layout.cluster_count);
visited.insert(start);
let mut current = Some(start);
for at in 0..clusters {
let Some(cluster) = current else {
return Err(E::from(ReadError::StreamTooShort {
start,
declared: node.data_length,
held: at * bytes_per_cluster,
}));
};
let first_sector = self
.layout
.cluster_start_sector(cluster)
.ok_or(ReadError::ClusterOutOfRange { cluster })?;
let bytes = self.read_cluster(cluster).map_err(E::from)?;
for (i, chunk) in bytes.as_chunks::<DIR_ENTRY_SIZE>().0.iter().enumerate() {
let slot = Slot {
bytes: *chunk,
index,
cluster,
sector: first_sector + (i as u64) / slots_per_sector.max(1),
};
index = index.saturating_add(1);
if visit(self, slot)?.is_break() {
return Ok(());
}
}
// Only where there is another cluster to reach. Asking for the one past the last
// is not free in either shape: a declared consecutive run's arithmetic refuses a
// cluster outside the heap, so a directory ending on the heap's *last* cluster
// would be refused for running past an end it never reached.
if at + 1 == clusters {
break;
}
current = match node.storage {
// A declared consecutive run is arithmetic, and the next cluster is refused
// where it would leave the heap rather than read from wherever it landed.
Storage::Contiguous(_) | Storage::None => {
self.stream_cluster(node.storage, at + 1).map_err(E::from)?
}
Storage::Chain(_) => match self.next_cluster(cluster).map_err(E::from)? {
None => None,
Some(following) => {
if !visited.insert(following) {
return Err(E::from(ReadError::ChainTooLong {
start,
clusters: self.layout.cluster_count,
}));
}
Some(following)
}
},
};
}
Ok(())
}
/// The entries of a directory, with names reassembled and every set checked.
///
/// The volume label and the two residents are not among them: none is a name a consumer of
/// a tree wants handed to it, and each is answered by its own accessor.
///
/// Every name that *is* handed back is one a directory can hold. A name resolving to `.` or
/// `..`, empty, or carrying a path separator or a NUL, is
/// [`HostileName`](ReadError::HostileName) — an error under [`ReadPolicy::Strict`] and a
/// finding a [`scan`](Self::scan) collects, never an entry in the returned list.
///
/// The directory's storage is read a cluster at a time and never held whole, so what one
/// call allocates is the entries it produces plus a single cluster. The entries themselves
/// are bounded by [`Limits::max_walk_entries`] and by the volume's whole directory
/// capacity, whichever is smaller.
///
/// What is *read* is bounded three times over, because a declared length is a number an
/// image supplies: at the end-of-directory marker, which is where the directory ends and
/// where every driver stops; at
/// [`MAX_DIRECTORY_BYTES`], which is the cap the format
/// puts on one; and at the cluster heap, which is what any stream's bytes could occupy.
///
/// # Errors
///
/// [`ReadError`] variants when the directory's storage cannot be read,
/// [`ReadError::WalkTooLarge`] when it holds more entries than that bound, and — under
/// [`ReadPolicy::Strict`] — whichever deviation its entries carry.
pub fn read_dir(&mut self, node: &Node) -> Result<Vec<Entry>, ReadError> {
let policy = self.policy;
self.parse_dir(node, &mut OnDeviation::Policy(policy))
}
/// A directory's entries gathered into a list, held to [`Limits::max_walk_entries`] and
/// the volume's whole directory capacity.
fn parse_dir(
&mut self,
node: &Node,
deviations: &mut OnDeviation<'_>,
) -> Result<Vec<Entry>, ReadError> {
// The directory's own entries are held, and its storage is not: a crafted directory is
// bounded by what a caller allowed rather than by how many clusters it chained
// together. The structural half of the cap is the volume's whole directory capacity,
// which a well-formed directory can never reach.
let cap = self.limits.max_walk_entries.min(self.max_names());
let mut out: Vec<Entry> = Vec::new();
// Every name the directory answers to, folded through the volume's up-case table as a
// lookup compares it, beside the set that first carried it. A second set carrying one
// is reported once the whole directory is read, since `deviations` is the parser's
// while it runs.
let mut names: std::collections::HashMap<Vec<u16>, u32> = std::collections::HashMap::new();
let mut repeats = Vec::new();
self.parse_entries(node, deviations, |reader, entry, index| {
if out.len() >= cap {
return Err(ReadError::WalkTooLarge { limit: cap });
}
match names.entry(reader.fold_name(&entry.name)) {
std::collections::hash_map::Entry::Occupied(first) => {
repeats.push((
index,
ReadError::IndistinguishableNames {
index,
first: *first.get(),
},
));
}
std::collections::hash_map::Entry::Vacant(slot) => {
slot.insert(index);
}
}
out.push(entry);
Ok(ControlFlow::Continue(()))
})?;
for (index, repeat) in repeats {
deviations.record(Location::at_entry(index), repeat)?;
}
Ok(out)
}
/// The shared directory parser, which is the one place an entry's bytes become a name.
///
/// Each entry is handed to `each` as its set is completed, and `each` says whether to go
/// on, so a lookup stops at the name it came for rather than reading the directory to its
/// end. Nothing is held but the set in flight.
fn parse_entries(
&mut self,
node: &Node,
deviations: &mut OnDeviation<'_>,
mut each: impl FnMut(&mut Self, Entry, u32) -> Result<ControlFlow<()>, ReadError>,
) -> Result<(), ReadError> {
if !node.is_dir() {
return Err(ReadError::NotADirectory { path: Vec::new() });
}
// The root is the one directory the format records no entry for, which is what
// [`Node::times`] being `None` carries — so the identity is read off the node rather
// than recomputed from where its bytes are. A subdirectory whose stream extension
// names the root's first cluster is `Storage::Chain(root)` and is not the root, and a
// bitmap, up-case or label entry inside it is misplaced like any other.
let is_root = node.times.is_none();
let mut set: Option<PendingSet> = None;
// The cluster the end-of-directory marker sat in, once one has been met.
let mut ended: Option<u32> = None;
let mut reported_after_end = false;
self.for_each_slot::<ReadError>(node, |reader, slot| {
let at = slot.location();
let entry_type = slot.entry_type();
if let Some(marker) = ended {
// The directory ends at the marker: every driver stops there, so what is
// behind it is not the directory's content however far its declared length
// runs. Reading on to that length is a courtesy a scan is owed and not a
// traversal the format asks for, so it stops at the end of the cluster the
// marker sat in — the one already in hand. That is what keeps the cost of
// reading a directory the cost of what is in it: a length is a number an
// image supplies, and a directory of two entries declaring the whole heap
// would otherwise be read to the end of the heap.
if slot.cluster != marker {
return Ok(ControlFlow::Break(()));
}
// A used slot past the marker is storage no reader reaches — including this
// one, since yielding it would show a caller names that nothing else on the
// volume can see. It is reported once rather than once per slot, and never
// handed back.
if !entry_type.is_end_of_directory() && !reported_after_end {
deviations.record(at, ReadError::EntriesAfterEnd { index: slot.index })?;
reported_after_end = true;
}
return Ok(ControlFlow::Continue(()));
}
// A set under assembly consumes the slots behind it. Anything that is not an
// in-use secondary entry ends it short, and the slot is then read afresh below as
// whatever it is — a set that stopped early must not swallow the entry after it.
if let Some(pending) = set.as_mut() {
if entry_type.in_use() && entry_type.is_secondary() {
pending.push(&slot.bytes);
if pending.is_complete() {
let finished = set.take().expect("just checked");
let index = finished.index;
if finished.benign {
reader.finish_benign_set(&finished, deviations)?;
} else if let Some(entry) = reader.finish_set(finished, deviations)? {
return each(reader, entry, index);
}
}
return Ok(ControlFlow::Continue(()));
}
let broken = set.take().expect("just checked");
deviations.record(
Location::at_entry(broken.index),
ReadError::IncompleteEntrySet {
index: broken.index,
detail: format!(
"it declares {} entries behind it and {} follow",
broken.want,
broken.have()
),
},
)?;
}
if entry_type.is_end_of_directory() {
ended = Some(slot.cluster);
return Ok(ControlFlow::Continue(()));
}
// A slot whose in-use bit is clear is skipped and enumeration continues. It is not
// an edge case: the second slot of every formatted volume's root directory is
// exactly that, with the bitmap and the up-case table behind it.
if !entry_type.in_use() {
return Ok(ControlFlow::Continue(()));
}
if entry_type.is_secondary() {
deviations.record(at, ReadError::StraySecondaryEntry { index: slot.index })?;
return Ok(ControlFlow::Continue(()));
}
match entry_type {
EntryType::FILE => {
let file = FileEntry::read_from(&slot.bytes)?;
if file.secondary_count == 0 {
deviations.record(
at,
ReadError::IncompleteEntrySet {
index: slot.index,
detail: "it declares no entries behind it, and a file needs a \
stream extension and a name"
.to_string(),
},
)?;
return Ok(ControlFlow::Continue(()));
}
set = Some(PendingSet::new(
slot.index,
file.secondary_count,
&slot.bytes,
false,
));
}
// The three the root directory owns. Each is answered by its own accessor, so
// none is a name in the tree — and one anywhere else is an entry the format
// defines a single place for.
EntryType::ALLOCATION_BITMAP
| EntryType::UPCASE_TABLE
| EntryType::VOLUME_LABEL => {
if !is_root {
let named = match entry_type {
EntryType::ALLOCATION_BITMAP => "allocation bitmap",
EntryType::UPCASE_TABLE => "up-case table",
_ => "volume label",
};
deviations.record(
at,
ReadError::MisplacedRootEntry {
index: slot.index,
entry_type: named,
},
)?;
}
}
// A benign primary heads a set as every primary does, through the generic template:
// the format lets an implementation pass over one it does not recognize together
// with the set behind it (documented), so its secondaries are its own rather than
// strays, and what it allocates is claimed by a scan. The two the format defines
// carry no secondaries, and the volume GUID's place is the root.
other if other.is_benign() => {
let count = slot.bytes[1];
if other == EntryType::VOLUME_GUID {
if !is_root {
deviations.record(
at,
ReadError::MisplacedRootEntry {
index: slot.index,
entry_type: "volume GUID",
},
)?;
}
if count != 0 {
deviations.record(
at,
ReadError::VolumeGuidWithSecondaries {
index: slot.index,
count,
},
)?;
}
}
let pending = PendingSet::new(slot.index, count, &slot.bytes, true);
if pending.is_complete() {
reader.finish_benign_set(&pending, deviations)?;
} else {
set = Some(pending);
}
}
other => {
deviations.record(
at,
ReadError::UnknownCriticalEntry {
index: slot.index,
entry_type: other.0,
},
)?;
}
}
Ok(ControlFlow::Continue(()))
})?;
// A directory whose last set runs past its end is a set that was never completed.
if let Some(unfinished) = set {
deviations.record(
Location::at_entry(unfinished.index),
ReadError::IncompleteEntrySet {
index: unfinished.index,
detail: format!(
"it declares {} entries behind it and the directory ends after {}",
unfinished.want,
unfinished.have()
),
},
)?;
}
Ok(())
}
/// Read a complete set headed by a benign primary entry this reader does not interpret,
/// through the generic template (documented): its checksum is held to its bytes, and
/// what it and its benign secondaries allocate is handed to the scan.
fn finish_benign_set(
&mut self,
set: &PendingSet,
deviations: &mut OnDeviation<'_>,
) -> Result<(), ReadError> {
let index = set.index;
let stored = get_u16(&set.bytes, 2);
let computed = entry_set_checksum(&set.bytes);
if computed != stored {
deviations.record(
Location::at_entry(index),
ReadError::SetChecksumMismatch {
index,
computed,
stored,
},
)?;
}
let (primary, secondaries) = set.bytes.split_at(DIR_ENTRY_SIZE);
if let Some((storage, bytes)) = generic_allocation(primary, true) {
deviations.claim(BenignAllocation {
index,
storage,
bytes,
});
}
for slot in secondaries.as_chunks::<DIR_ENTRY_SIZE>().0 {
if EntryType(slot[0]).is_benign()
&& let Some((storage, bytes)) = generic_allocation(slot, false)
{
deviations.claim(BenignAllocation {
index,
storage,
bytes,
});
}
}
Ok(())
}
/// Turn a complete entry set into the one name it describes, or nothing where a deviation
/// the policy tolerates leaves no name to hand back.
fn finish_set(
&mut self,
set: PendingSet,
deviations: &mut OnDeviation<'_>,
) -> Result<Option<Entry>, ReadError> {
let at = Location::at_entry(set.index);
let index = set.index;
let computed = entry_set_checksum(&set.bytes);
let file = FileEntry::read_from(&set.bytes)?;
if computed != file.set_checksum {
deviations.record(
at,
ReadError::SetChecksumMismatch {
index,
computed,
stored: file.set_checksum,
},
)?;
}
// The stream extension is the set's first secondary entry, and the format puts it
// nowhere else: a set without one describes a file with no length and no allocation.
let Some(stream_bytes) = set.bytes.get(DIR_ENTRY_SIZE..2 * DIR_ENTRY_SIZE) else {
deviations.record(
at,
ReadError::IncompleteEntrySet {
index,
detail: "it holds no stream extension".to_string(),
},
)?;
return Ok(None);
};
let Ok(stream) = StreamExtensionEntry::read_from(stream_bytes) else {
deviations.record(
at,
ReadError::IncompleteEntrySet {
index,
detail: "its first secondary entry is not a stream extension".to_string(),
},
)?;
return Ok(None);
};
// Every name entry of the set, in order. A benign secondary entry a vendor placed among
// them is stepped over rather than read as name units.
let mut units: Vec<u16> = Vec::new();
for slot in set.bytes[2 * DIR_ENTRY_SIZE..]
.as_chunks::<DIR_ENTRY_SIZE>()
.0
{
let entry_type = EntryType(slot[0]);
if entry_type == EntryType::FILE_NAME {
let name = FileNameEntry::read_from(slot)?;
units.extend_from_slice(&name.units);
} else if !entry_type.is_benign() {
deviations.record(
at,
ReadError::UnknownCriticalEntry {
index,
entry_type: entry_type.0,
},
)?;
} else if let Some((storage, bytes)) = generic_allocation(slot, false) {
deviations.claim(BenignAllocation {
index,
storage,
bytes,
});
}
}
// Both directions of one comparison. The secondary count is defined as one plus the
// name's entries, so a set is as long as its name and no longer: short of it there is
// no name to hand back, and past it there are bytes the set's checksum covers and no
// implementation reads.
let want = usize::from(stream.name_length);
if units.len() < want {
deviations.record(
at,
ReadError::IncompleteEntrySet {
index,
detail: format!(
"its name is {want} code units and its entries carry {}",
units.len()
),
},
)?;
return Ok(None);
}
//
// Counted in *entries* rather than in units, because the last entry of a name is
// padded: a ten-unit name occupies one entry carrying fifteen units, and comparing
// units would report every name whose length is not a multiple of fifteen.
let carried = units.len() / NAME_UNITS_PER_ENTRY;
let needed = want.div_ceil(NAME_UNITS_PER_ENTRY);
if carried > needed {
deviations.record(
at,
ReadError::ExcessNameEntries {
index,
want: needed,
have: carried,
},
)?;
}
units.truncate(want);
// The hash is over the folded name, which is the form a lookup compares — so a hash
// that disagrees is a file no driver trusting the field will find.
let computed = name_hash(&self.upcase.fold(&units));
if computed != stream.name_hash {
deviations.record(
at,
ReadError::NameHashMismatch {
index,
computed,
stored: stream.name_hash,
},
)?;
}
let (name, well_formed) = decode_utf16(&units);
if !well_formed {
deviations.record(at, ReadError::IllFormedName { index })?;
}
if is_hostile_component(&name) {
deviations.record(at, ReadError::HostileName { index })?;
// Never handed back, whatever the policy: a path built by joining this onto its
// directory's would leave the tree.
return Ok(None);
}
// What the format reserves in a name, which the writer refuses in one.
if let Some(ch) = String::from_utf8_lossy(&name)
.chars()
.find(|&ch| is_reserved_name_char(ch))
{
deviations.record(
at,
ReadError::ReservedCharacter {
index,
code: u32::from(ch),
},
)?;
}
let node = self.node_of(&file, &stream, index, deviations)?;
Ok(Some(Entry { name, node }))
}
/// The node a file entry and its stream extension describe, with every field the format
/// bounds held to its bound and what is incoherent about the pair reported.
///
/// Each length a deviation is reported for is also *clamped* to what the volume could
/// hold. That is what makes the bounds bounds rather than remarks: a lenient read passes
/// over every deviation here, and a length nothing narrowed would still drive the read
/// that follows it.
fn node_of(
&mut self,
file: &FileEntry,
stream: &StreamExtensionEntry,
index: u32,
deviations: &mut OnDeviation<'_>,
) -> Result<Node, ReadError> {
let at = Location::at_entry(index);
let is_dir = file.attributes.contains(FileAttributes::DIRECTORY);
// Eleven of the sixteen attribute bits are reserved, and a conformant volume has all
// eleven clear.
let reserved = file.attributes.bits() & !FileAttributes::DEFINED.bits();
if reserved != 0 {
deviations.record(
at,
ReadError::ReservedAttributes {
index,
bits: reserved,
},
)?;
}
self.check_times(file, index, deviations)?;
// The format states the constraint in both directions — a first cluster of zero means
// the stream owns nothing, and the only length a stream owning nothing has is zero —
// so both directions are held to it. Neither is visible downstream on its own: a
// length with no cluster reads as a file whose bytes cannot be reached, and a cluster
// with no length reads as an ordinary empty file whose allocation a scan meets much
// later, as clusters in use and reached by nothing.
let unallocated = stream.first_cluster == 0 || stream.data_length == 0;
let storage = if unallocated {
if stream.first_cluster == 0 && stream.data_length != 0 {
deviations.record(
at,
ReadError::StreamWithoutAllocation {
index,
declared: stream.data_length,
},
)?;
}
if stream.first_cluster != 0 && stream.data_length == 0 {
deviations.record(
at,
ReadError::AllocationWithoutLength {
index,
first_cluster: stream.first_cluster,
},
)?;
}
if is_dir {
// A directory needs a cluster to hold even the byte that ends it, so one with
// no allocation is a directory nothing can be in — including the entries a
// walk would otherwise report as absent.
deviations.record(at, ReadError::DirectoryWithoutAllocation { index })?;
}
Storage::None
} else {
if stream.no_fat_chain() {
Storage::Contiguous(stream.first_cluster)
} else {
Storage::Chain(stream.first_cluster)
}
};
// The flags are judged whatever the stream holds, once what it addresses has been. The
// writer's `stream_flags` rule, read from the other side: `AllocationPossible` is
// required on every stream extension, empty or not, and `NoFatChain` describes an
// allocation — it says the table holds no chain for these clusters — so set on a
// stream with none it describes nothing.
if stream.flags & SECONDARY_ALLOCATION_POSSIBLE == 0 {
deviations.record(at, ReadError::AllocationNotPossible { index })?;
}
if unallocated && stream.no_fat_chain() {
deviations.record(at, ReadError::NoFatChainWithoutAllocation { index })?;
}
let declared = self.bound_length(stream.data_length, is_dir, index, deviations)?;
// The two lengths are one number on a volume this crate wrote and routinely differ on
// a file a driver wrote. Which way a file's differ is what decides whether the pair is
// a state or a contradiction. A directory's are one number by the format's own rule,
// so either direction is a deviation, and the directory is read to its length.
let mut valid = stream.valid_data_length;
if is_dir && valid != declared {
deviations.record(
at,
ReadError::DirectoryValidLength {
index,
valid,
declared,
},
)?;
valid = declared;
} else if valid > declared {
deviations.record(at, ReadError::ValidLengthPastEnd { valid, declared })?;
valid = declared;
} else if valid < declared {
deviations.record(at, ReadError::ValidLengthTrails { valid, declared })?;
}
Ok(Node {
storage,
attributes: file.attributes,
data_length: declared,
valid_data_length: valid,
times: Some(times_of(file)),
})
}
/// `declared` held to every bound the format puts on a stream's length, with each one it
/// passes reported and the length narrowed to it.
///
/// Two bounds, and the second applies to directories alone.
///
/// The heap is the first. exFAT has no holes — a stream's bytes are its allocation — so a
/// length past the whole cluster heap is a length no volume could hold. Without it a
/// 64-bit field is an unbounded source of the zeros an unwritten tail reads as: set
/// `ValidDataLength` to zero and no cluster is ever touched, so the read is answered
/// entirely out of the number.
///
/// The format's directory cap is the second, and it is the bound that keeps reading a
/// directory a cost the format decides. Every slot the length covers is read, and neither
/// the entry cap nor the cycle check reaches it — a directory that produces no entries
/// never reaches the first, and a declared consecutive run has no chain to repeat.
///
/// Neither refuses a volume any conformant implementation writes: the whole heap is the
/// most anything in it could occupy, and the writer here holds every directory to the same
/// cap.
fn bound_length(
&self,
declared: u64,
is_dir: bool,
index: u32,
deviations: &mut OnDeviation<'_>,
) -> Result<u64, ReadError> {
let at = Location::at_entry(index);
let mut declared = declared;
let heap = self.layout.heap_bytes();
if declared > heap {
deviations.record(
at,
ReadError::StreamPastHeap {
declared,
limit: heap,
},
)?;
declared = heap;
}
if is_dir {
if declared > MAX_DIRECTORY_BYTES {
deviations.record(
at,
ReadError::DirectoryTooLong {
index,
declared,
limit: MAX_DIRECTORY_BYTES,
},
)?;
declared = MAX_DIRECTORY_BYTES;
}
// A directory's length is the entire size of its allocation, which makes it whole
// clusters on every conformant volume. It is enumerated by the clusters it covers
// either way, so a length that is not one is neither honoured nor meaningful.
let bytes_per_cluster = self.layout.bytes_per_cluster;
if !declared.is_multiple_of(u64::from(bytes_per_cluster)) {
deviations.record(
at,
ReadError::DirectoryLengthNotClusters {
index,
declared,
bytes_per_cluster,
},
)?;
}
}
Ok(declared)
}
/// Judge the three times a file entry records, each against the range the encoding
/// defines for its fields.
///
/// A read hands back the instant the arithmetic reaches, which is what every driver does
/// and what [`DosTimestamp::decode`](crate::DosTimestamp::decode) documents deferring.
/// This is the site it defers to: month zero, day 31 of February, a twenty-fifth hour and
/// a hundredths byte past 199 are each a field no encoder produces and an image may carry.
///
/// The access time has no hundredths byte, which is the whole of what "granular to two
/// seconds" means for it, so zero is what is judged beside it.
fn check_times(
&self,
file: &FileEntry,
index: u32,
deviations: &mut OnDeviation<'_>,
) -> Result<(), ReadError> {
let at = Location::at_entry(index);
for (field, packed, tenth) in [
("creation time", file.create, file.create_tenth),
("modification time", file.modify, file.modify_tenth),
("access time", file.access, 0),
] {
if !unpack_timestamp(packed, tenth).is_well_formed() {
deviations.record(at, ReadError::MalformedTimestamp { index, field })?;
}
}
Ok(())
}
/// The node at `path`, resolved from the root.
///
/// Names are compared the way every driver reading this volume compares them: through the
/// volume's own up-case table. So a lookup for `readme.txt` finds a `README.TXT` the volume
/// holds, and finds it by the same rule that made the pair unwritable in one directory.
///
/// A `..` component ascends to the directory the resolution descended from, staying at the
/// root where there is nothing to ascend to — so nothing outside the volume can be named.
/// It is an ascent and not a lookup, this format storing no entry of that name in any
/// directory.
///
/// Each directory is read only as far as the name it resolves and nothing is gathered, so
/// [`Limits::max_walk_entries`] does not govern a lookup, and an entry set past the name
/// is not read. A name found only through the up-case table reads on to the directory's
/// end, since an exact match further on would be the one returned.
///
/// # Errors
///
/// [`ReadError::NotFound`] where no such path exists, [`ReadError::NotADirectory`] where
/// one traverses through something that is not a directory, and the errors of reading
/// each directory as far as the name, which are [`read_dir`](Self::read_dir)'s.
pub fn lookup(&mut self, path: &[u8]) -> Result<Node, ReadError> {
crate::resolve::drive(self, path, true)
}
/// `name` as the volume's own table folds it, which is the form two names are one name in.
///
/// A name that is not UTF-8 has no UTF-16 form, and so folds to nothing rather than to a
/// replacement character that would collide with every other such name.
fn fold_name(&self, name: &[u8]) -> Vec<u16> {
match core::str::from_utf8(name) {
Ok(text) => self.upcase.fold(&text.encode_utf16().collect::<Vec<_>>()),
Err(_) => Vec::new(),
}
}
// -- file contents ------------------------------------------------------------------
/// Fill `buf` from `offset` in a regular file, returning how many bytes were placed.
///
/// A short fill means the file ends there. A node that is not a regular file holds no bytes
/// and yields none: a directory's storage is its entries, and handing those back as file
/// contents would be a directory entry read as data.
///
/// Bytes past the stream's written length read as zeros. That region is allocated and was
/// never written, so what is on the medium there is whatever it last held — and handing
/// that back would leak it. Every driver answers the same way, and the discrepancy that
/// creates the region is reported when the entry is read.
///
/// # Errors
///
/// [`ReadError`] variants where the stream cannot be followed.
pub fn read_into(
&mut self,
node: &Node,
offset: u64,
buf: &mut [u8],
) -> Result<usize, ReadError> {
if node.is_dir() {
return Ok(0);
}
let size = node.data_length;
if offset >= size || buf.is_empty() {
return Ok(0);
}
let bytes_per_cluster = u64::from(self.layout.bytes_per_cluster);
let want = buf
.len()
.min(usize::try_from(size - offset).unwrap_or(usize::MAX));
let mut done = 0usize;
while done < want {
let at = offset + done as u64;
if at >= node.valid_data_length {
// The tail nothing wrote. Zeroed rather than read, and in one step rather than
// cluster by cluster: what is there is not the file's.
buf[done..want].fill(0);
return Ok(want);
}
let take = (want - done)
.min(usize::try_from(node.valid_data_length - at).unwrap_or(usize::MAX));
let index = at / bytes_per_cluster;
let within = (at % bytes_per_cluster) as usize;
let Some(cluster) = self.stream_cluster(node.storage, index)? else {
// The allocation ran out with bytes still to come, which is the length and the
// allocation disagreeing.
return Err(ReadError::StreamTooShort {
start: node.storage.first_cluster().unwrap_or(0),
declared: size,
held: index * bytes_per_cluster,
});
};
let bytes = self.read_cluster(cluster)?;
let take = take.min(bytes.len() - within);
buf[done..done + take].copy_from_slice(&bytes[within..within + take]);
done += take;
}
Ok(done)
}
/// A file's length as a whole-file read sees it: the length its entry records, held to
/// [`Limits::max_file_bytes`].
///
/// Every whole-file form goes through this, so the cap governs what a read hands back and
/// what a stream into a caller's writer produces alike. Nothing accumulates in the second
/// of those, which is exactly why it needs the cap named here: what it *writes* follows
/// the length the image declares, and an unwritten tail reads as zeros without a cluster
/// being touched.
///
/// # Errors
///
/// [`ReadError::FileTooLarge`] if the length exceeds the cap.
fn whole_file_len(&self, node: &Node) -> Result<u64, ReadError> {
if node.data_length > self.limits.max_file_bytes {
return Err(ReadError::FileTooLarge {
size: node.data_length,
limit: self.limits.max_file_bytes,
});
}
Ok(node.data_length)
}
/// Stream a file's whole contents into `out`, returning how many bytes were written.
///
/// Nothing accumulates, so a file of any size costs one cluster of working memory.
///
/// # Errors
///
/// [`ReadError::FileTooLarge`] where the length exceeds [`Limits::max_file_bytes`],
/// [`ReadError`] variants where the stream cannot be followed,
/// [`ReadError::StreamTooShort`] where it ends before the length the entry records, and
/// whatever `out` returns.
pub fn read_data_to(&mut self, node: &Node, mut out: impl Write) -> Result<u64, ReadError> {
if node.is_dir() {
return Ok(0);
}
let size = self.whole_file_len(node)?;
let mut buf = vec![0u8; self.layout.bytes_per_cluster as usize];
let mut done = 0u64;
while done < size {
let want = buf
.len()
.min(usize::try_from(size - done).unwrap_or(usize::MAX));
let got = self.read_into(node, done, &mut buf[..want])?;
if got == 0 {
return Err(ReadError::StreamTooShort {
start: node.storage.first_cluster().unwrap_or(0),
declared: size,
held: done,
});
}
out.write_all(&buf[..got])?;
done += got as u64;
}
Ok(done)
}
/// A file's whole contents.
///
/// The buffer grows as bytes arrive rather than being sized from the length field up front,
/// so a crafted length costs nothing beyond the bytes the volume actually holds.
///
/// # Errors
///
/// [`ReadError::FileTooLarge`] where the length exceeds [`Limits::max_file_bytes`], and the
/// errors of [`read_data_to`](Self::read_data_to).
pub fn read_data(&mut self, node: &Node) -> Result<Vec<u8>, ReadError> {
let mut out = Vec::new();
self.read_data_to(node, &mut out)?;
Ok(out)
}
// -- walking ------------------------------------------------------------------------
/// Every name in the tree, depth-first, a parent before its children.
///
/// # Errors
///
/// [`ReadError`] variants if any directory along the walk cannot be read,
/// [`ReadError::RepeatedDirectory`] under [`ReadPolicy::Strict`] if an entry names a
/// directory the tree already reaches, and [`ReadError::WalkTooLarge`] if the tree holds
/// more names than the bounds allow.
pub fn walk(&mut self) -> Result<Vec<WalkEntry>, ReadError> {
let mut out = Vec::new();
self.walk_with::<ReadError>(|_, entry| {
out.push(entry);
Ok(())
})?;
Ok(out)
}
/// Walk the whole tree, handing each [`WalkEntry`] to `visit` as it is reached rather than
/// gathering them all first.
///
/// `visit` receives the reader itself, so it may read each entry's contents as it goes. The
/// error type is the consumer's, and the walk's own [`ReadError`]s convert into it, so a
/// consumer's failure and the volume's each reach the caller as themselves.
///
/// What the walk holds is the frontier — the names reached and not yet visited — rather
/// than the tree, so a tree far larger than memory is walked without accumulating it.
///
/// # Errors
///
/// Whatever `visit` returns, or the [`walk`](Self::walk) errors converted into it.
pub fn walk_with<E: From<ReadError>>(
&mut self,
mut visit: impl FnMut(&mut Self, WalkEntry) -> Result<(), E>,
) -> Result<(), E> {
crate::walk::drive(self, |reader, entry| visit(reader, entry))
}
/// The child entries of `node` in reverse name order, so a stack pops them in order.
fn walk_children(&mut self, node: &Node, prefix: &[u8]) -> Result<Vec<WalkEntry>, ReadError> {
let mut entries = self.read_dir(node)?;
entries.sort_by(|a, b| a.name.cmp(&b.name));
let mut children = Vec::new();
for e in entries.iter().rev() {
let path = crate::walk::child_path(prefix, &e.name)
.ok_or(ReadError::PathTooLong { limit: MAX_PATH })?;
children.push(WalkEntry { path, node: e.node });
}
Ok(children)
}
/// The most names the volume's own storage could hold, which bounds a walk regardless of
/// what a caller asked for.
///
/// Every name spends at least three 32-byte slots — a file entry, a stream extension, and a
/// name entry — and every slot is in a cluster, so the heap's slot count over three is a
/// hard ceiling that a well-formed tree can never reach.
fn max_names(&self) -> usize {
let slots = u64::from(self.layout.cluster_count) * u64::from(self.layout.bytes_per_cluster)
/ DIR_ENTRY_SIZE as u64;
usize::try_from(slots / 3).unwrap_or(usize::MAX)
}
// -- scanning -----------------------------------------------------------------------
/// Check the whole volume, collecting every deviation rather than stopping at the first.
///
/// This is the lenient reading made explicit: both boot regions, the allocation table's
/// reserved entries, every directory entry set, every name's hash, and every cluster the
/// tree occupies held against the allocation bitmap in both directions — a cluster in use
/// and reached by nothing, and a cluster reached and marked free.
///
/// The report is capped by [`Limits::max_findings`], and reaching the cap is itself
/// recorded: an absence of findings from a scan that stopped looking is not a verdict.
#[must_use]
pub fn scan(&mut self) -> ScanReport {
let mut findings = Findings::new(self.limits.max_findings);
findings.extend_from(&self.open_anomalies);
self.scan_table_head(&mut findings);
let reached = self.scan_tree(&mut findings);
// A scan its source failed did not look at what the failed reads held, so it cannot
// say what nothing reaches, as a walk cut short cannot.
if let Some(reached) = reached
&& !findings.met_source_failure()
{
self.scan_allocation(&mut findings, &reached);
}
findings.into_report(self.layout.bytes_per_sector)
}
/// The allocation table's two reserved entries, which the format fixes.
fn scan_table_head(&mut self, findings: &mut Findings<Anomaly>) {
for (index, expected) in [(0u32, FAT_ENTRY_MEDIA), (1, FAT_ENTRY_RESERVED)] {
let bytes_per_sector = u64::from(self.layout.bytes_per_sector);
let offset = u64::from(index) * 4;
let sector = u64::from(self.layout.fat_offset) + offset / bytes_per_sector;
let within = (offset % bytes_per_sector) as usize;
let found = match self.read_sectors(sector, 1) {
Ok(buf) if within + 4 <= buf.len() => get_u32(&buf, within),
Ok(_) => continue,
Err(e) => {
findings.push(e.anomaly());
return;
}
};
if found != expected {
findings.push(
ReadError::BadReservedEntry {
index,
found,
expected,
}
.anomaly(),
);
}
}
}
/// Walk the tree, collecting every deviation and the clusters it occupies.
///
/// Each name is reported by its [label](crate::walk::label), so a tree of any depth is
/// read whole.
///
/// `None` where the walk did not finish. What it did not reach is not evidence of anything,
/// and an allocation comparison over a partial traversal reads as a fact and is not one.
fn scan_tree(&mut self, findings: &mut Findings<Anomaly>) -> Option<ClusterSet> {
let mut reached = ClusterSet::new(self.layout.cluster_count);
// The three the format itself allocates. They are not in the tree and they are in the
// bitmap, so a comparison that did not claim them would call every one of their
// clusters lost.
let residents = [
(self.bitmap.first_cluster, self.bitmap.bytes),
(self.layout.upcase_cluster, self.layout.upcase_bytes),
(self.layout.first_cluster_of_root, self.root_bytes),
];
for (first, bytes) in residents {
self.claim_stream(Storage::Chain(first), bytes, &[], &mut reached, findings);
}
let mut visited = ClusterSet::new(self.layout.cluster_count);
visited.insert(self.layout.first_cluster_of_root);
let mut queue = vec![(Vec::new(), self.root())];
let mut names = 0usize;
let cap = self.limits.max_walk_entries.min(self.max_names());
while let Some((label, node)) = queue.pop() {
if findings.is_full() {
return None;
}
if node.is_dir() {
// The root's clusters were claimed above with the other residents; every other
// directory's are its own.
if !label.is_empty() {
self.claim_stream(
node.storage,
node.data_length,
&label,
&mut reached,
findings,
);
}
let mut allocations = Vec::new();
let mut deviations = OnDeviation::Collect {
findings,
allocations: &mut allocations,
};
let parsed = self.parse_dir(&node, &mut deviations);
// What the directory's benign entries allocate is the directory's to account
// for, whether or not the rest of it parsed.
for allocation in allocations {
let mut owner = label.clone();
owner.extend_from_slice(
format!(" (the allocation of entry {})", allocation.index).as_bytes(),
);
self.claim_stream(
allocation.storage,
allocation.bytes,
&owner,
&mut reached,
findings,
);
}
let entries = match parsed {
Ok(entries) => entries,
Err(e @ ReadError::WalkTooLarge { .. }) => {
findings.push(e.anomaly());
return None;
}
Err(e) => {
findings.push(e.anomaly());
continue;
}
};
for entry in entries {
names += 1;
if names > cap {
findings.push(ReadError::WalkTooLarge { limit: cap }.anomaly());
return None;
}
let child = crate::walk::label(&label, &entry.name);
let descend = match entry.node.storage {
Storage::None => false,
Storage::Contiguous(first) | Storage::Chain(first) => {
!entry.node.is_dir() || visited.insert(first)
}
};
if descend {
queue.push((child, entry.node));
}
}
} else {
self.claim_stream(
node.storage,
node.data_length,
&label,
&mut reached,
findings,
);
}
}
Some(reached)
}
/// Claim every cluster one stream occupies, reporting a cluster two streams both claim and
/// one the bitmap says is free.
///
/// A chained stream's table is held to its length besides. A chain running on past the
/// length is reported, and the clusters past it are claimed as well, so one another stream
/// also claims is named as cross-linked and none of them reads as lost.
fn claim_stream(
&mut self,
storage: Storage,
bytes: u64,
path: &[u8],
reached: &mut ClusterSet,
findings: &mut Findings<Anomaly>,
) {
let Some(start) = storage.first_cluster() else {
return;
};
let bytes_per_cluster = u64::from(self.layout.bytes_per_cluster);
let clusters = bytes.div_ceil(bytes_per_cluster.max(1));
let mut own = std::collections::HashSet::new();
let mut last = None;
for index in 0..clusters {
let cluster = match self.stream_cluster(storage, index) {
Ok(Some(cluster)) => cluster,
Ok(None) => {
findings.push(
ReadError::StreamTooShort {
start,
declared: bytes,
held: index * bytes_per_cluster,
}
.anomaly(),
);
return;
}
Err(e) => {
findings.push(named(e.anomaly(), path));
return;
}
};
if !self.claim_cluster(cluster, start, path, &mut own, reached, findings) {
return;
}
last = Some(cluster);
}
// Where the length ends, the table ends the chain. A `NoFatChain` stream has no chain
// in the table to end, and its run is exactly its length.
let (Storage::Chain(_), Some(mut cluster)) = (storage, last) else {
return;
};
let mut held = clusters;
loop {
let next = match self.next_cluster(cluster) {
Ok(Some(next)) => next,
Ok(None) => break,
Err(e) => {
findings.push(named(e.anomaly(), path));
break;
}
};
held += 1;
// A chain longer than the volume has clusters repeats one, which the claim below
// names; this bounds the walk if the report is too full to hold that.
if held > u64::from(self.layout.cluster_count) {
break;
}
if !self.claim_cluster(next, start, path, &mut own, reached, findings) {
break;
}
cluster = next;
}
if held > clusters {
findings.push(named(
ReadError::ChainPastLength {
start,
declared: bytes,
held: held.saturating_mul(bytes_per_cluster),
}
.anomaly(),
path,
));
}
}
/// Claim one cluster of the stream beginning at `start`, answering whether to go on: a
/// cluster already claimed, a bitmap that cannot be read, and a report that is full each
/// stop the stream's claim.
fn claim_cluster(
&mut self,
cluster: u32,
start: u32,
path: &[u8],
own: &mut std::collections::HashSet<u32>,
reached: &mut ClusterSet,
findings: &mut Findings<Anomaly>,
) -> bool {
if !reached.insert(cluster) {
// Whose claim is repeated decides what the finding says: a cluster this
// stream already stepped through is its own chain looping onto itself, and
// one another stream claimed is two streams sharing storage. Blaming
// "another stream" for a loop would send a reader hunting for a second file
// that does not exist.
let mut anomaly = ReadError::CrossLinkedCluster { cluster }.anomaly();
if own.contains(&cluster) {
anomaly.detail = format!(
"the chain from cluster {start} returns to cluster {cluster}, and a \
chain that loops never ends"
);
}
findings.push(named(anomaly, path));
return false;
}
own.insert(cluster);
match self.is_allocated(cluster) {
Ok(true) => {}
Ok(false) => findings.push(ReadError::ClusterNotAllocated { cluster }.anomaly()),
Err(e) => {
findings.push(e.anomaly());
return false;
}
}
!findings.is_full()
}
/// Count what the allocation bitmap says of every cluster: in use, and in use with no chain
/// in `reached` holding it. Without `reached`, nothing is counted lost.
fn census(&mut self, reached: Option<&ClusterSet>) -> Result<Census, ReadError> {
let mut census = Census {
in_use: 0,
lost: 0,
first_lost: None,
};
for n in 0..self.layout.cluster_count {
let cluster = FIRST_CLUSTER + n;
if self.is_allocated(cluster)? {
census.in_use += 1;
if reached.is_some_and(|reached| !reached.contains(cluster)) {
census.lost += 1;
census.first_lost.get_or_insert(cluster);
}
}
}
Ok(census)
}
/// Hold the allocation bitmap against what the walk reached, and how full the volume says
/// it is against how full it is.
fn scan_allocation(&mut self, findings: &mut Findings<Anomaly>, reached: &ClusterSet) {
let Census {
in_use,
lost,
first_lost,
} = match self.census(Some(reached)) {
Ok(census) => census,
Err(e) => {
findings.push(e.anomaly());
return;
}
};
if let Some(first) = first_lost {
findings.push(ReadError::LostClusters { count: lost, first }.anomaly());
}
// How full the volume says it is, against how full it is. Two remarks rather than one,
// because a value the field cannot hold and a value that is merely out of date are
// different things to be told: the field is a percentage or `0xFF` for "not known",
// and it sits outside the boot region's checksum precisely so a driver can keep it
// current — so a stale value is a number nobody was obliged to update, and a value
// between 100 and 255 is a byte that was never a percentage.
let stated = self.boot.percent_in_use;
let actual = percent_in_use(
u32::try_from(in_use).unwrap_or(u32::MAX),
self.layout.cluster_count,
);
if stated > PERCENT_IN_USE_MAX && stated != PERCENT_IN_USE_UNKNOWN {
findings.push(ReadError::PercentInUseOutOfRange { stated }.anomaly());
} else if stated != actual && stated != PERCENT_IN_USE_UNKNOWN {
findings.push(
ReadError::PercentInUseStale {
stated,
in_use,
clusters: self.layout.cluster_count,
actual,
}
.anomaly(),
);
}
}
}
/// The exFAT family's half of the shared path resolution: a directory listing to find a name
/// in, folded through the volume's own up-case table.
///
/// The link half of the trait is defaulted, because the format has none.
impl<R: Read + Seek> crate::resolve::Resolve for Reader<R> {
/// The node itself, for the reason the walk's frontier holds one: an exFAT [`Node`] is
/// five fixed-size fields, so a locator would cost as much as the node.
type Ancestor = Node;
type Node = Node;
type Error = ReadError;
fn root_node(&mut self) -> Result<Node, ReadError> {
Ok(self.root())
}
fn ancestor_of(&self, node: &Node) -> Node {
*node
}
fn node_at(&mut self, ancestor: Node) -> Result<Node, ReadError> {
Ok(ancestor)
}
fn is_directory(&self, node: &Node) -> bool {
node.is_dir()
}
fn find_name(&mut self, dir: &Node, name: &[u8]) -> Result<Option<Node>, ReadError> {
// One pass answers both questions: an exact match wins outright, and the first
// up-case-folded match is remembered in case none is exact. The needle folds
// once; each entry folds at most once, and only until a folded candidate is in
// hand — where two passes folded every name of the directory per lookup.
//
// The directory is streamed, as ext's is, and nothing is gathered: an exact match
// ends the read where it is, so neither the walk's cap nor an entry past the match
// can fail a lookup that found its name. A folded match reads on to the end, in case
// an exact one follows.
let folded = self.fold_name(name);
let policy = self.policy;
let mut exact = None;
let mut fallback = None;
self.parse_entries(dir, &mut OnDeviation::Policy(policy), |reader, e, _| {
if e.name == name {
exact = Some(e.node);
return Ok(ControlFlow::Break(()));
}
if fallback.is_none() && reader.fold_name(&e.name) == folded {
fallback = Some(e.node);
}
Ok(ControlFlow::Continue(()))
})?;
Ok(exact.or(fallback))
}
fn not_found(&self, path: &[u8]) -> ReadError {
ReadError::NotFound {
path: path.to_vec(),
}
}
fn not_a_directory(&self, _node: &Node, path: &[u8]) -> ReadError {
ReadError::NotADirectory {
path: path.to_vec(),
}
}
}
/// The exFAT family's half of the shared walk: a resolved entry on the frontier, a first
/// cluster as the cycle key, and a directory listing as the children.
impl<R: Read + Seek> crate::walk::Walk for Reader<R> {
/// A whole entry. Like FAT and unlike ext, there is nothing to re-read at the pop: an
/// exFAT [`Node`] is five fixed-size fields, so a locator would cost as much as the node.
type Pending = WalkEntry;
type Entry = WalkEntry;
/// The directory's first cluster.
type Key = u32;
type Error = ReadError;
fn cap(&mut self) -> usize {
self.limits.max_walk_entries.min(self.max_names())
}
fn seed(&mut self) -> Result<crate::walk::Seed<Self>, ReadError> {
let root = self.root();
let occupied = root.storage.first_cluster().into_iter().collect();
Ok((self.walk_children(&root, &[])?, occupied))
}
fn resolve(&mut self, pending: WalkEntry) -> Result<WalkEntry, ReadError> {
Ok(pending)
}
fn descend_key(&self, entry: &WalkEntry) -> Option<u32> {
entry
.node
.is_dir()
.then(|| entry.node.storage.first_cluster())?
}
fn children(&mut self, entry: &WalkEntry) -> Result<Vec<WalkEntry>, ReadError> {
self.walk_children(&entry.node, &entry.path)
}
fn repeated(&mut self, entry: &WalkEntry) -> Result<(), ReadError> {
let Some(cluster) = entry.node.storage.first_cluster() else {
return Ok(());
};
let err = ReadError::RepeatedDirectory { cluster };
if self.policy.is_fatal(err.anomaly().severity) {
return Err(err);
}
Ok(())
}
fn too_large(limit: usize) -> ReadError {
ReadError::WalkTooLarge { limit }
}
}
impl<R: Read + Seek> FsTree for Reader<R> {
type Node = Node;
fn family(&self) -> Family {
Family::ExFat
}
fn max_file_bytes(&self) -> u64 {
self.limits.max_file_bytes
}
fn walk_tree<E, F>(&mut self, mut visit: F) -> Result<(), E>
where
E: From<TreeError>,
F: FnMut(&mut Self, TreeEntry<Node>) -> Result<(), E>,
{
// The root has no name, so the walk does not reach it. Yielding it first under the
// empty path is what lets a sink apply the root's own metadata without a second way of
// asking for it — even though on this family there is none to apply, which the stat
// says by naming everything it filled in.
let root = self.root();
visit(self, TreeEntry::new(Vec::new(), NodeKind::Directory, root))?;
let outcome = self.walk_with::<WalkFail<E>>(|reader, entry| {
let kind = node_kind(&entry.node);
// No `shared`: the format has no second name for a node, so two paths are always
// two nodes.
visit(reader, TreeEntry::new(entry.path, kind, entry.node)).map_err(WalkFail::Visitor)
});
match outcome {
Ok(()) => Ok(()),
Err(WalkFail::Read(e)) => Err(E::from(TreeError::from(e))),
// Nothing above produces one: an exFAT node is a directory or a file, and both are
// kinds the shared frame has. The arm is here because the failure is the shared
// surface's rather than this family's.
Err(WalkFail::Tree(e)) => Err(E::from(e)),
Err(WalkFail::Visitor(e)) => Err(e),
}
}
fn stat(&mut self, node: &Node, synthesis: &Synthesis) -> Result<Attributes, TreeError> {
// An exFAT volume's whole record of a node is a read-only bit and two times, which is
// FAT's too — so what a read of one invents has a single home, beside the one that
// says what a write of one loses.
Ok(Attributes::from_read_only_bit(
synthesis,
node.is_dir(),
node.attributes.contains(FileAttributes::READ_ONLY),
node.times
.map(|t| (Some(t.access), t.modify, Some(t.create))),
))
}
fn read_bytes(&mut self, node: &Node, offset: u64, buf: &mut [u8]) -> Result<usize, TreeError> {
Ok(Reader::read_into(self, node, offset, buf)?)
}
fn link_target(&mut self, _node: &Node) -> Result<Vec<u8>, TreeError> {
// The format has no symbolic links, so no node a walk yields is one and this is reached
// only by a caller that did not look at the kind it was handed.
Err(TreeError::Malformed {
family: Family::ExFat,
detail: "an exFAT volume holds no symbolic links".to_string(),
})
}
fn find(&mut self, path: &[u8]) -> Result<Child<Node>, TreeError> {
let node = self.lookup(path).map_err(|e| match e {
ReadError::NotFound { .. } | ReadError::NotADirectory { .. } => TreeError::NotFound {
family: Family::ExFat,
path: path.to_vec(),
},
other => TreeError::from(other),
})?;
Ok(Child::new(
crate::tree::last_name(path),
node_kind(&node),
node,
))
}
fn list(&mut self, dir: &Node) -> Result<Vec<Child<Node>>, TreeError> {
if !dir.is_dir() {
return Err(crate::tree::not_a_directory(Family::ExFat));
}
let entries = self.read_dir(dir)?.into_iter().map(|e| (e.name, e.node));
Ok(crate::tree::listed(Family::ExFat, entries)?
.into_iter()
.map(|(name, node)| Child::new(name, node_kind(&node), node))
.collect())
}
/// In clusters: the volume's cluster count, and the clusters its allocation bitmap marks
/// free. The boot sector's percentage in use is a hint a driver keeps outside the boot
/// checksum and need not keep current, so it is not read.
fn usage(&mut self) -> Result<Usage, TreeError> {
let census = self.census(None)?;
let total = u64::from(self.layout.cluster_count);
Ok(Usage::new(
u64::from(self.layout.bytes_per_cluster),
total,
total - census.in_use,
))
}
}
/// What a node is, in the shared frame's words: the one projection a walk, a lookup and a
/// listing all go through. An exFAT node is a directory or a file and nothing else.
fn node_kind(node: &Node) -> NodeKind {
if node.is_dir() {
NodeKind::Directory
} else {
NodeKind::File {
size: node.data_length,
}
}
}
/// What the allocation bitmap says of every cluster, counted once for a scan and for a
/// volume's usage.
struct Census {
/// The clusters it marks in use.
in_use: u64,
/// Those that no chain the census was handed holds.
lost: u64,
/// The first of them.
first_lost: Option<u32>,
}
/// The shared walk failure over this family's read error.
type WalkFail<E> = crate::tree::WalkFail<ReadError, E>;
/// What makes `?` on a [`ReadError`] work inside a walk through the shared surface. Written per
/// family because a blanket implementation would collide with the reflexive one.
impl<E> From<ReadError> for WalkFail<E> {
fn from(err: ReadError) -> Self {
WalkFail::Read(err)
}
}
/// A directory entry set being assembled, slot by slot.
///
/// The raw bytes are kept because the set's checksum is over exactly them, and because a set
/// spans as many clusters as it needs — so the assembler is what carries a set across a cluster
/// boundary rather than the reader holding two clusters at once.
struct PendingSet {
/// The primary entry's index within its directory.
index: u32,
/// Entries the primary entry says follow it.
want: usize,
/// The set's bytes so far, the primary entry included.
bytes: Vec<u8>,
/// Whether the primary is a benign one this reader does not interpret, rather than a file.
benign: bool,
}
impl PendingSet {
/// A set opened by the primary entry `primary`, expecting `secondary` entries behind it.
fn new(index: u32, secondary: u8, primary: &[u8; DIR_ENTRY_SIZE], benign: bool) -> Self {
let want = usize::from(secondary);
let mut bytes = Vec::with_capacity((want + 1) * DIR_ENTRY_SIZE);
bytes.extend_from_slice(primary);
Self {
index,
want,
bytes,
benign,
}
}
/// Take one more entry.
fn push(&mut self, entry: &[u8; DIR_ENTRY_SIZE]) {
self.bytes.extend_from_slice(entry);
}
/// Entries taken so far, the file entry excepted.
fn have(&self) -> usize {
self.bytes.len() / DIR_ENTRY_SIZE - 1
}
/// Whether every entry the file entry declared has arrived.
fn is_complete(&self) -> bool {
self.have() >= self.want
}
}
/// A set over the volume's clusters, one bit each, kept a 64-cluster word at a time and only
/// for the words that hold a member.
///
/// Bounded by the count the boot sector records, which the geometry has already held to the
/// heap fitting inside the source — so the widest set this reaches is one bit per cluster of a
/// volume that exists — and costing what is in it below that: a directory's chain walk holds
/// the clusters of that chain, and a scan's set the clusters it reached.
///
/// This is the one answer to "which clusters has this been to", and every question of that
/// shape asks it: the chain a directory follows, the chain the root's length is measured from,
/// the directories a scan has descended into, and the clusters a scan has claimed. The domain
/// is the same in all four — a cluster number of this volume — and a second structure over it
/// would be a second answer to keep in step.
struct ClusterSet {
/// The set's words, by index: word `w` holds clusters `64 * w` to `64 * w + 63`. Only a
/// word holding a member is kept, so a set costs memory in proportion to what is in it
/// rather than to the volume: a directory of one cluster on a volume of four billion is
/// one word, where a word per 64 clusters of the volume would be half a gibibyte for every
/// directory read.
words: std::collections::HashMap<u32, u64>,
clusters: u32,
}
impl ClusterSet {
fn new(clusters: u32) -> Self {
Self {
words: std::collections::HashMap::new(),
clusters,
}
}
/// Whether `cluster` is one this set covers.
fn holds(&self, cluster: u32) -> bool {
cluster >= FIRST_CLUSTER && cluster - FIRST_CLUSTER < self.clusters
}
/// Add `cluster`, answering whether it was not already there.
fn insert(&mut self, cluster: u32) -> bool {
if !self.holds(cluster) {
return true;
}
let word = self.words.entry(cluster / 64).or_default();
let bit = 1u64 << (cluster % 64);
let was = *word & bit != 0;
*word |= bit;
!was
}
fn contains(&self, cluster: u32) -> bool {
self.holds(cluster)
&& self
.words
.get(&(cluster / 64))
.is_some_and(|word| word & (1u64 << (cluster % 64)) != 0)
}
}
/// The three instants a file entry records, with each one's recorded zone applied.
///
/// The packed words are a *local* time and the byte beside them says which locality, so the
/// instant is the decoded time less the offset. An entry recording no offset is read as UTC,
/// which is the only thing a reader can do with a time whose zone the volume did not write
/// down, and [`Times`] says which of the three that happened to.
fn times_of(file: &FileEntry) -> Times {
let at = |field: u32, tenth: u8, offset: u8| {
let minutes = utc_offset_minutes(offset);
let local = unpack_timestamp(field, tenth).decode();
let secs = local
.secs
.saturating_sub(i64::from(minutes.unwrap_or(0)) * 60);
(
Timestamp {
secs,
nanos: local.nanos,
},
minutes,
)
};
let (create, create_offset) = at(file.create, file.create_tenth, file.create_utc_offset);
let (modify, modify_offset) = at(file.modify, file.modify_tenth, file.modify_utc_offset);
// The access field has no hundredths byte, which is the whole of what "granular to two
// seconds" means for it.
let (access, access_offset) = at(file.access, 0, file.access_utc_offset);
Times {
create,
access,
modify,
create_offset,
access_offset,
modify_offset,
}
}
/// `units` as UTF-8, and whether they were well-formed UTF-16.
///
/// A unit standing for no character becomes U+FFFD rather than stopping the decode: a name that
/// cannot be spelled is still a name a lenient read must be able to enumerate, and the caller
/// reports the fact separately.
fn decode_utf16(units: &[u16]) -> (Vec<u8>, bool) {
let mut out = String::with_capacity(units.len());
let mut well_formed = true;
for ch in char::decode_utf16(units.iter().copied()) {
match ch {
Ok(ch) => out.push(ch),
Err(_) => {
well_formed = false;
out.push(char::REPLACEMENT_CHARACTER);
}
}
}
(out.into_bytes(), well_formed)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::exfat::ondisk::{
BOOT_CHECKSUM_SKIPS, RECOMMENDED_UPCASE_TABLE, SECONDARY_NO_FAT_CHAIN, UTC_OFFSET,
UTC_OFFSET_VALID, write_checksum_sector, write_upcase_table,
};
use crate::exfat::{FormatOptions, VolumeLabel, format};
use crate::fidelity::Property;
use crate::finding::Finding;
use crate::source::{Metadata, TreeBuilder};
use crate::time::DosTimestamp;
use std::io::Cursor;
/// An instant every field of an entry holds exactly, so nothing under test is also
/// exercising a rounding.
const TIME: Timestamp = Timestamp {
secs: 1_426_325_212,
nanos: 0,
};
/// The volume every case below is built on: 64 MiB, which convention formats at
/// four-kilobyte clusters and whose up-case table therefore spans two of them.
const VOLUME: u64 = 64 << 20;
fn meta(mode: u16) -> Metadata {
Metadata::new(mode, TIME)
}
/// A tree with a subdirectory, a file in it, an empty file, a file spanning more than one
/// cluster, and a name that needs more than one name entry.
fn tree() -> TreeBuilder {
TreeBuilder::new()
.directory(b"/DCIM".to_vec(), meta(0o755))
.file(b"/DCIM/READY.TXT".to_vec(), b"hello\n", meta(0o644))
.file(b"/DCIM/EMPTY.BIN".to_vec(), b"", meta(0o644))
.file(
b"/DCIM/A name long enough to need two entries.txt".to_vec(),
b"two",
meta(0o444),
)
.file(b"/BIG.BIN".to_vec(), vec![0x5a; 9_000], meta(0o644))
}
/// `source` formatted onto a volume of the usual size, as bytes.
fn image_of(source: TreeBuilder) -> Vec<u8> {
format(source, VOLUME, FormatOptions::new(0x1234_5678))
.expect("format")
.into_bytes()
}
/// The tree above, formatted.
fn image() -> Vec<u8> {
image_of(tree())
}
/// A reader over `bytes`, opened strictly.
fn reader(bytes: &[u8]) -> Reader<Cursor<&[u8]>> {
Reader::open(Cursor::new(bytes)).expect("open")
}
/// A reader over `bytes`, opened leniently, so a case can scan an image a strict read
/// would refuse.
fn lenient(bytes: &[u8]) -> Reader<Cursor<&[u8]>> {
Reader::open_with(
Cursor::new(bytes),
&OpenOptions::new().policy(ReadPolicy::Lenient),
)
.expect("open leniently")
}
/// The failure opening `bytes` under `policy`.
///
/// A helper rather than `expect_err`, since a [`Reader`] holds a source and is not a
/// value to render — so the `Err` side is unwrapped by matching rather than by requiring
/// the `Ok` side to be printable.
fn open_err(bytes: &[u8], policy: ReadPolicy) -> ReadError {
match Reader::open_with(Cursor::new(bytes), &OpenOptions::new().policy(policy)) {
Err(e) => e,
Ok(_) => panic!("the image was expected to be refused and was not"),
}
}
/// The root directory's entries, read strictly.
fn root_entries(bytes: &[u8]) -> Result<Vec<Entry>, ReadError> {
let mut r = reader(bytes);
let root = r.root();
r.read_dir(&root)
}
/// The root directory's entries, read leniently, so a deviation is collected rather than
/// fatal.
fn root_entries_lenient(bytes: &[u8]) -> Vec<Entry> {
let mut r = lenient(bytes);
let root = r.root();
r.read_dir(&root).expect("a lenient read carries on")
}
/// Every path a walk reaches, in the order it yields them.
fn paths(bytes: &[u8]) -> Vec<Vec<u8>> {
reader(bytes)
.walk()
.expect("walk")
.into_iter()
.map(|e| e.path)
.collect()
}
/// Every path a lenient walk reaches, for a case whose image a strict one refuses.
fn lenient_paths(bytes: &[u8]) -> Vec<Vec<u8>> {
lenient(bytes)
.walk()
.expect("a lenient walk")
.into_iter()
.map(|e| e.path)
.collect()
}
/// The byte offset of cluster `n`, for a case that patches an image.
fn cluster_at(bytes: &[u8], n: u32) -> usize {
reader(bytes)
.layout()
.cluster_start_byte(n)
.expect("a cluster the volume has") as usize
}
/// Where the entry set naming `name` begins, as a byte offset into `bytes`.
///
/// Found by walking the directory's slots rather than computed, so a case that patches a
/// set stays correct when the order a directory is written in changes.
fn set_at(bytes: &[u8], dir_cluster: u32, name: &str) -> usize {
let want: Vec<u16> = name.encode_utf16().collect();
let at = cluster_at(bytes, dir_cluster);
let cluster = reader(bytes).layout().bytes_per_cluster as usize;
let mut slot = 0;
while (slot + 1) * DIR_ENTRY_SIZE <= cluster {
let start = at + slot * DIR_ENTRY_SIZE;
let entry = &bytes[start..start + DIR_ENTRY_SIZE];
if EntryType(entry[0]) == EntryType::FILE {
let secondary = usize::from(entry[1]);
let stream = &bytes[start + DIR_ENTRY_SIZE..start + 2 * DIR_ENTRY_SIZE];
let length = usize::from(stream[3]);
let mut units = Vec::new();
for n in 2..=secondary {
let e = &bytes[start + n * DIR_ENTRY_SIZE..start + (n + 1) * DIR_ENTRY_SIZE];
if EntryType(e[0]) != EntryType::FILE_NAME {
continue;
}
for pair in e[2..].as_chunks::<2>().0 {
units.push(u16::from_le_bytes(*pair));
}
}
units.truncate(length);
if units == want {
return start;
}
slot += secondary + 1;
continue;
}
slot += 1;
}
panic!("no entry set names {name} in cluster {dir_cluster}");
}
/// Recompute and patch the set checksum of the set at `at`, so a case that changes one
/// field of a set is testing that field rather than the checksum.
fn refresh_set_checksum(bytes: &mut [u8], at: usize) {
let slots = usize::from(bytes[at + 1]) + 1;
let checksum = entry_set_checksum(&bytes[at..at + slots * DIR_ENTRY_SIZE]);
bytes[at + 2..at + 4].copy_from_slice(&checksum.to_le_bytes());
}
/// Recompute and patch the checksum of the boot region beginning at `sector`, so a case
/// that changes a boot field is testing that field rather than the checksum.
///
/// The sector size comes from the main boot sector's own shift, which is where a reader
/// gets it and the one field this cannot be told.
fn refresh_boot_checksum(bytes: &mut [u8], sector: u64) {
let size = 1usize << bytes[108];
let at = sector as usize * size;
let covered = boot_checksum(&bytes[at..at + 11 * size]);
write_checksum_sector(&mut bytes[at + 11 * size..at + 12 * size], covered);
}
/// Every finding a lenient scan of `bytes` reports.
fn scan_of(bytes: &[u8]) -> Vec<Finding> {
lenient(bytes).scan().to_report().findings().to_vec()
}
// -- the round trip -----------------------------------------------------------------
/// A directory of ten files, `n0.txt` to `n9.txt`, which the writer lays down in that
/// order.
fn ten_names() -> Vec<u8> {
let mut tree = TreeBuilder::new().directory(b"/d".to_vec(), meta(0o755));
for i in 0..10 {
tree = tree.file(format!("/d/n{i}.txt").into_bytes(), b"x", meta(0o644));
}
image_of(tree)
}
#[test]
fn a_volume_is_read_inside_its_region_and_refused_where_it_runs_past_the_end() {
// A volume a mebibyte into a disk, and a neighbour's bytes after it.
const BASE: u64 = 1 << 20;
let image = image();
let len = image.len() as u64;
let mut disk = vec![0u8; BASE as usize];
disk.extend_from_slice(&image);
disk.extend(vec![0xee; 1 << 20]);
// In a partition a sector short of the volume, the volume records more sectors than
// its source holds, which is a boot sector describing no volume here, however leniently
// it is read. Without the partition's end, the neighbour's bytes would make up the
// difference.
for policy in [ReadPolicy::Strict, ReadPolicy::Lenient] {
match Reader::open_with(
Cursor::new(disk.as_slice()),
&OpenOptions::new().base(BASE).len(len - 512).policy(policy),
) {
Err(ReadError::BadBootSector { detail }) => {
assert!(detail.contains("the source does not hold"), "{detail}");
}
Err(e) => panic!("expected the volume's length refused, got {e}"),
Ok(_) => panic!("a volume longer than its region opened"),
}
}
// The partition that holds it whole, and the disk with no partition named, both read
// the volume as it was written.
for options in [
OpenOptions::new().base(BASE).len(len),
OpenOptions::new().base(BASE),
] {
let mut r = Reader::open_with(Cursor::new(disk.as_slice()), &options).expect("open");
assert!(r.scan().is_clean());
let file = r.lookup(b"/DCIM/READY.TXT").expect("the file");
assert_eq!(r.read_data(&file).expect("its bytes"), b"hello\n");
}
}
#[test]
fn a_lookup_reads_a_directory_only_as_far_as_its_name() {
// A lookup streams the directory as ext's does: it gathers nothing, so the cap on
// what a walk gathers is not its business, and a directory longer than the cap still
// resolves every name in it.
let bytes = ten_names();
let mut r = Reader::open_with(
Cursor::new(bytes.as_slice()),
&OpenOptions::new().limits(Limits::new().max_walk_entries(3)),
)
.expect("open");
let dir = r.lookup(b"/d").expect("the directory");
assert!(matches!(
r.read_dir(&dir),
Err(ReadError::WalkTooLarge { limit: 3 })
));
for name in [&b"/d/n0.txt"[..], b"/d/n9.txt", b"/D/N9.TXT"] {
assert!(
r.lookup(name).is_ok(),
"{} is past the cap and found",
String::from_utf8_lossy(name)
);
}
}
#[test]
fn an_entry_past_the_match_does_not_refuse_a_strict_lookup() {
// The lookup stops at its name, so an entry set it never reads cannot refuse it. One
// it does read on the way still does, as a listing of the directory does.
let mut bytes = ten_names();
let dir = reader(&bytes)
.lookup(b"/d")
.expect("look up")
.storage
.first_cluster()
.expect("a directory has an allocation");
let set = set_at(&bytes, dir, "n5.txt");
bytes[set + 2] ^= 0xff;
let mut r = reader(&bytes);
let dir = r.lookup(b"/d").expect("the directory");
assert!(matches!(
r.read_dir(&dir),
Err(ReadError::SetChecksumMismatch { .. })
));
assert!(r.lookup(b"/d/n2.txt").is_ok(), "before the bad set");
assert!(
matches!(
r.lookup(b"/d/n8.txt"),
Err(ReadError::SetChecksumMismatch { .. })
),
"past it, the lookup reads it on the way"
);
// A name matched through the up-case table reads on to the end in case an exact one
// follows, so it meets the bad set too.
assert!(r.lookup(b"/d/N2.TXT").is_err());
}
#[test]
fn a_tree_written_by_this_crate_reads_back_whole() {
// The claim the whole family rests on: a format followed by a strict open is a round
// trip. Every path, in order, and every byte of every file.
let bytes = image();
assert_eq!(
paths(&bytes),
vec![
b"/BIG.BIN".to_vec(),
b"/DCIM".to_vec(),
b"/DCIM/A name long enough to need two entries.txt".to_vec(),
b"/DCIM/EMPTY.BIN".to_vec(),
b"/DCIM/READY.TXT".to_vec(),
]
);
let mut r = reader(&bytes);
for (path, contents) in [
(&b"/DCIM/READY.TXT"[..], &b"hello\n"[..]),
(b"/DCIM/EMPTY.BIN", b""),
(b"/DCIM/A name long enough to need two entries.txt", b"two"),
] {
let node = r.lookup(path).expect("look the path up");
assert_eq!(r.read_data(&node).expect("read"), contents, "{path:?}");
}
let big = r.lookup(b"/BIG.BIN").expect("look /BIG.BIN up");
assert_eq!(r.read_data(&big).expect("read"), vec![0x5a; 9_000]);
assert!(r.scan().is_clean(), "{}", r.scan().to_report().to_table());
}
#[test]
fn a_layout_read_back_is_the_layout_that_was_planned() {
// Recovered rather than recomputed, which is what makes the two halves of the family
// one thing: the four fields no boot sector records are what the root directory said,
// and they agree with what the planner placed.
let image = format(tree(), VOLUME, FormatOptions::new(0x1234_5678)).expect("format");
let planned = *image.layout();
let bytes = image.into_bytes();
assert_eq!(reader(&bytes).layout(), &planned);
}
#[test]
fn the_times_an_entry_records_come_back_as_the_instants_that_went_in() {
let bytes = image();
let mut r = reader(&bytes);
let node = r.lookup(b"/DCIM/READY.TXT").expect("look up");
let times = node.times.expect("a file has times");
assert_eq!(times.modify, TIME);
assert_eq!(times.access, TIME);
// A volume this crate writes records that its times are UTC rather than leaving a
// reader to guess, which is a zero offset *recorded* and not an absent one.
assert_eq!(times.modify_offset, Some(0));
assert_eq!(times.access_offset, Some(0));
assert_eq!(times.create_offset, Some(0));
// The root has no entry, so it has no times at all rather than invented ones.
assert_eq!(r.root().times, None);
}
#[test]
fn a_zone_offset_moves_the_instant_and_an_absent_one_reads_as_utc() {
// The field FAT does not have. The packed words are a local time, so the same words
// beside two offsets are two instants — and a reader that ignored the byte would
// report a photograph taken in Auckland as having been taken thirteen hours earlier.
let mut file = FileEntry::read_from(&{
let mut buf = [0u8; DIR_ENTRY_SIZE];
buf[0] = EntryType::FILE.0;
buf
})
.expect("a file entry");
let stamp = DosTimestamp::encode(TIME).expect("in range");
file.create = super::super::ondisk::pack_timestamp(stamp);
file.modify = file.create;
file.access = file.create;
file.create_tenth = stamp.tenth;
file.modify_tenth = stamp.tenth;
// UTC recorded.
file.create_utc_offset = UTC_OFFSET;
file.modify_utc_offset = UTC_OFFSET;
file.access_utc_offset = UTC_OFFSET;
assert_eq!(times_of(&file).modify, TIME);
// One hour east: the local words say the same thing and the instant is an hour
// earlier.
file.modify_utc_offset = UTC_OFFSET_VALID | 0x04;
let east = times_of(&file);
assert_eq!(east.modify.secs, TIME.secs - 3600);
assert_eq!(east.modify_offset, Some(60));
// Nothing recorded: read as UTC, and said to have been unqualified.
file.modify_utc_offset = 0;
let bare = times_of(&file);
assert_eq!(bare.modify, TIME);
assert_eq!(bare.modify_offset, None);
}
#[test]
fn a_volume_answers_to_the_name_its_root_directory_records() {
let labelled = format(
TreeBuilder::new(),
VOLUME,
FormatOptions::new(1).label(VolumeLabel::new("CARD").expect("a label")),
)
.expect("format")
.into_bytes();
assert_eq!(reader(&labelled).volume_label(), Some(&b"CARD"[..]));
// A volume with no name carries the entry all the same, with a character count of
// zero — which is the volume having no name rather than an entry to report.
let unnamed = image_of(TreeBuilder::new());
assert_eq!(reader(&unnamed).volume_label(), None);
}
#[test]
fn a_label_field_the_reader_cannot_read_as_a_name_is_named_rather_than_invented() {
// `CharacterCount` runs 0 to 11 and the field is eleven units wide, so a larger count
// names units that are not there. `libexfat` writes one and `fsck.exfat` calls the
// volume clean, so this is a volume a reader meets.
let mut bytes = image_of(TreeBuilder::new());
let root = cluster_at(&bytes, reader(&bytes).layout().first_cluster_of_root);
assert_eq!(bytes[root], EntryType::VOLUME_LABEL.0, "the first slot");
bytes[root + 1] = 200;
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(
matches!(
err,
ReadError::LabelTooLong {
count: 200,
limit: MAX_LABEL_UNITS
}
),
"{err}"
);
// And the half that makes the clamp worth reporting rather than merely doing. The
// field of an unnamed volume is eleven zero units, so a reader that clamped in
// silence would turn "no name" into a name of eleven NULs — a name this crate's
// writer refuses to produce, because a label holding one is a label every
// implementation that reads the field as terminated would read differently.
let mut r = lenient(&bytes);
assert_eq!(r.volume_label(), None);
let details: Vec<_> = r
.scan()
.to_report()
.findings()
.iter()
.map(|f| f.detail.clone())
.collect();
assert!(
details.iter().any(|d| d.contains("carries a NUL")),
"{details:#?}"
);
}
#[test]
fn a_label_carrying_a_character_a_name_may_not_hold_is_named_and_handed_back() {
// A label reserves the characters a file name does. The writer refuses one, so this is
// a volume someone else wrote: a strict read refuses it, and a lenient one reads the
// label as the volume states it and reports the character.
let label = crate::exfat::VolumeLabel::new("AXB").expect("a label");
let mut bytes = format(
TreeBuilder::new(),
VOLUME,
FormatOptions::new(0x1234_5678).label(label),
)
.expect("format")
.into_bytes();
let root = cluster_at(&bytes, reader(&bytes).layout().first_cluster_of_root);
assert_eq!(bytes[root], EntryType::VOLUME_LABEL.0, "the first slot");
// The label's units begin at byte 2 of the entry, two bytes each; the second is `X`.
bytes[root + 4..root + 6].copy_from_slice(&u16::from(b'/').to_le_bytes());
assert!(matches!(
open_err(&bytes, ReadPolicy::Strict),
ReadError::LabelForbiddenCharacter { ch: '/' }
));
let mut r = lenient(&bytes);
assert_eq!(r.volume_label(), Some(&b"A/B"[..]));
assert!(
r.scan()
.anomalies()
.iter()
.any(|a| a.detail.contains("'/'") && a.severity == Severity::Conformance)
);
}
#[test]
fn a_bitmap_entry_contradicting_a_one_table_volume_is_named() {
// The identifier says which of two bitmaps an entry is, and a volume with one
// allocation table has one bitmap: the first. The bits above it are reserved. The
// entry carries no checksum, so the change is the whole of the case.
let bytes = image_of(TreeBuilder::new());
let root_cluster = reader(&bytes).layout().first_cluster_of_root;
let root = cluster_at(&bytes, root_cluster);
let slots = reader(&bytes).layout().bytes_per_cluster as usize / DIR_ENTRY_SIZE;
let entry = (0..slots)
.map(|n| root + n * DIR_ENTRY_SIZE)
.find(|at| bytes[*at] == EntryType::ALLOCATION_BITMAP.0)
.expect("the bitmap's entry");
assert_eq!(bytes[entry + 1], 0, "the writer names the first bitmap");
for (flags, what) in [(0x01u8, "the second bitmap"), (0x80, "a reserved bit")] {
let mut bytes = bytes.clone();
bytes[entry + 1] = flags;
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(
match flags {
0x01 => matches!(err, ReadError::SecondBitmap),
_ => matches!(err, ReadError::BitmapReservedFlags { bits: 0x80 }),
},
"{what}: {err}"
);
let report = lenient(&bytes).scan();
assert!(
report
.anomalies()
.iter()
.any(|a| a.category == Category::AllocationBitmap
&& a.severity == Severity::Conformance),
"{what}: {:?}",
report.anomalies()
);
}
}
#[test]
fn an_empty_streams_flags_are_held_to_the_format_as_an_allocated_ones_are() {
// The writer's `stream_flags` rule from the reading side: every stream extension
// declares an allocation possible, and only one that addresses clusters declares them
// contiguous. An empty file's stream addresses none, so neither half was judged there.
use super::super::ondisk::SECONDARY_NO_FAT_CHAIN;
let bytes = image_of(TreeBuilder::new().file(b"/E.BIN".to_vec(), b"", meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "E.BIN");
let stream = stream_at(set);
assert_eq!(
bytes[stream + 1],
SECONDARY_ALLOCATION_POSSIBLE,
"the writer's shape for an empty stream"
);
for flags in [0, SECONDARY_ALLOCATION_POSSIBLE | SECONDARY_NO_FAT_CHAIN] {
let mut bytes = bytes.clone();
bytes[stream + 1] = flags;
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(
if flags == 0 {
matches!(err, ReadError::AllocationNotPossible { .. })
} else {
matches!(err, ReadError::NoFatChainWithoutAllocation { .. })
},
"flags {flags:#04x}: {err}"
);
assert_eq!(err.anomaly().severity, Severity::Conformance);
assert!(
!lenient(&bytes).scan().is_clean(),
"flags {flags:#04x}: a scan names it"
);
}
}
#[test]
fn what_an_open_holds_of_a_root_full_of_duplicates_is_the_callers_bound() {
// Every free slot of the root carries another copy of the bitmap's entry. Each is a
// deviation, and how many there are is the volume's to choose: a root as large as the
// heap allows holds hundreds of thousands. A lenient open reads past them all to the
// residents it needs, and keeps of them what the caller's bound allows, saying so.
let mut bytes = image_of(TreeBuilder::new());
let root = cluster_at(&bytes, reader(&bytes).layout().first_cluster_of_root);
let slots = reader(&bytes).layout().bytes_per_cluster as usize / DIR_ENTRY_SIZE;
let bitmap = (0..slots)
.map(|n| root + n * DIR_ENTRY_SIZE)
.find(|at| bytes[*at] == EntryType::ALLOCATION_BITMAP.0)
.expect("the bitmap's entry");
let entry = bytes[bitmap..bitmap + DIR_ENTRY_SIZE].to_vec();
let mut copies = 0;
for at in (0..slots).map(|n| root + n * DIR_ENTRY_SIZE) {
if bytes[at] == 0 {
bytes[at..at + DIR_ENTRY_SIZE].copy_from_slice(&entry);
copies += 1;
}
}
assert!(copies > 100, "the root is full of copies: {copies}");
let bounded = OpenOptions::new()
.policy(ReadPolicy::Lenient)
.limits(Limits::new().max_findings(1));
let mut r = match Reader::open_with(Cursor::new(&bytes[..]), &bounded) {
Ok(r) => r,
Err(e) => panic!("a lenient open reads past them: {e}"),
};
assert_eq!(
r.open_anomalies.held(),
(1, true),
"the open holds what the bound allows, and says it held no more"
);
let report = r.scan();
assert!(report.anomalies().len() <= 1);
assert!(
report.is_truncated(),
"the scan's report carries the truncation"
);
// A strict open refuses at the first, without reading on for a verdict already
// reached.
assert!(matches!(
open_err(&bytes, ReadPolicy::Strict),
ReadError::DuplicateRootEntry {
entry_type: "allocation bitmap",
..
}
));
}
#[test]
fn a_second_entry_of_a_kind_the_root_owns_one_of_is_named() {
// A reader takes the first of each and steps over the rest, so a second is storage
// nothing reads and a second answer to a question with one. The misplaced case — one
// of these outside the root — was reported and the duplicate inside it was not.
let bytes = image_of(TreeBuilder::new());
let root_cluster = reader(&bytes).layout().first_cluster_of_root;
let root = cluster_at(&bytes, root_cluster);
for (entry_type, named) in [
(EntryType::VOLUME_LABEL, "volume label"),
(EntryType::ALLOCATION_BITMAP, "allocation bitmap"),
(EntryType::UPCASE_TABLE, "up-case table"),
] {
let mut bytes = bytes.clone();
let slots = reader(&bytes).layout().bytes_per_cluster as usize / DIR_ENTRY_SIZE;
let source = (0..slots)
.map(|n| root + n * DIR_ENTRY_SIZE)
.find(|at| bytes[*at] == entry_type.0)
.expect("the entry the format writes");
let free = (0..slots)
.map(|n| root + n * DIR_ENTRY_SIZE)
.find(|at| bytes[*at] == 0)
.expect("a slot past the end marker");
let copy: Vec<u8> = bytes[source..source + DIR_ENTRY_SIZE].to_vec();
bytes[free..free + DIR_ENTRY_SIZE].copy_from_slice(©);
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(
matches!(err, ReadError::DuplicateRootEntry { entry_type: e, .. } if e == named),
"{named}: {err}"
);
}
}
#[test]
fn a_subdirectory_naming_the_roots_first_cluster_is_not_the_root() {
// Which directory is the root is carried on the node — it is the one the format
// records no entry for, which is what `times: None` says — rather than recomputed
// from where its bytes are. A subdirectory whose stream extension names the root's
// own first cluster is `Storage::Chain(root)` and is still a subdirectory, so an
// entry the format defines one place for is misplaced inside it like any other.
let mut bytes = image();
let root_cluster = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root_cluster, "DCIM");
let stream = stream_at(set);
bytes[stream + 1] &= !SECONDARY_NO_FAT_CHAIN;
bytes[stream + 20..stream + 24].copy_from_slice(&root_cluster.to_le_bytes());
refresh_set_checksum(&mut bytes, set);
let mut r = lenient(&bytes);
let node = r.lookup(b"/DCIM").expect("look up");
assert_eq!(node.storage, Storage::Chain(root_cluster));
let err = {
let mut strict = reader(&bytes);
let node = strict.lookup(b"/DCIM").expect("look up");
strict
.read_dir(&node)
.expect_err("the root's own entries are misplaced in it")
};
assert!(matches!(err, ReadError::MisplacedRootEntry { .. }), "{err}");
}
#[test]
fn a_lookup_finds_a_name_through_the_folding_the_volume_carries() {
// exFAT lookups are case-insensitive, and what "case" means is the volume's own
// table. So the reader finds the entry by the same rule that made `README` and
// `readme` a pair no directory could hold.
let bytes = image();
let mut r = reader(&bytes);
assert!(r.lookup(b"/dcim/ready.txt").is_ok());
assert!(r.lookup(b"/DCIM/Ready.Txt").is_ok());
// And a name the folding keeps apart is a name the volume does not hold.
assert!(matches!(
r.lookup(b"/DCIM/READY_TXT"),
Err(ReadError::NotFound { .. })
));
// A path through something that is not a directory says so rather than reporting the
// path absent.
assert!(matches!(
r.lookup(b"/DCIM/READY.TXT/nothing"),
Err(ReadError::NotADirectory { .. })
));
}
#[test]
fn an_ascent_lands_where_the_volumes_own_folding_resolves_from() {
// This format stores no dot entry in any directory, so an ascent never had anything
// it could be a lookup of. What it has to get right instead is the directory it
// hands back: every component after one is found through the up-case table the
// *volume* carries, so an ascent that landed somewhere else would resolve names
// against the wrong directory and still fold them correctly.
let bytes = image();
let mut r = reader(&bytes);
let want = r.lookup(b"/dcim/ready.txt").expect("lookup");
// Down under one spelling, up, and back down under another.
assert_eq!(
r.lookup(b"/DCIM/../dcim/Ready.TXT")
.map(|node| node.storage),
Ok(want.storage)
);
assert_eq!(
r.lookup(b"/dcim/..").map(|n| n.storage),
Ok(r.root().storage)
);
// And a name the folding keeps apart is still absent after an ascent, so what the
// ascent produced is a directory being searched rather than a lookup being skipped.
assert!(matches!(
r.lookup(b"/dcim/../DCIM/READY_TXT"),
Err(ReadError::NotFound { .. })
));
}
#[test]
fn the_folding_is_the_volumes_own_and_not_this_crates_copy_of_one() {
// The claim a reader can only make by reading the table: fold through a volume that
// carries a *different* mapping and the lookup follows that mapping instead. Here the
// volume's table folds the 128 characters the format fixes and nothing else, so `Ä`
// and `ä` are two names on it — conformant, and not what any ordinary volume does.
let mut bytes =
image_of(TreeBuilder::new().file("/ÄX".as_bytes().to_vec(), b"x", meta(0o644)));
install_upcase_table(&mut bytes, &ascii_only_upcase_table());
let mut r = reader(&bytes);
assert_eq!(
r.upcase().folded_units(),
26,
"the volume folds a to z and nothing else"
);
assert!(r.lookup("/ÄX".as_bytes()).is_ok());
assert!(
r.lookup(b"/\xc3\x84x").is_ok(),
"ASCII folds as the format fixes it"
);
assert!(
matches!(r.lookup("/äx".as_bytes()), Err(ReadError::NotFound { .. })),
"a volume that does not fold Ä resolves it case-sensitively",
);
// And the same image read through the mapping every implementation writes would have
// found it, which is what makes this a measurement rather than a tautology.
assert_eq!(
UpcaseTable::recommended().fold(&"äx".encode_utf16().collect::<Vec<_>>()),
UpcaseTable::recommended().fold(&"ÄX".encode_utf16().collect::<Vec<_>>()),
);
}
#[test]
fn a_table_that_folds_ascii_otherwise_than_the_format_fixes_is_refused_strictly() {
// A volume may fold every character but the first 128 its own way. Those 128 are fixed,
// and a checksum that holds says only that the table is the one recorded. A table that
// folds nothing — case-sensitive lookups, ASCII included — is one a strict read refuses
// by naming the first mapping it breaks. A lenient read keeps the volume's own folding,
// which is the answer a reader of that volume gets, and the scan says what is wrong.
let mut bytes = image_of(TreeBuilder::new().file(b"/README".to_vec(), b"x", meta(0o644)));
install_upcase_table(&mut bytes, &[super::super::ondisk::UPCASE_IDENTITY_RUN, 0]);
assert!(matches!(
open_err(&bytes, ReadPolicy::Strict),
ReadError::UpcaseMandatoryMapping {
character: 0x61,
maps_to: 0x61
}
));
let mut r = lenient(&bytes);
assert_eq!(r.upcase().folded_units(), 0, "the volume's own table, kept");
assert!(matches!(
r.lookup(b"/readme"),
Err(ReadError::NotFound { .. })
));
let report = r.scan();
assert!(
report
.anomalies()
.iter()
.any(|a| a.category == Category::UpcaseTable && a.severity == Severity::Conformance),
"{:?}",
report.anomalies()
);
// A table changing one mapping among the 128 is the same refusal, naming it. Here `a`
// maps to `B`.
let mut table: Vec<u16> = ascii_only_upcase_table();
table[0x61] = 0x42;
let mut bytes = image_of(TreeBuilder::new().file(b"/README".to_vec(), b"x", meta(0o644)));
install_upcase_table(&mut bytes, &table);
assert!(matches!(
open_err(&bytes, ReadPolicy::Strict),
ReadError::UpcaseMandatoryMapping {
character: 0x61,
maps_to: 0x42
}
));
}
/// An up-case table folding the 128 characters the format fixes as it fixes them, and
/// every character past them to itself.
fn ascii_only_upcase_table() -> Vec<u16> {
let mut units: Vec<u16> = (0u16..128)
.map(|c| {
if (0x61..=0x7a).contains(&c) {
c - 0x20
} else {
c
}
})
.collect();
units.extend([
super::super::ondisk::UPCASE_IDENTITY_RUN,
(0x1_0000u32 - 128) as u16,
]);
units
}
/// Replace the volume's up-case table with `units`, and its describing entry with what is
/// now there, so a read objects to the folding rather than to the checksum.
fn install_upcase_table(bytes: &mut [u8], units: &[u16]) {
// Every offset taken before a byte of the volume is changed: past this point the
// volume's table is not the one its entry advertises, so opening a reader over it is
// exactly what must not be done to find one's way around it.
let (table_at, table_bytes, entry_at) = {
let r = reader(bytes);
let layout = r.layout();
let table_at = layout
.cluster_start_byte(layout.upcase_cluster)
.expect("a cluster") as usize;
let root_at = layout
.cluster_start_byte(layout.first_cluster_of_root)
.expect("a cluster") as usize;
let entry_at = (0..16)
.map(|n| root_at + n * DIR_ENTRY_SIZE)
.find(|at| bytes[*at] == EntryType::UPCASE_TABLE.0)
.expect("the up-case table's entry");
(table_at, layout.upcase_bytes as usize, entry_at)
};
let mut table = vec![0u8; units.len() * 2];
write_upcase_table(units, &mut table).expect("write the table");
assert!(
table.len() <= table_bytes,
"the table fits where the old one was"
);
bytes[table_at..table_at + table_bytes].fill(0);
bytes[table_at..table_at + table.len()].copy_from_slice(&table);
let checksum = upcase_checksum(&table);
bytes[entry_at + 4..entry_at + 8].copy_from_slice(&checksum.to_le_bytes());
bytes[entry_at + 24..entry_at + 32].copy_from_slice(&(table.len() as u64).to_le_bytes());
}
// -- the two run shapes -------------------------------------------------------------
#[test]
fn a_stream_chained_through_the_table_reads_the_same_as_a_consecutive_one() {
// This writer always declares `NoFatChain`, so the chained shape is one only a
// foreign volume produces — and the reader must follow both. The volume is rewritten
// here into the shape this crate never emits: the flag cleared, and the chain the
// format then requires written into the allocation table.
let mut bytes =
image_of(TreeBuilder::new().file(b"/BIG.BIN".to_vec(), vec![0x5a; 9_000], meta(0o644)));
let (root, bytes_per_cluster, fat_at) = {
let r = reader(&bytes);
(
r.layout().first_cluster_of_root,
r.layout().bytes_per_cluster,
r.layout().fat_offset as usize * r.layout().bytes_per_sector as usize,
)
};
let set = set_at(&bytes, root, "BIG.BIN");
let stream = set + DIR_ENTRY_SIZE;
let first = u32::from_le_bytes(bytes[stream + 20..stream + 24].try_into().unwrap());
let clusters = 9_000u32.div_ceil(bytes_per_cluster);
assert!(clusters > 1, "the file must span more than one cluster");
// Clear the flag and write the chain the format then requires.
bytes[stream + 1] &= !SECONDARY_NO_FAT_CHAIN;
refresh_set_checksum(&mut bytes, set);
for n in 0..clusters {
let entry = fat_at + (first + n) as usize * 4;
let next = if n + 1 == clusters {
super::super::ondisk::END_OF_CHAIN
} else {
first + n + 1
};
bytes[entry..entry + 4].copy_from_slice(&next.to_le_bytes());
}
let mut r = reader(&bytes);
let node = r.lookup(b"/BIG.BIN").expect("look up");
assert_eq!(node.storage, Storage::Chain(first));
assert_eq!(r.read_data(&node).expect("read"), vec![0x5a; 9_000]);
assert!(r.scan().is_clean(), "{}", r.scan().to_report().to_table());
}
#[test]
fn a_chain_looping_onto_itself_is_told_apart_from_a_cluster_two_streams_share() {
// Whose claim is repeated decides what the scan says: a cluster this stream already
// stepped through is its own chain cycling, and blaming "another stream" for it
// would send a reader hunting for a second file that does not exist. The chain here
// is two clusters pointing at each other under a three-cluster declared length, so
// the third step returns to the first.
let mut bytes =
image_of(TreeBuilder::new().file(b"/BIG.BIN".to_vec(), vec![0x5a; 9_000], meta(0o644)));
let (root, bytes_per_cluster, fat_at) = {
let r = reader(&bytes);
(
r.layout().first_cluster_of_root,
r.layout().bytes_per_cluster,
r.layout().fat_offset as usize * r.layout().bytes_per_sector as usize,
)
};
let set = set_at(&bytes, root, "BIG.BIN");
let stream = set + DIR_ENTRY_SIZE;
let first = u32::from_le_bytes(bytes[stream + 20..stream + 24].try_into().unwrap());
assert_eq!(9_000u32.div_ceil(bytes_per_cluster), 3);
bytes[stream + 1] &= !SECONDARY_NO_FAT_CHAIN;
refresh_set_checksum(&mut bytes, set);
for (cluster, next) in [(first, first + 1), (first + 1, first)] {
let entry = fat_at + cluster as usize * 4;
bytes[entry..entry + 4].copy_from_slice(&next.to_le_bytes());
}
let mut r = reader(&bytes);
let report = r.scan();
let said = report
.anomalies()
.iter()
.find(|a| a.detail.contains("loops"))
.unwrap_or_else(|| panic!("no loop finding: {}", report.to_report().to_table()))
.detail
.clone();
assert!(
said.contains(&format!(
"the chain from cluster {first} returns to cluster {first}"
)),
"{said}"
);
assert!(
said.contains("BIG.BIN"),
"the owning path rides along: {said}"
);
assert!(
!report
.anomalies()
.iter()
.any(|a| a.detail.contains("more than one stream")),
"a loop is not a cross-link: {}",
report.to_report().to_table()
);
}
#[test]
fn a_consecutive_run_is_read_without_consulting_the_table() {
// What the flag *means*: the table's entries for the run are undefined, so a reader
// that consulted them would follow whatever is there. This writes nonsense into them
// and the read is unaffected.
let mut bytes =
image_of(TreeBuilder::new().file(b"/BIG.BIN".to_vec(), vec![0x5a; 9_000], meta(0o644)));
let (root, fat_at, count) = {
let r = reader(&bytes);
(
r.layout().first_cluster_of_root,
r.layout().fat_offset as usize * r.layout().bytes_per_sector as usize,
r.layout().cluster_count,
)
};
let stream = set_at(&bytes, root, "BIG.BIN") + DIR_ENTRY_SIZE;
let first = u32::from_le_bytes(bytes[stream + 20..stream + 24].try_into().unwrap());
assert_ne!(bytes[stream + 1] & SECONDARY_NO_FAT_CHAIN, 0);
for n in 0..4u32 {
let entry = fat_at + (first + n) as usize * 4;
bytes[entry..entry + 4].copy_from_slice(&(count - 1).to_le_bytes());
}
let mut r = reader(&bytes);
let node = r.lookup(b"/BIG.BIN").expect("look up");
assert_eq!(node.storage, Storage::Contiguous(first));
assert_eq!(r.read_data(&node).expect("read"), vec![0x5a; 9_000]);
}
// -- the two lengths ----------------------------------------------------------------
#[test]
fn a_written_length_behind_a_declared_one_reads_as_zeros_and_stops_no_strict_read() {
// The state every driver leaves behind and this writer never produces. It is the
// format recording something true, so a strict read carries on and says so — and the
// region past it reads as zeros rather than as whatever the medium last held.
let mut bytes =
image_of(TreeBuilder::new().file(b"/F.BIN".to_vec(), vec![0x5a; 300], meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "F.BIN");
let stream = set + DIR_ENTRY_SIZE;
bytes[stream + 8..stream + 16].copy_from_slice(&100u64.to_le_bytes());
refresh_set_checksum(&mut bytes, set);
let mut r = reader(&bytes);
let node = r.lookup(b"/F.BIN").expect("a strict read accepts it");
assert_eq!(node.data_length, 300);
assert_eq!(node.valid_data_length, 100);
let read = r.read_data(&node).expect("read");
assert_eq!(read.len(), 300);
assert_eq!(&read[..100], &[0x5a; 100]);
assert!(
read[100..].iter().all(|b| *b == 0),
"the tail reads as zeros"
);
// Said out loud, at the severity that lets a strict read carry on.
let found = scan_of(&bytes)
.into_iter()
.find(|f| f.detail.contains("of them written"))
.expect("the discrepancy is reported");
assert_eq!(found.severity, Severity::Cosmetic);
}
#[test]
fn a_written_length_past_a_declared_one_is_a_contradiction_and_is_refused() {
let mut bytes =
image_of(TreeBuilder::new().file(b"/F.BIN".to_vec(), vec![0x5a; 300], meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "F.BIN");
let stream = set + DIR_ENTRY_SIZE;
bytes[stream + 8..stream + 16].copy_from_slice(&4000u64.to_le_bytes());
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(matches!(err, ReadError::ValidLengthPastEnd { .. }), "{err}");
// And a lenient read bounds the read by the length rather than by the claim.
let mut r = lenient(&bytes);
let node = r.lookup(b"/F.BIN").expect("look up");
assert_eq!(node.valid_data_length, 300);
assert_eq!(r.read_data(&node).expect("read").len(), 300);
}
// -- the ranges the format states ---------------------------------------------------
/// The stream extension of the set at `set`, as a byte offset.
fn stream_at(set: usize) -> usize {
set + DIR_ENTRY_SIZE
}
/// Rewrite the 64-bit field at `at` and repair the set checksum at `set`, so a case that
/// changes one field of a set is testing that field.
fn patch_u64(bytes: &mut [u8], set: usize, at: usize, value: u64) {
bytes[at..at + 8].copy_from_slice(&value.to_le_bytes());
refresh_set_checksum(bytes, set);
}
#[test]
fn a_stream_longer_than_the_whole_heap_is_refused_and_its_length_is_held_to_it() {
// exFAT has no holes, so a stream's bytes are its allocation and the heap is what
// bounds it. Without the bound a 64-bit field is an unbounded source of the zeros an
// unwritten tail reads as: nothing past `ValidDataLength` touches a cluster, so the
// read is answered entirely out of the number.
let mut bytes =
image_of(TreeBuilder::new().file(b"/F.BIN".to_vec(), vec![0x5a; 300], meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "F.BIN");
let stream = stream_at(set);
patch_u64(&mut bytes, set, stream + 8, 0);
patch_u64(&mut bytes, set, stream + 24, 8 << 30);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(matches!(err, ReadError::StreamPastHeap { .. }), "{err}");
// And a lenient read is *bounded*, not merely informed: the length it answers with
// is the heap's, and a stream of it is that many bytes rather than eight gibibytes.
let heap = reader(&bytes).layout().heap_bytes();
assert!(heap < 8 << 30, "the fixture is not evidence otherwise");
let mut r = lenient(&bytes);
let node = r.lookup(b"/F.BIN").expect("look up");
assert_eq!(node.data_length, heap);
assert_eq!(
r.read_data_to(&node, std::io::sink()).expect("stream"),
heap
);
}
#[test]
fn a_streamed_read_stops_at_the_cap_a_caller_set() {
// The cap governs what an extraction *writes*, and a stream into a caller's writer
// is what an extraction's `--cat` is. Nothing accumulates there, so the memory a
// stream costs says nothing about the bytes it produces.
let bytes = image();
let mut r = Reader::open_with(
Cursor::new(&bytes[..]),
&OpenOptions::new().limits(Limits::new().max_file_bytes(1024)),
)
.expect("open");
let node = r.lookup(b"/BIG.BIN").expect("look up");
assert!(matches!(
r.read_data_to(&node, std::io::sink()),
Err(ReadError::FileTooLarge { size: 9_000, .. })
));
}
#[test]
fn a_directory_is_read_to_its_end_marker_and_not_to_its_declared_length() {
// The marker is where a directory ends and where every driver stops, so what is
// behind it is not the directory's content however far the length runs. Without that
// bound a directory of two entries declaring the rest of the heap costs a full-heap
// read — once per directory, and the count of them is bounded by the cluster count.
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "DCIM");
let stream = stream_at(set);
let heap = reader(&bytes).layout().heap_bytes();
let dcim = reader(&bytes).lookup(b"/DCIM").expect("look up").storage;
let first = dcim.first_cluster().expect("a directory has an allocation");
let bytes_per_cluster = u64::from(reader(&bytes).layout().bytes_per_cluster);
// Every cluster from the directory's first to the end of the heap, declared as a
// consecutive run so there is no chain to repeat and no cycle to catch it.
let rest = heap - u64::from(first - FIRST_CLUSTER) * bytes_per_cluster;
bytes[stream + 1] |= SECONDARY_NO_FAT_CHAIN;
patch_u64(&mut bytes, set, stream + 8, rest);
patch_u64(&mut bytes, set, stream + 24, rest);
// The declared length is inside every bound the format states, so nothing refuses it
// and the traversal itself is what has to be bounded.
assert!(rest <= heap && rest <= MAX_DIRECTORY_BYTES);
assert!(
rest / bytes_per_cluster > 1000,
"the fixture declares {} clusters, which is not evidence of anything",
rest / bytes_per_cluster
);
assert_eq!(
reader(&bytes)
.lookup(b"/DCIM")
.expect("look up")
.data_length,
rest
);
// Which clusters were read, said by what the reader would object to. An entry of a
// critical type nothing recognizes refuses a strict read wherever it is met, so it
// is a probe that answers "this cluster was read" — placed in the last cluster the
// declared length covers, and in the marker's own cluster as the control that says
// the probe works.
let unknown = |bytes: &mut Vec<u8>, at: usize| bytes[at] = 0x9F;
let last = FIRST_CLUSTER + reader(&bytes).layout().cluster_count - 1;
let dcim_at = cluster_at(&bytes, first);
let slots = usize::try_from(bytes_per_cluster).expect("a cluster") / DIR_ENTRY_SIZE;
let marker = dcim_at
+ (0..slots)
.find(|n| bytes[dcim_at + n * DIR_ENTRY_SIZE] == 0)
.expect("the end marker")
* DIR_ENTRY_SIZE;
let mut control = bytes.clone();
unknown(&mut control, marker + DIR_ENTRY_SIZE);
let err = root_entries(&control)
.map(|_| ())
.and_then(|()| {
let mut r = reader(&control);
let node = r.lookup(b"/DCIM")?;
r.read_dir(&node).map(|_| ())
})
.expect_err("the probe is met in the cluster the marker sits in");
assert!(matches!(err, ReadError::EntriesAfterEnd { .. }), "{err}");
let last_at = cluster_at(&bytes, last);
unknown(&mut bytes, last_at);
let mut r = reader(&bytes);
let node = r.lookup(b"/DCIM").expect("look up");
let entries = r
.read_dir(&node)
.expect("the read stopped at the marker, so the probe was never met");
assert_eq!(entries.len(), 3, "and it is still the directory it was");
}
#[test]
fn a_directory_longer_than_the_format_allows_one_is_refused() {
// The cap is the format's own and the writer is held to it, so the two ends match.
// It binds only above the 256 mebibytes it states, and a volume with a heap that
// large is larger than a case here holds in memory — so the heap the bound is asked
// about is set on the layout rather than formatted, and every other field is the
// volume's own.
let bytes = image();
let mut r = reader(&bytes);
r.layout.cluster_count = 100_000;
assert!(r.layout.heap_bytes() > MAX_DIRECTORY_BYTES);
let mut strict = OnDeviation::Policy(ReadPolicy::Strict);
let err = r
.bound_length(MAX_DIRECTORY_BYTES + 1, true, 7, &mut strict)
.expect_err("a strict read refuses it");
assert!(
matches!(err, ReadError::DirectoryTooLong { index: 7, .. }),
"{err}"
);
// A lenient read is bounded rather than merely informed, and a file of the same
// length is not a directory and is not held to a directory's cap.
let mut lenient = OnDeviation::Policy(ReadPolicy::Lenient);
assert_eq!(
r.bound_length(MAX_DIRECTORY_BYTES + 1, true, 7, &mut lenient)
.expect("a lenient read carries on"),
MAX_DIRECTORY_BYTES
);
assert_eq!(
r.bound_length(MAX_DIRECTORY_BYTES + 1, false, 7, &mut lenient)
.expect("a lenient read carries on"),
MAX_DIRECTORY_BYTES + 1
);
}
/// A volume holding one 300-byte file, with the byte offsets of that file's entry set and
/// of the stream extension inside it.
///
/// The two fields that describe where a stream's bytes are — `FirstCluster` and
/// `DataLength` — both live in that entry, and the constraint between them runs in two
/// directions, so the fixture is shared and the patch is what each case says.
fn a_volume_with_one_file() -> (Vec<u8>, usize, usize) {
let bytes =
image_of(TreeBuilder::new().file(b"/F.BIN".to_vec(), vec![0x5a; 300], meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "F.BIN");
let stream = stream_at(set);
(bytes, set, stream)
}
#[test]
fn a_stream_recording_a_length_and_no_first_cluster_is_named_where_it_is_read() {
// The format states the constraint in both directions, and the directory half was
// the only one reported: a file claiming nine thousand bytes it has nowhere to keep
// is inside every bound, and the incoherence surfaced halfway through an extraction
// rather than at the entry that carries it.
let (mut bytes, set, stream) = a_volume_with_one_file();
bytes[stream + 20..stream + 24].copy_from_slice(&0u32.to_le_bytes());
patch_u64(&mut bytes, set, stream + 8, 9_000);
patch_u64(&mut bytes, set, stream + 24, 9_000);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(
matches!(
err,
ReadError::StreamWithoutAllocation {
declared: 9_000,
..
}
),
"{err}"
);
assert_eq!(err.anomaly().severity, Severity::Structural);
}
#[test]
fn a_stream_recording_a_first_cluster_and_no_length_is_named_where_it_is_read() {
// The other half of the same constraint, and the half that hides better: the entry
// reads back as an ordinary empty file, every bound it passes is one it would pass
// anyway, and the clusters it holds surface only at the far end of a scan as space in
// use and reached by nothing — a symptom, three structures away from its cause. The
// volume still reads, which is what puts this one a severity below its converse.
let (mut bytes, set, stream) = a_volume_with_one_file();
patch_u64(&mut bytes, set, stream + 8, 0);
patch_u64(&mut bytes, set, stream + 24, 0);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(
matches!(err, ReadError::AllocationWithoutLength { .. }),
"{err}"
);
assert_eq!(err.anomaly().severity, Severity::Conformance);
}
#[test]
fn a_directory_whose_length_is_not_whole_clusters_is_named() {
// The format states a directory's length as the entire size of its allocation, which
// makes it a multiple of the cluster size on every conformant volume. It is
// enumerated by the clusters it covers either way, so a length that is not one is
// neither honoured nor meaningful.
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "DCIM");
patch_u64(&mut bytes, set, stream_at(set) + 24, 1);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(
matches!(
err,
ReadError::DirectoryLengthNotClusters { declared: 1, .. }
),
"{err}"
);
}
#[test]
fn attribute_bits_the_format_reserves_are_named() {
// Eleven of the sixteen are reserved and zero on a conformant volume, bit 3 among
// them — which is FAT's volume-label attribute, and is reserved here because exFAT
// gives the label an entry type of its own.
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "DCIM");
let attributes = u16::from_le_bytes([bytes[set + 4], bytes[set + 5]]) | 0xF008;
bytes[set + 4..set + 6].copy_from_slice(&attributes.to_le_bytes());
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(
matches!(err, ReadError::ReservedAttributes { bits: 0xF008, .. }),
"{err}"
);
// And the five the format defines are not swept up with them.
assert_eq!(FileAttributes::DEFINED.bits(), 0x0037);
}
#[test]
fn a_stream_with_an_allocation_and_no_allocation_declared_possible_is_named() {
// The format requires the flag on every stream extension, whether or not the stream
// currently addresses a cluster — so a clear one beside a first cluster and a length
// is the entry contradicting itself.
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "DCIM");
let stream = stream_at(set);
assert_ne!(
bytes[stream + 1] & SECONDARY_ALLOCATION_POSSIBLE,
0,
"the writer sets it, which is what makes clearing it the case under test"
);
bytes[stream + 1] &= !SECONDARY_ALLOCATION_POSSIBLE;
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(
matches!(err, ReadError::AllocationNotPossible { .. }),
"{err}"
);
}
#[test]
fn a_time_the_encoding_does_not_define_is_named_where_the_entry_is_read() {
// `DosTimestamp::decode` reports the instant the arithmetic reaches and says a scan
// is what judges it. This is that scan: a creation time of zero spells month 0 and
// day 0, which reads back as a date in 1979 and was never an instant.
for (offset, field) in [(8usize, "creation time"), (16, "access time")] {
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "DCIM");
bytes[set + offset..set + offset + 4].copy_from_slice(&0u32.to_le_bytes());
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(
matches!(err, ReadError::MalformedTimestamp { field: f, .. } if f == field),
"{field}: {err}"
);
}
// And the hundredths byte, whose range the format states as 0 to 199 — a value of
// 255 would move the instant 2.55 seconds by a field that cannot hold that value.
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "DCIM");
bytes[set + 20] = 255;
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(
matches!(
err,
ReadError::MalformedTimestamp {
field: "creation time",
..
}
),
"{err}"
);
}
#[test]
fn a_set_carrying_a_name_entry_its_name_does_not_reach_is_named() {
// The secondary count is defined as one plus the entries the name occupies. The
// mirror case — a set that ends before its name does — was reported and this one was
// not, which is one direction of one comparison.
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "DCIM");
assert_eq!(bytes[set + 1], 2, "a file entry, a stream and one name");
// A second name entry behind the first, with the count raised to match so the set is
// complete and only its length is wrong.
bytes[set + 1] = 3;
let third = set + 3 * DIR_ENTRY_SIZE;
let mut extra = [0u8; DIR_ENTRY_SIZE];
FileNameEntry::new(&[0x0041])
.write_to(&mut extra)
.expect("write");
bytes[third..third + DIR_ENTRY_SIZE].copy_from_slice(&extra);
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses it");
assert!(
matches!(
err,
ReadError::ExcessNameEntries {
want: 1,
have: 2,
..
}
),
"{err}"
);
// The name is still the one `NameLength` states, since no implementation reads past
// it — so a lenient read enumerates the directory unchanged.
assert!(
root_entries_lenient(&bytes)
.iter()
.any(|e| e.name == b"DCIM")
);
}
// -- what a volume must carry -------------------------------------------------------
#[test]
fn a_volume_recording_two_allocation_tables_is_refused_by_name_under_either_policy() {
// The transaction-safe variant. Which of the two tables is live is a flag rather than
// a convention, so there is no lenient reading of one — only a coin toss dressed as
// an answer.
let mut bytes = image();
bytes[110] = 2;
refresh_boot_checksum(&mut bytes, 0);
for policy in [ReadPolicy::Strict, ReadPolicy::Lenient] {
let err = open_err(&bytes, policy);
assert!(matches!(err, ReadError::TexFat), "{policy:?}: {err}");
}
// A count the format does not define at all is refused as that rather than as TexFAT.
for count in [0u8, 3, 255] {
let mut bytes = image();
bytes[110] = count;
refresh_boot_checksum(&mut bytes, 0);
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(matches!(err, ReadError::FatCount { .. }), "{count}: {err}");
}
}
#[test]
fn a_volume_whose_root_names_no_bitmap_or_no_table_is_refused_rather_than_read_empty() {
// A reader that answered with an empty tree would report a working filesystem: both
// are found by reading the root directory and nowhere else, and a volume without them
// is one nothing can allocate in or look a name up in.
for entry_type in [EntryType::ALLOCATION_BITMAP, EntryType::UPCASE_TABLE] {
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let at = cluster_at(&bytes, root);
let slot = (0..8)
.map(|n| at + n * DIR_ENTRY_SIZE)
.find(|at| bytes[*at] == entry_type.0)
.expect("the describing entry");
// Its in-use bit cleared, which is a slot a reader steps over.
bytes[slot] = entry_type.cleared().0;
for policy in [ReadPolicy::Strict, ReadPolicy::Lenient] {
let err = open_err(&bytes, policy);
assert!(
matches!(err, ReadError::MissingResident { .. }),
"{entry_type:?} under {policy:?}: {err}"
);
}
}
}
#[test]
fn a_slot_whose_in_use_bit_is_clear_is_stepped_over_rather_than_read_as_the_end() {
// Not an edge case: the second slot of every formatted volume's root directory is a
// volume GUID entry reserved by clearing its in-use bit, with the bitmap and the
// up-case table behind it. A reader that stopped there would find neither, on a
// conformant volume, silently — which is why the case above passes at all.
let bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let at = cluster_at(&bytes, root);
let guid = at + DIR_ENTRY_SIZE;
assert_eq!(bytes[guid], EntryType::VOLUME_GUID.cleared().0);
assert!(!EntryType(bytes[guid]).is_end_of_directory());
assert!(!paths(&bytes).is_empty());
}
// -- negative controls, each watched failing ----------------------------------------
#[test]
fn a_damaged_boot_region_checksum_is_named_and_the_main_region_is_still_preferred() {
// Every geometry field a reader depends on is inside the checksum, so a mismatch says
// those bytes have changed since a formatter wrote them.
let mut bytes = image();
bytes[64] ^= 0x01; // PartitionOffset, inside the checksum and read by nothing
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(
matches!(err, ReadError::BootChecksumMismatch { sector: 0, .. }),
"{err}"
);
let anomaly = err.anomaly();
assert_eq!(anomaly.severity, Severity::Integrity);
assert_eq!(anomaly.category, Category::BootRegion);
// Leniently the volume still opens, through the main region rather than the backup —
// which is what every driver does, so a reader that fell back would open a volume
// under a geometry nothing else uses.
let r = lenient(&bytes);
assert_eq!(r.boot_sector().partition_offset, bytes_u64(&bytes, 64));
}
#[test]
fn a_backup_region_describing_a_different_volume_is_named() {
let mut bytes = image();
let sector = reader(&bytes).layout().bytes_per_sector as usize;
let backup = 12 * sector;
bytes[backup + 100..backup + 104].copy_from_slice(&0xdead_beefu32.to_le_bytes());
refresh_boot_checksum(&mut bytes, 12);
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(
matches!(err, ReadError::BackupBootRegionDiffers { .. }),
"{err}"
);
assert!(err.to_string().contains("VolumeSerialNumber"), "{err}");
assert_eq!(err.anomaly().severity, Severity::Conformance);
}
#[test]
fn the_two_fields_a_driver_rewrites_are_not_held_against_the_backup() {
// The trap a byte comparison walks into. A mounted driver marks the volume dirty and
// updates how full it is in the *main* region alone, so comparing the regions byte for
// byte would report every volume that has ever been written to.
let mut bytes = image();
bytes[106] = 0x02; // VolumeDirty, outside the checksum
bytes[112] = 99; // PercentInUse, likewise
let r = lenient(&bytes);
assert!(r.volume_dirty());
let report = r.boot_sector().volume_flags;
assert_eq!(report & 0x0002, 0x0002);
assert!(
!scan_of(&bytes)
.iter()
.any(|a| a.detail.contains("does not describe the same volume")),
"a driver's own two fields are not a backup that has drifted",
);
}
#[test]
fn a_volume_a_driver_left_open_is_a_remark_and_not_a_refusal() {
// The carve-out the strict line needs. This crate's writer never produces a dirty
// volume because it never mounts one, so the literal rule would refuse a card someone
// pulled out of a reader — the most common image a consumer has.
let mut bytes = image();
bytes[106] = 0x02;
let mut r = Reader::open(Cursor::new(&bytes)).expect("a strict read accepts it");
assert!(r.volume_dirty());
assert!(!r.media_failure());
assert!(!r.scan().has_fatal(ReadPolicy::Strict));
let found = scan_of(&bytes)
.into_iter()
.find(|f| f.detail.contains("not cleanly unmounted"))
.expect("the state is reported");
assert_eq!(found.severity, Severity::Cosmetic);
// The message says what the bit means rather than which field held it: the two
// readings send a caller to different places.
assert!(!found.detail.contains("VolumeFlags"), "{}", found.detail);
let mut bytes = image();
bytes[106] = 0x04;
let r = Reader::open(Cursor::new(&bytes)).expect("a strict read accepts it");
assert!(r.media_failure());
}
#[test]
fn a_major_revision_this_reader_does_not_implement_is_refused_and_a_minor_one_is_a_remark() {
// The format states the major half as a `shall`: an implementation mounts revision 1
// and no other, because a major revision is how it says the structures behind the
// boot sector are not the ones a reader knows. Comparing the two boot regions against
// each other reads as coverage and is not — both copies agreeing on a revision
// nothing here implements is the case that matters, so both are written.
for revision in [0x0200u16, 0xFFFF] {
let mut bytes = image();
for region in [0u64, BOOT_REGION_SECTORS] {
let at = region as usize * 512;
bytes[at + 104..at + 106].copy_from_slice(&revision.to_le_bytes());
refresh_boot_checksum(&mut bytes, region);
}
for policy in [ReadPolicy::Strict, ReadPolicy::Lenient] {
let err = open_err(&bytes, policy);
assert!(
matches!(err, ReadError::BadBootSector { .. }),
"{revision:#06x} under {policy:?}: {err}"
);
assert!(err.to_string().contains("revision"), "{err}");
}
// The classifier answers with the reader, since both judge the boot sector
// through one function.
assert!(
crate::detect(Cursor::new(&bytes)).is_err(),
"{revision:#06x}"
);
}
// A minor revision is the weaker case: the format asks an implementation to honour
// one, so every structure is still the one this reader knows and the volume opens.
let mut bytes = image();
for region in [0u64, BOOT_REGION_SECTORS] {
let at = region as usize * 512;
bytes[at + 104..at + 106].copy_from_slice(&0x0103u16.to_le_bytes());
refresh_boot_checksum(&mut bytes, region);
}
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(
matches!(err, ReadError::UnknownMinorRevision { minor: 3 }),
"{err}"
);
let found = scan_of(&bytes)
.into_iter()
.find(|f| f.detail.contains("minor revision"))
.expect("the revision is reported");
assert_eq!(found.severity, Severity::Conformance);
}
#[test]
fn an_extended_boot_sector_missing_its_signature_is_named() {
// The region's checksum covers whatever is in the sector and says nothing about what
// it should be, so a region with its eight signatures wiped and a checksum that
// agrees with its bytes is self-consistent and still not the region the format
// defines. The accessor for the check existed and the check did not.
for region in [0u64, BOOT_REGION_SECTORS] {
let mut bytes = image();
let at = (region as usize + 1) * 512;
bytes[at + 508..at + 512].copy_from_slice(&0u32.to_le_bytes());
refresh_boot_checksum(&mut bytes, region);
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(
matches!(
err,
ReadError::BadExtendedBootSignature {
sector,
found: 0,
expected: EXTENDED_BOOT_SIGNATURE,
} if sector == region + 1
),
"region {region}: {err}"
);
}
// One report per region, however many of its eight sectors are wiped: eight sectors
// zeroed together are one fact about the region, and a scan that spent eight findings
// on it would have that much less room for the rest of the volume.
let mut bytes = image();
for sector in 1..=EXTENDED_BOOT_SECTORS as usize {
let at = sector * 512;
bytes[at + 508..at + 512].copy_from_slice(&0u32.to_le_bytes());
}
refresh_boot_checksum(&mut bytes, 0);
let named: Vec<_> = scan_of(&bytes)
.into_iter()
.filter(|f| f.detail.contains("extended boot sector"))
.collect();
assert_eq!(named.len(), 1, "{named:#?}");
assert_eq!(named[0].severity, Severity::Conformance);
}
#[test]
fn a_chain_reaching_a_cluster_the_table_marks_bad_is_named_as_that() {
// A bad cluster is a number the format sets aside so that nothing allocates it, so a
// chain reaching one is a chain into storage a driver was told to leave alone rather
// than a cluster number that happens to be too high. The range test would refuse it
// either way; what the constant buys is a reader that says which.
let mut bytes =
image_of(TreeBuilder::new().file(b"/F.BIN".to_vec(), vec![0x5a; 9_000], meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "F.BIN");
let stream = stream_at(set);
// Chained rather than consecutive, so the table is consulted at all.
bytes[stream + 1] &= !SECONDARY_NO_FAT_CHAIN;
refresh_set_checksum(&mut bytes, set);
let first = u32::from_le_bytes([
bytes[stream + 20],
bytes[stream + 21],
bytes[stream + 22],
bytes[stream + 23],
]);
let entry = reader(&bytes)
.layout()
.fat_entry_byte(first)
.expect("an entry for the first cluster") as usize;
bytes[entry..entry + 4].copy_from_slice(&BAD_CLUSTER.to_le_bytes());
let mut r = lenient(&bytes);
let node = r.lookup(b"/F.BIN").expect("look up");
let err = r
.read_data(&node)
.expect_err("the chain runs into the mark");
assert!(
matches!(err, ReadError::BadClusterInChain { cluster } if cluster == BAD_CLUSTER),
"{err}"
);
}
#[test]
fn a_percentage_the_field_cannot_hold_is_a_different_remark_from_a_stale_one() {
// The field is a percentage, 0 through 100, or 255 for "not known", and it sits
// outside the boot region's checksum precisely so a driver can keep it current. So a
// stale value is a number nobody was obliged to update, and a value between the two
// is a byte that was never a percentage — which is a different thing to be told.
let mut bytes = image();
bytes[112] = 200;
let found = scan_of(&bytes)
.into_iter()
.find(|f| f.detail.contains("PercentInUse"))
.expect("the value is reported");
assert_eq!(found.severity, Severity::Conformance);
assert!(!found.detail.contains("200%"), "{}", found.detail);
// A percentage that is merely out of date says how full the volume is instead.
let mut bytes = image();
bytes[112] = 99;
let found = scan_of(&bytes)
.into_iter()
.find(|f| f.detail.contains("99% in use"))
.expect("the staleness is reported");
assert_eq!(found.severity, Severity::Cosmetic);
// And "not known" is neither.
let mut bytes = image();
bytes[112] = PERCENT_IN_USE_UNKNOWN;
assert!(
!scan_of(&bytes)
.iter()
.any(|f| f.detail.contains("PercentInUse") || f.detail.contains("in use and")),
"the format's own value for an unmeasured volume is not a deviation"
);
}
#[test]
fn an_up_case_table_that_is_not_the_mapping_its_entry_advertises_is_named() {
let mut bytes = image();
let table = cluster_at(&bytes, reader(&bytes).layout().upcase_cluster);
bytes[table + 200] ^= 0xff;
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(
matches!(err, ReadError::UpcaseChecksumMismatch { .. }),
"{err}"
);
assert_eq!(err.anomaly().severity, Severity::Integrity);
assert_eq!(err.anomaly().category, Category::UpcaseTable);
// Leniently the volume opens and folds through the table as it stands, because those
// bytes are still the volume's own statement about how its names compare.
assert!(lenient(&bytes).upcase().folded_units() > 0);
}
#[test]
fn a_damaged_entry_set_checksum_is_named() {
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "BIG.BIN");
// The attribute word, which is inside the set and outside the two bytes the checksum
// steps over.
bytes[set + 4] ^= 0x01;
let err = root_entries(&bytes).expect_err("a strict read refuses");
assert!(
matches!(err, ReadError::SetChecksumMismatch { .. }),
"{err}"
);
assert_eq!(err.anomaly().severity, Severity::Integrity);
}
#[test]
fn a_name_hash_no_name_produces_is_named_where_no_checksum_covers_it() {
// The failure a reader is uniquely placed to name: the set's own checksum is
// satisfied by a hash and a name that disagree, so nothing but recomputing the hash
// finds it — and a driver that trusts the field never sees the file.
let mut bytes = image();
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "BIG.BIN");
let stream = set + DIR_ENTRY_SIZE;
let was = u16::from_le_bytes(bytes[stream + 4..stream + 6].try_into().unwrap());
bytes[stream + 4..stream + 6].copy_from_slice(&(was ^ 0x0001).to_le_bytes());
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses");
assert!(matches!(err, ReadError::NameHashMismatch { .. }), "{err}");
assert_eq!(err.anomaly().severity, Severity::Integrity);
}
#[test]
fn a_name_no_directory_can_hold_is_refused_where_the_reader_resolves_it() {
// Nothing about the field a name arrives in rules these out: an exFAT name is UTF-16
// and may spell anything, so the refusal is the reader's.
for name in ["..", ".", "a/b", "a\u{0}b"] {
let mut bytes = image_of(TreeBuilder::new().file(b"/XX".to_vec(), b"x", meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "XX");
let stream = set + DIR_ENTRY_SIZE;
let units: Vec<u16> = name.encode_utf16().collect();
bytes[stream + 3] = units.len() as u8;
let hash = name_hash(&UpcaseTable::recommended().fold(&units));
bytes[stream + 4..stream + 6].copy_from_slice(&hash.to_le_bytes());
let name_entry = set + 2 * DIR_ENTRY_SIZE;
bytes[name_entry + 2..name_entry + DIR_ENTRY_SIZE].fill(0);
for (n, unit) in units.iter().enumerate() {
let at = name_entry + 2 + n * 2;
bytes[at..at + 2].copy_from_slice(&unit.to_le_bytes());
}
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses");
assert!(
matches!(err, ReadError::HostileName { .. }),
"{name:?}: {err}"
);
assert_eq!(err.anomaly().severity, Severity::Structural);
// And it is never handed back, whatever the policy: a path built by joining it
// onto its directory's would leave the tree.
let names = root_entries_lenient(&bytes);
assert!(names.is_empty(), "{name:?}: the name was handed back");
}
}
#[test]
fn an_entry_set_that_ends_before_it_said_it_would_is_named() {
let mut bytes = image_of(TreeBuilder::new().file(b"/XX".to_vec(), b"x", meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "XX");
// One more entry than the set has, so the terminator behind it ends the set short.
bytes[set + 1] += 1;
refresh_set_checksum(&mut bytes, set);
let err = root_entries(&bytes).expect_err("a strict read refuses");
assert!(matches!(err, ReadError::IncompleteEntrySet { .. }), "{err}");
assert_eq!(err.anomaly().severity, Severity::Structural);
}
#[test]
fn an_entry_continuing_a_set_no_entry_opened_is_named() {
let mut bytes = image_of(TreeBuilder::new());
let root = reader(&bytes).layout().first_cluster_of_root;
let at = cluster_at(&bytes, root);
// The first free slot behind the four a format writes.
let slot = at + 4 * DIR_ENTRY_SIZE;
bytes[slot] = EntryType::FILE_NAME.0;
let err = root_entries(&bytes).expect_err("a strict read refuses");
assert!(
matches!(err, ReadError::StraySecondaryEntry { .. }),
"{err}"
);
}
#[test]
fn an_entry_of_a_critical_type_this_reader_does_not_know_is_named_and_a_benign_one_is_not() {
// The type byte says whether an implementation that does not know an entry may carry
// on, and this reader takes the format at its word in both directions.
let root = {
let bytes = image_of(TreeBuilder::new());
reader(&bytes).layout().first_cluster_of_root
};
let mut bytes = image_of(TreeBuilder::new());
let at = cluster_at(&bytes, root);
bytes[at + 4 * DIR_ENTRY_SIZE] = 0x9F; // in use, primary, critical, code 31
let err = root_entries(&bytes).expect_err("a strict read refuses");
assert!(
matches!(err, ReadError::UnknownCriticalEntry { .. }),
"{err}"
);
assert_eq!(err.anomaly().severity, Severity::Conformance);
let mut bytes = image_of(TreeBuilder::new());
bytes[at + 4 * DIR_ENTRY_SIZE] = 0xBF; // in use, primary, benign, code 31
refresh_set_checksum(&mut bytes, at + 4 * DIR_ENTRY_SIZE);
assert!(
root_entries(&bytes).is_ok(),
"a benign entry is carried through rather than refused",
);
}
/// The byte offset of `cluster`'s entry in the allocation table.
fn table_at(bytes: &[u8], cluster: u32) -> usize {
let layout = *reader(bytes).layout();
layout.fat_offset as usize * layout.bytes_per_sector as usize + cluster as usize * 4
}
/// Set or clear `cluster`'s bit in the allocation bitmap.
fn mark(bytes: &mut [u8], cluster: u32, in_use: bool) {
let bitmap = cluster_at(bytes, reader(bytes).layout().bitmap_cluster);
let bit = (cluster - FIRST_CLUSTER) as usize;
if in_use {
bytes[bitmap + bit / 8] |= 1 << (bit % 8);
} else {
bytes[bitmap + bit / 8] &= !(1 << (bit % 8));
}
}
/// A cluster nothing on a small volume this crate wrote holds: the heap's last.
fn spare_cluster(bytes: &[u8]) -> u32 {
let mut r = reader(bytes);
let last = FIRST_CLUSTER + r.layout().cluster_count - 1;
assert!(
!r.is_allocated(last).expect("the bitmap"),
"the fixture's last cluster is free"
);
last
}
/// A vendor allocation entry: benign and secondary, addressing `cluster` alone as a
/// consecutive run, under a vendor's GUID.
fn vendor_allocation(cluster: u32, bytes_per_cluster: u32) -> [u8; DIR_ENTRY_SIZE] {
let mut slot = [0u8; DIR_ENTRY_SIZE];
slot[0] = EntryType::VENDOR_ALLOCATION.0;
slot[1] = SECONDARY_ALLOCATION_POSSIBLE | SECONDARY_NO_FAT_CHAIN;
slot[2..18].copy_from_slice(&[0x5a; 16]);
slot[20..24].copy_from_slice(&cluster.to_le_bytes());
slot[24..32].copy_from_slice(&u64::from(bytes_per_cluster).to_le_bytes());
slot
}
#[test]
fn a_benign_entry_this_reader_does_not_know_heads_a_set_it_passes_over_whole() {
// The generic template: a primary records how many secondaries follow it and a
// checksum over all of them, and a benign one an implementation does not recognize is
// passed over together with its set (documented). Here an unassigned benign primary
// with a vendor extension behind it, the shape a vendor writes.
let mut bytes = image_of(TreeBuilder::new());
let root = reader(&bytes).layout().first_cluster_of_root;
let at = cluster_at(&bytes, root) + 4 * DIR_ENTRY_SIZE;
assert_eq!(bytes[at], 0, "the root ends at its fifth slot");
bytes[at] = 0xA5; // in use, primary, benign, code 5
bytes[at + 1] = 1;
bytes[at + DIR_ENTRY_SIZE] = EntryType::VENDOR_EXTENSION.0;
bytes[at + DIR_ENTRY_SIZE + 2..at + DIR_ENTRY_SIZE + 18].copy_from_slice(&[0x5a; 16]);
refresh_set_checksum(&mut bytes, at);
assert!(
root_entries(&bytes).is_ok(),
"its secondary is its own, not a stray"
);
assert!(scan_of(&bytes).is_empty(), "{:#?}", scan_of(&bytes));
// Its checksum is held to its bytes, as every set's is.
bytes[at + DIR_ENTRY_SIZE + 20] ^= 1;
assert!(matches!(
root_entries(&bytes),
Err(ReadError::SetChecksumMismatch { index: 4, .. })
));
}
#[test]
fn a_volume_guid_entry_has_no_secondaries_and_sits_in_the_root() {
// Documented: the volume GUID entry's secondary count is zero, and it is one of the
// root's own entries.
let bytes = image_of(TreeBuilder::new().directory(b"/D".to_vec(), meta(0o755)));
let root = reader(&bytes).layout().first_cluster_of_root;
let d = cluster_at(&bytes, {
let mut r = reader(&bytes);
r.lookup(b"/D")
.expect("the directory")
.storage
.first_cluster()
.expect("a cluster")
});
let at = (0..)
.map(|n| cluster_at(&bytes, root) + n * DIR_ENTRY_SIZE)
.find(|&at| bytes[at] == 0)
.expect("a free slot");
let mut guid = bytes.clone();
guid[at] = EntryType::VOLUME_GUID.0;
guid[at + 1] = 1;
guid[at + DIR_ENTRY_SIZE] = EntryType::VENDOR_EXTENSION.0;
refresh_set_checksum(&mut guid, at);
let found = scan_of(&guid);
assert!(
found
.iter()
.any(|f| f.detail.contains("declares 1 secondary entries")
&& f.severity == Severity::Conformance),
"{found:#?}"
);
assert!(
!found.iter().any(|f| f.detail.contains("stray")),
"{found:#?}"
);
let mut misplaced = bytes.clone();
misplaced[d] = EntryType::VOLUME_GUID.0;
refresh_set_checksum(&mut misplaced, d);
let found = scan_of(&misplaced);
assert!(
found.iter().any(|f| f.detail.contains("volume GUID")),
"{found:#?}"
);
}
#[test]
fn what_a_benign_entry_allocates_is_claimed_by_the_scan() {
// A vendor allocation entry owns the clusters it addresses (documented), so they are
// neither lost nor free to another stream, whether it sits behind a benign primary
// or in a file's set.
let fixture =
image_of(TreeBuilder::new().file(b"/F.BIN".to_vec(), vec![1; 300], meta(0o644)));
let (root, bytes_per_cluster) = {
let r = reader(&fixture);
(
r.layout().first_cluster_of_root,
r.layout().bytes_per_cluster,
)
};
let spare = spare_cluster(&fixture);
let file = set_at(&fixture, root, "F.BIN");
let first = u32::from_le_bytes(
fixture[file + DIR_ENTRY_SIZE + 20..file + DIR_ENTRY_SIZE + 24]
.try_into()
.expect("four bytes"),
);
let after_file = file + 3 * DIR_ENTRY_SIZE;
assert_eq!(
fixture[after_file], 0,
"the root ends behind the file's set"
);
// Behind a benign primary.
let under_primary = |cluster: u32| {
let mut bytes = fixture.clone();
bytes[after_file] = 0xA5;
bytes[after_file + 1] = 1;
let slot = vendor_allocation(cluster, bytes_per_cluster);
bytes[after_file + DIR_ENTRY_SIZE..after_file + 2 * DIR_ENTRY_SIZE]
.copy_from_slice(&slot);
refresh_set_checksum(&mut bytes, after_file);
bytes
};
// In the file's own set, behind its name.
let in_file = |cluster: u32| {
let mut bytes = fixture.clone();
let slot = vendor_allocation(cluster, bytes_per_cluster);
bytes[after_file..after_file + DIR_ENTRY_SIZE].copy_from_slice(&slot);
bytes[file + 1] += 1;
refresh_set_checksum(&mut bytes, file);
bytes
};
for (what, place) in [
(
"behind a benign primary",
&under_primary as &dyn Fn(u32) -> Vec<u8>,
),
("in a file's set", &in_file),
] {
// Its cluster in use: nothing to say.
let mut bytes = place(spare);
mark(&mut bytes, spare, true);
assert!(scan_of(&bytes).is_empty(), "{what}: {:#?}", scan_of(&bytes));
assert!(root_entries(&bytes).is_ok(), "{what}");
// Free in the bitmap: the allocation is held to it, as a stream's is.
let found = scan_of(&place(spare));
assert!(
found
.iter()
.any(|f| f.detail.contains("the allocation bitmap says it is free")),
"{what}: {found:#?}"
);
// The file's own cluster: two owners.
let found = scan_of(&place(first));
assert!(
found
.iter()
.any(|f| f.detail.contains("occupied by more than one stream")),
"{what}: {found:#?}"
);
}
}
#[test]
fn a_directory_whose_two_lengths_differ_is_named_and_read_to_its_length() {
// Documented: a directory's written length is its length. The pinned `fsck.exfat`
// accepts the pair and reads the directory to its length (observed), and so does this.
let mut bytes = image_of(
TreeBuilder::new()
.directory(b"/D".to_vec(), meta(0o755))
.file(b"/D/F.TXT".to_vec(), b"f", meta(0o644)),
);
let root = reader(&bytes).layout().first_cluster_of_root;
let d = set_at(&bytes, root, "D");
let stream = d + DIR_ENTRY_SIZE;
bytes[stream + 8..stream + 16].copy_from_slice(&0u64.to_le_bytes());
refresh_set_checksum(&mut bytes, d);
let found = scan_of(&bytes);
let named: Vec<&Finding> = found
.iter()
.filter(|f| f.detail.contains("where a directory's two lengths are one"))
.collect();
assert_eq!(named.len(), 1, "{found:#?}");
assert_eq!(named[0].severity, Severity::Conformance);
assert!(
!found.iter().any(|f| f.detail.contains("reads as zeros")),
"a directory's slots are not a region read as zeros: {found:#?}"
);
assert!(
lenient_paths(&bytes).contains(&b"/D/F.TXT".to_vec()),
"the entry inside is read"
);
assert!(
Reader::open(Cursor::new(bytes.as_slice()))
.expect("open")
.walk()
.is_err(),
"a strict walk refuses it"
);
}
#[test]
fn a_chain_running_past_its_stream_s_length_is_named_and_claimed() {
// A one-cluster file, chained through the table rather than declared consecutive, whose
// chain runs on through two clusters more.
let fixture =
image_of(TreeBuilder::new().file(b"/F.BIN".to_vec(), vec![1; 300], meta(0o644)));
let root = reader(&fixture).layout().first_cluster_of_root;
let file = set_at(&fixture, root, "F.BIN");
let stream = file + DIR_ENTRY_SIZE;
let first = u32::from_le_bytes(fixture[stream + 20..stream + 24].try_into().expect("four"));
let spare = spare_cluster(&fixture);
let (one, two) = (spare - 1, spare);
let chained = |marked: bool| {
let mut bytes = fixture.clone();
bytes[stream + 1] &= !SECONDARY_NO_FAT_CHAIN;
refresh_set_checksum(&mut bytes, file);
for (from, to) in [
(first, one),
(one, two),
(two, super::super::ondisk::END_OF_CHAIN),
] {
let at = table_at(&bytes, from);
bytes[at..at + 4].copy_from_slice(&to.to_le_bytes());
}
mark(&mut bytes, one, marked);
mark(&mut bytes, two, marked);
bytes
};
// The file still reads its own byte count, whatever the chain holds past it.
let marked = chained(true);
let mut r = lenient(&marked);
let node = r.lookup(b"/F.BIN").expect("look up");
assert_eq!(r.read_data(&node).expect("read").len(), 300);
let found = scan_of(&chained(true));
let past: Vec<&Finding> = found
.iter()
.filter(|f| {
f.detail
.contains("bytes of clusters and its stream records 300")
})
.collect();
assert_eq!(past.len(), 1, "{found:#?}");
assert_eq!(past[0].severity, Severity::Conformance);
assert!(
!found
.iter()
.any(|f| f.detail.contains("reached by nothing")),
"{found:#?}"
);
// Claimed, so a bitmap calling them free is held to it as well.
let found = scan_of(&chained(false));
assert_eq!(
found
.iter()
.filter(|f| f.detail.contains("the allocation bitmap says it is free"))
.count(),
2,
"{found:#?}"
);
}
/// The cluster at `index` of the chain beginning at `first`, read from the table.
fn chain_at(bytes: &[u8], first: u32, index: u32) -> u32 {
let mut cluster = first;
for _ in 0..index {
let at = table_at(bytes, cluster);
cluster = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four"));
}
cluster
}
/// Move cluster `index` of the chain beginning at `first` to the free cluster `to`: its
/// bytes, the link to it and its own link, and the bitmap's account of both — written to
/// the bitmap before the move, so a chain that is the bitmap's own carries them along. The
/// cluster it leaves is zeroed.
fn relocate(bytes: &mut [u8], first: u32, index: u32, to: u32) {
// Every offset is taken before anything moves: the volume does not open between the
// edits below.
let before = chain_at(bytes, first, index - 1);
let moved = chain_at(bytes, first, index);
let links = [
table_at(bytes, before),
table_at(bytes, to),
table_at(bytes, moved),
];
let after = u32::from_le_bytes(bytes[links[2]..links[2] + 4].try_into().expect("four"));
let size = reader(bytes).layout().bytes_per_cluster as usize;
let (from, into) = (cluster_at(bytes, moved), cluster_at(bytes, to));
mark(bytes, to, true);
mark(bytes, moved, false);
let held = bytes[from..from + size].to_vec();
bytes[into..into + size].copy_from_slice(&held);
// Emptied, so a reader that took the old place for granted reads nothing it wants.
bytes[from..from + size].fill(0);
for (at, link) in links.into_iter().zip([to, after, 0]) {
bytes[at..at + 4].copy_from_slice(&link.to_le_bytes());
}
}
/// A volume of six mebibytes, which convention formats at 512-byte clusters: sixteen slots
/// a cluster, an up-case table of twelve clusters, and a bitmap of three.
fn small_clusters(source: TreeBuilder) -> Vec<u8> {
format(source, 6 << 20, FormatOptions::new(0x1234_5678))
.expect("format")
.into_bytes()
}
#[test]
fn a_resident_whose_chain_is_not_consecutive_is_read_through_the_table() {
// The up-case table and the bitmap are found by their chains (documented), and a
// driver may have placed either anywhere. Each is given a second cluster that is not
// the one after its first, and read whole.
let fixture = small_clusters(TreeBuilder::new().file(
b"/Mixed Case.TXT".to_vec(),
b"folded",
meta(0o644),
));
let layout = *reader(&fixture).layout();
assert_eq!(layout.bytes_per_cluster, 512);
assert!(
layout.upcase_bytes > 512 && layout.bitmap_bytes > 512,
"{layout:?}"
);
let spare = spare_cluster(&fixture);
for (what, first) in [
("the up-case table", layout.upcase_cluster),
("the allocation bitmap", layout.bitmap_cluster),
] {
let mut bytes = fixture.clone();
relocate(&mut bytes, first, 1, spare);
assert_eq!(
chain_at(&bytes, first, 1),
spare,
"{what}: the fixture's chain"
);
assert_ne!(spare, first + 1, "{what}: not consecutive");
// A strict open reads the table's checksum through the chain, and the folding the
// table holds is what finds the name in another case.
let mut r = Reader::open(Cursor::new(bytes.as_slice()))
.unwrap_or_else(|e| panic!("{what}: {e}"));
assert!(r.lookup(b"/mixed case.txt").is_ok(), "{what}");
assert!(scan_of(&bytes).is_empty(), "{what}: {:#?}", scan_of(&bytes));
}
}
#[test]
fn an_entry_set_crossing_from_one_cluster_to_the_next_is_read_whole() {
// Sixteen slots a cluster, and sets of three and four slots behind the root's own
// entries, so some set begins in one cluster and ends in the next.
let mut source = TreeBuilder::new();
let mut want = Vec::new();
for n in 0..12u8 {
let name = if n % 2 == 0 {
format!("/F{n}.TXT")
} else {
format!("/a name of twenty units {n:02}.txt")
};
source = source.file(name.clone().into_bytes(), vec![n; 40], meta(0o644));
want.push((name, vec![n; 40]));
}
let bytes = small_clusters(source);
let mut r = reader(&bytes);
let root = r.root();
let mut slots: Vec<(EntryType, u32, u32)> = Vec::new();
r.for_each_slot::<ReadError>(&root, |_, slot| {
slots.push((slot.entry_type(), slot.bytes[1].into(), slot.cluster));
Ok(ControlFlow::Continue(()))
})
.expect("the root's slots");
let crossing = slots
.iter()
.enumerate()
.any(|(at, &(kind, count, cluster))| {
kind == EntryType::FILE
&& slots
.get(at + count as usize)
.is_some_and(|&(_, _, last)| last != cluster)
});
assert!(crossing, "no set crosses a cluster: {slots:?}");
for (name, contents) in want {
let node = r.lookup(name.as_bytes()).expect("look up");
assert_eq!(r.read_data(&node).expect("read"), contents, "{name}");
}
assert!(scan_of(&bytes).is_empty(), "{:#?}", scan_of(&bytes));
}
#[test]
fn a_name_carrying_a_character_the_format_reserves_is_named_and_handed_back() {
let mut bytes = image_of(TreeBuilder::new().file(b"/AB.TXT".to_vec(), b"x", meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "AB.TXT");
// The second unit of the name, `B`, becomes `:`, and the hash follows it so the case is
// the character alone.
let name = set + 2 * DIR_ENTRY_SIZE + 2;
bytes[name + 2..name + 4].copy_from_slice(&u16::from(b':').to_le_bytes());
let units: Vec<u16> = "A:.TXT".encode_utf16().collect();
let hash = name_hash(&reader(&bytes).upcase.fold(&units));
bytes[set + DIR_ENTRY_SIZE + 4..set + DIR_ENTRY_SIZE + 6]
.copy_from_slice(&hash.to_le_bytes());
refresh_set_checksum(&mut bytes, set);
assert!(matches!(
root_entries(&bytes),
Err(ReadError::ReservedCharacter { code: 0x3a, .. })
));
assert!(
lenient_paths(&bytes).contains(&b"/A:.TXT".to_vec()),
"handed back as stored"
);
let found = scan_of(&bytes);
assert!(
found
.iter()
.any(|f| f.detail.contains("0x003a") && f.severity == Severity::Conformance),
"{found:#?}"
);
}
#[test]
fn two_names_the_volume_folds_to_one_are_integrity_damage() {
// `ab.txt` beside `AB.TXT`: one name to the volume's up-case table, which the writer
// refuses and a lookup cannot choose between.
let mut bytes = image_of(
TreeBuilder::new()
.file(b"/AB.TXT".to_vec(), b"1", meta(0o644))
.file(b"/AC.TXT".to_vec(), b"2", meta(0o644)),
);
let root = reader(&bytes).layout().first_cluster_of_root;
let set = set_at(&bytes, root, "AC.TXT");
let name = set + 2 * DIR_ENTRY_SIZE + 2;
bytes[name + 2..name + 4].copy_from_slice(&u16::from(b'b').to_le_bytes());
bytes[name..name + 2].copy_from_slice(&u16::from(b'a').to_le_bytes());
let units: Vec<u16> = "ab.TXT".encode_utf16().collect();
let hash = name_hash(&reader(&bytes).upcase.fold(&units));
bytes[set + DIR_ENTRY_SIZE + 4..set + DIR_ENTRY_SIZE + 6]
.copy_from_slice(&hash.to_le_bytes());
refresh_set_checksum(&mut bytes, set);
let found = scan_of(&bytes);
let named: Vec<&Finding> = found
.iter()
.filter(|f| {
f.detail
.contains("once folded through the volume's up-case table")
})
.collect();
assert_eq!(named.len(), 1, "{found:#?}");
assert_eq!(named[0].severity, Severity::Integrity);
assert!(
Reader::open(Cursor::new(bytes.as_slice()))
.expect("open")
.walk()
.is_err(),
"a strict walk refuses it"
);
let listed = lenient_paths(&bytes);
assert!(listed.contains(&b"/AB.TXT".to_vec()) && listed.contains(&b"/ab.TXT".to_vec()));
}
#[test]
fn an_entry_after_the_end_marker_is_named_once_and_never_handed_back() {
let mut bytes = image_of(TreeBuilder::new().file(b"/XX".to_vec(), b"x", meta(0o644)));
let root = reader(&bytes).layout().first_cluster_of_root;
let at = cluster_at(&bytes, root);
let set = set_at(&bytes, root, "XX");
// The terminator moved ahead of the set, so the set is past the end of the directory.
assert!(set > at);
bytes[set] = 0;
// ...and a used slot behind it, which every driver stops before reaching.
let orphan = set + 4 * DIR_ENTRY_SIZE;
bytes[orphan] = EntryType::VOLUME_GUID.0;
let err = root_entries(&bytes).expect_err("a strict read refuses");
assert!(matches!(err, ReadError::EntriesAfterEnd { .. }), "{err}");
let entries = root_entries_lenient(&bytes);
assert!(entries.is_empty(), "nothing past the marker is a name");
}
// -- the allocation record ----------------------------------------------------------
#[test]
fn a_cluster_a_stream_occupies_and_the_bitmap_calls_free_is_named() {
// The bitmap is the volume's record of what is in use, so a stream occupying a
// cluster it calls free is a volume in which the next allocation overwrites a file.
// It is also the disagreement the checker misses: `fsck.exfat` objects only when a
// cluster a file *chains through* is marked free, and every stream this writer emits
// chains through nothing.
let mut bytes =
image_of(TreeBuilder::new().file(b"/F.BIN".to_vec(), vec![0x5a; 300], meta(0o644)));
let (root, bitmap_cluster) = {
let r = reader(&bytes);
(r.layout().first_cluster_of_root, r.layout().bitmap_cluster)
};
let stream = set_at(&bytes, root, "F.BIN") + DIR_ENTRY_SIZE;
let first = u32::from_le_bytes(bytes[stream + 20..stream + 24].try_into().unwrap());
let bit = (first - FIRST_CLUSTER) as usize;
let at = cluster_at(&bytes, bitmap_cluster) + bit / 8;
assert_ne!(bytes[at] & (1 << (bit % 8)), 0, "the bit was set");
bytes[at] &= !(1 << (bit % 8));
let found = scan_of(&bytes);
assert!(
found
.iter()
.any(|a| a.detail.contains("the allocation bitmap says it is free")),
"{found:#?}"
);
// The volume still reads: the disagreement is about the record, not about the bytes.
let mut r = lenient(&bytes);
let node = r.lookup(b"/F.BIN").expect("look up");
assert_eq!(r.read_data(&node).expect("read").len(), 300);
}
#[test]
fn clusters_the_bitmap_holds_and_nothing_reaches_are_named() {
let mut bytes = image();
let bitmap = cluster_at(&bytes, reader(&bytes).layout().bitmap_cluster);
// Two bits high in the bitmap, for clusters nothing on the volume owns.
bytes[bitmap + 40] |= 0b1001;
let found = scan_of(&bytes);
let lost = found
.iter()
.find(|a| a.detail.contains("reached by nothing"))
.expect("the clusters are named");
assert!(lost.detail.contains('2'), "{}", lost.detail);
assert_eq!(lost.severity, Severity::Conformance);
}
#[test]
fn a_reserved_table_entry_the_format_fixes_is_held_to_it() {
let mut bytes = image();
let fat = reader(&bytes).layout().fat_offset as usize
* reader(&bytes).layout().bytes_per_sector as usize;
bytes[fat + 4..fat + 8].copy_from_slice(&0u32.to_le_bytes());
let found = scan_of(&bytes);
assert!(
found.iter().any(|a| a.detail.contains("table entry 1")),
"{found:#?}"
);
}
#[test]
fn a_clean_volume_scans_clean_at_every_cluster_size_the_writer_reaches() {
// The scan's own negative control: it has to be silent on a volume with nothing wrong
// with it, or nothing above means anything. Three geometries, so the bitmap spans one
// cluster on one of them and several on another.
use crate::exfat::{ClusterSize, PlanRequest};
for (bytes_total, cluster) in [
(32u64 << 20, ClusterSize::Bytes(512)),
(64 << 20, ClusterSize::Auto),
(256 << 20, ClusterSize::Bytes(128 << 10)),
] {
let options = FormatOptions::new(7).plan(PlanRequest::new(0).cluster_size(cluster));
let image = format(tree(), bytes_total, options).expect("format");
let bytes = image.into_bytes();
let mut r = reader(&bytes);
let report = r.scan();
assert!(
report.is_clean(),
"{bytes_total} at {cluster:?}:\n{}",
report.to_report().to_table()
);
assert_eq!(paths(&bytes).len(), 5);
}
}
// -- the bounds ----------------------------------------------------------------------
#[test]
fn a_walk_stops_at_the_cap_a_caller_set() {
let bytes = image();
let mut r = Reader::open_with(
Cursor::new(&bytes[..]),
&OpenOptions::new().limits(Limits::new().max_walk_entries(2)),
)
.expect("open");
assert!(matches!(
r.walk(),
Err(ReadError::WalkTooLarge { limit: 2 })
));
}
#[test]
fn a_whole_file_read_stops_at_the_cap_a_caller_set() {
let bytes = image();
let mut r = Reader::open_with(
Cursor::new(&bytes[..]),
&OpenOptions::new().limits(Limits::new().max_file_bytes(1024)),
)
.expect("open");
let node = r.lookup(b"/BIG.BIN").expect("look up");
assert!(matches!(
r.read_data(&node),
Err(ReadError::FileTooLarge { size: 9_000, .. })
));
// And a read into a caller's own buffer is bounded by the buffer instead, so a
// partial read stays representable rather than becoming a refusal.
let mut buf = [0u8; 16];
assert_eq!(r.read_into(&node, 0, &mut buf).expect("read"), 16);
}
#[test]
fn a_directory_that_points_at_itself_is_refused_strictly_and_bounded_leniently() {
// Nothing in a directory entry says it does not point back up the tree. Descending
// into a directory only the first time its first cluster is reached is what bounds
// the walk, and the set checksum is refreshed so the cycle is what stops it. An exFAT
// directory has one name, so a strict walk refuses the volume for the repeat.
let mut bytes = image_of(
TreeBuilder::new()
.directory(b"/a".to_vec(), meta(0o755))
.directory(b"/a/b".to_vec(), meta(0o755)),
);
let root = reader(&bytes).layout().first_cluster_of_root;
let a_cluster = {
let mut r = reader(&bytes);
let node = r.lookup(b"/a").expect("look up");
node.storage.first_cluster().expect("a directory has one")
};
let set = set_at(&bytes, a_cluster, "b");
let stream = set + DIR_ENTRY_SIZE;
bytes[stream + 20..stream + 24].copy_from_slice(&a_cluster.to_le_bytes());
refresh_set_checksum(&mut bytes, set);
assert_ne!(a_cluster, root);
let err = reader(&bytes).walk().expect_err("a strict walk refuses it");
assert!(
matches!(err, ReadError::RepeatedDirectory { cluster } if cluster == a_cluster),
"{err}"
);
let names: Vec<Vec<u8>> = lenient(&bytes)
.walk()
.expect("a lenient walk is bounded")
.into_iter()
.map(|e| e.path)
.collect();
assert_eq!(names, vec![b"/a".to_vec(), b"/a/b".to_vec()]);
}
#[test]
fn a_directory_ending_on_the_heaps_last_cluster_is_read_rather_than_refused() {
// The fencepost a consecutive run invites: the cluster after a run is arithmetic, and
// asking for the one past the last would refuse a directory that ends exactly where
// the heap does — for running past an end it never reached. Nothing this writer
// places lands there, which is why it is built rather than found.
let mut bytes = image_of(TreeBuilder::new().directory(b"/d".to_vec(), meta(0o755)));
let (root, last) = {
let r = reader(&bytes);
let layout = r.layout();
(
layout.first_cluster_of_root,
FIRST_CLUSTER + layout.cluster_count - 1,
)
};
let set = set_at(&bytes, root, "d");
let stream = set + DIR_ENTRY_SIZE;
bytes[stream + 20..stream + 24].copy_from_slice(&last.to_le_bytes());
refresh_set_checksum(&mut bytes, set);
let mut r = lenient(&bytes);
let node = r.lookup(b"/d").expect("look the directory up");
assert_eq!(node.storage, Storage::Contiguous(last));
// The cluster holds zeros, which is an empty directory: the first slot ends it.
assert!(r.read_dir(&node).expect("read the last cluster").is_empty());
}
#[test]
fn a_directory_whose_chain_repeats_a_cluster_is_refused_rather_than_followed() {
let mut bytes = image();
let (root, fat) = {
let r = reader(&bytes);
(
r.layout().first_cluster_of_root,
r.layout().fat_offset as usize * r.layout().bytes_per_sector as usize,
)
};
// The root's own chain, pointed back at itself.
let entry = fat + root as usize * 4;
bytes[entry..entry + 4].copy_from_slice(&root.to_le_bytes());
let err = open_err(&bytes, ReadPolicy::Strict);
assert!(matches!(err, ReadError::ChainTooLong { .. }), "{err}");
}
#[test]
fn a_reader_never_panics_on_mangled_images() {
// The never-panic contract: opening and every read path return errors on malformed
// bytes, never crash. A deterministic smoke test over degenerate geometry,
// truncations, and bit-flips of a valid image; the cargo-fuzz target in fuzz/ is the
// exhaustive version.
let image = image();
fn drive(bytes: &[u8]) {
if let Ok(mut r) = Reader::open(Cursor::new(bytes)) {
let _ = r.volume_label();
if let Ok(entries) = r.walk() {
for e in &entries {
let _ = r.read_data(&e.node);
}
for e in &entries {
let _ = r.lookup(&e.path);
}
}
}
if let Ok(mut r) = Reader::open_with(
Cursor::new(bytes),
&OpenOptions::new().policy(ReadPolicy::Lenient),
) {
let report = r.scan();
let _ = report.to_report().to_json();
let _ = report.to_report().to_table();
let _ = r.walk();
}
// At a nonzero base, which drives the base-relative addressing a volume inside a
// larger image is read through.
if let Ok(mut r) = Reader::open_with(
Cursor::new(bytes),
&OpenOptions::new().base(512).policy(ReadPolicy::Lenient),
) {
let _ = r.scan();
}
}
drive(&image);
// Degenerate geometry that would divide by zero, overflow, or address outside the
// volume if unguarded. Every one is a field of the Main Boot Sector at sector 0.
for (off, len, fill) in [
(72usize, 8usize, 0xffu8), // VolumeLength enormous
(80, 4, 0xff), // FatOffset past the volume
(84, 4, 0xff), // FatLength enormous
(88, 4, 0xff), // ClusterHeapOffset past the volume
(92, 4, 0xff), // ClusterCount enormous
(96, 4, 0xff), // FirstClusterOfRootDirectory outside the heap
(108, 1, 0x00), // BytesPerSectorShift zero
(108, 1, 0xff), // BytesPerSectorShift enormous
(109, 1, 0xff), // SectorsPerClusterShift enormous
(110, 1, 0x00), // NumberOfFats zero
] {
let mut mangled = image.clone();
mangled[off..off + len].fill(fill);
drive(&mangled);
}
// Truncations at assorted lengths.
for len in [0usize, 1, 511, 512, 513, 4096, 6144, 65_536, 1 << 20] {
drive(&image[..len.min(image.len())]);
}
// Deterministic single-byte flips across the metadata region, one image reused
// (flip, drive, restore) so the sweep stays cheap.
let mut flip = image.clone();
let span = flip.len().min(1 << 20);
let mut i = 0usize;
while i < span {
let orig = flip[i];
flip[i] ^= 0xff;
drive(&flip);
flip[i] = orig;
i += 4093; // a prime stride so flips land on varied field offsets
}
// A few fixed non-image patterns.
drive(&vec![0x00u8; 1 << 16]);
drive(&vec![0xffu8; 1 << 16]);
let ramp: Vec<u8> = (0..1u32 << 16).map(|k| (k % 256) as u8).collect();
drive(&ramp);
}
// -- the shared surface --------------------------------------------------------------
#[test]
fn the_extraction_surface_answers_for_every_node_a_walk_reaches() {
// What a sink sees, and the one thing that must be complete however little the format
// records: an owner and a mode, both invented, both said to be.
let bytes = image();
let mut r = reader(&bytes);
let synthesis = Synthesis::new();
let mut seen = Vec::new();
r.walk_tree::<TreeError, _>(|reader, entry| {
let attrs = reader.stat(&entry.node, &synthesis)?;
assert!(attrs.synthesized.contains(&Property::Ownership));
assert!(attrs.synthesized.contains(&Property::Permissions));
assert!(attrs.xattrs.is_empty());
// No second name for a node: the format has none, so two paths are two nodes.
assert_eq!(entry.shared, None);
seen.push((entry.path.clone(), entry.kind));
Ok(())
})
.expect("walk");
assert_eq!(seen[0].0, Vec::<u8>::new(), "the root comes first");
assert_eq!(seen.len(), 6);
assert!(matches!(seen[1].1, NodeKind::File { size: 9_000 }));
// A link target is an error rather than a value, this family having no links at all.
let root = r.root();
assert!(matches!(
r.link_target(&root),
Err(TreeError::Malformed { .. })
));
}
#[test]
fn a_read_only_file_comes_back_with_its_write_bits_cleared() {
// The one permission bit the format holds. The other eight came from the caller and
// nothing in the volume speaks to them, which is why both are named as invented.
let bytes = image();
let mut r = reader(&bytes);
let node = r
.lookup(b"/DCIM/A name long enough to need two entries.txt")
.expect("look up");
let attrs = r.stat(&node, &Synthesis::new()).expect("stat");
assert_eq!(attrs.meta.mode & 0o222, 0);
}
#[test]
fn every_read_error_answers_with_an_anomaly_that_says_where_it_was() {
// Exhaustive by construction: a variant added without a case here is a variant whose
// severity nobody chose. The list is the enum's, and the assertion is only that each
// answers rather than what it answers, which the cases above pin one at a time.
let all = [
ReadError::Io {
kind: std::io::ErrorKind::UnexpectedEof,
message: "x".to_string(),
},
ReadError::Parse(ParseError::TooShort {
structure: "x",
need: 1,
got: 0,
}),
ReadError::BadBootSector {
detail: "x".to_string(),
},
ReadError::TexFat,
ReadError::FatCount { count: 3 },
ReadError::BootChecksumMismatch {
sector: 0,
computed: 1,
stored: 2,
},
ReadError::BootChecksumSectorSplit { sector: 12 },
ReadError::BackupBootRegionDiffers {
sector: 12,
detail: "x".to_string(),
},
ReadError::UnknownMinorRevision { minor: 3 },
ReadError::BadExtendedBootSignature {
sector: 1,
found: 0,
expected: EXTENDED_BOOT_SIGNATURE,
},
ReadError::ClusterOutOfRange { cluster: 9 },
ReadError::BadChainEntry {
cluster: 9,
entry: 0,
},
ReadError::BadClusterInChain {
cluster: BAD_CLUSTER,
},
ReadError::ChainTooLong {
start: 2,
clusters: 4,
},
ReadError::StreamTooShort {
start: 2,
declared: 8,
held: 4,
},
ReadError::BadReservedEntry {
index: 1,
found: 0,
expected: 1,
},
ReadError::MissingResident { resident: "x" },
ReadError::UpcaseChecksumMismatch {
computed: 1,
stored: 2,
},
ReadError::UpcaseTooLong {
bytes: 1 << 40,
limit: MAX_UPCASE_BYTES,
},
ReadError::BitmapWrongSize {
bytes: 1,
clusters: 2,
},
ReadError::SetChecksumMismatch {
index: 0,
computed: 1,
stored: 2,
},
ReadError::IncompleteEntrySet {
index: 0,
detail: "x".to_string(),
},
ReadError::StraySecondaryEntry { index: 0 },
ReadError::UnknownCriticalEntry {
index: 0,
entry_type: 0x9F,
},
ReadError::IllFormedName { index: 0 },
ReadError::NameHashMismatch {
index: 0,
computed: 1,
stored: 2,
},
ReadError::HostileName { index: 0 },
ReadError::ReservedCharacter {
index: 0,
code: 0x3a,
},
ReadError::IndistinguishableNames { index: 7, first: 4 },
ReadError::DirectoryValidLength {
index: 0,
valid: 0,
declared: 4096,
},
ReadError::ChainPastLength {
start: 5,
declared: 300,
held: 12_288,
},
ReadError::VolumeGuidWithSecondaries { index: 0, count: 1 },
ReadError::ExcessNameEntries {
want: 1,
have: 2,
index: 0,
},
ReadError::MisplacedRootEntry {
index: 0,
entry_type: "x",
},
ReadError::DuplicateRootEntry {
index: 0,
entry_type: "x",
},
ReadError::LabelTooLong {
count: 200,
limit: MAX_LABEL_UNITS,
},
ReadError::LabelNulUnit,
ReadError::LabelForbiddenCharacter { ch: '/' },
ReadError::SecondBitmap,
ReadError::BitmapReservedFlags { bits: 0x80 },
ReadError::UpcaseMandatoryMapping {
character: 0x61,
maps_to: 0x61,
},
ReadError::EntriesAfterEnd { index: 0 },
ReadError::DirectoryWithoutAllocation { index: 0 },
ReadError::StreamWithoutAllocation {
index: 0,
declared: 9_000,
},
ReadError::AllocationWithoutLength {
index: 0,
first_cluster: 5,
},
ReadError::StreamPastHeap {
declared: 1 << 40,
limit: 1 << 20,
},
ReadError::DirectoryTooLong {
index: 0,
declared: 1 << 30,
limit: MAX_DIRECTORY_BYTES,
},
ReadError::DirectoryLengthNotClusters {
index: 0,
declared: 1,
bytes_per_cluster: 4096,
},
ReadError::ReservedAttributes {
index: 0,
bits: 0xF008,
},
ReadError::AllocationNotPossible { index: 0 },
ReadError::NoFatChainWithoutAllocation { index: 0 },
ReadError::MalformedTimestamp {
index: 0,
field: "creation time",
},
ReadError::ValidLengthPastEnd {
valid: 2,
declared: 1,
},
ReadError::ValidLengthTrails {
valid: 1,
declared: 2,
},
ReadError::ClusterNotAllocated { cluster: 2 },
ReadError::LostClusters { count: 1, first: 2 },
ReadError::CrossLinkedCluster { cluster: 2 },
ReadError::PercentInUseOutOfRange { stated: 200 },
ReadError::PercentInUseStale {
stated: 4,
in_use: 10,
clusters: 15_872,
actual: 0,
},
ReadError::VolumeDirty,
ReadError::MediaFailure,
ReadError::NotFound {
path: b"/x".to_vec(),
},
ReadError::NotADirectory {
path: b"/x".to_vec(),
},
ReadError::FileTooLarge { size: 2, limit: 1 },
ReadError::PathTooLong { limit: MAX_PATH },
ReadError::WalkTooLarge { limit: 1 },
];
for err in all {
let anomaly = err.anomaly();
assert!(!anomaly.detail.is_empty(), "{err:?}");
// The projection too: a coordinate and a byte offset are arithmetic over numbers
// an image supplied, and the family and category ride along.
let finding = anomaly.to_finding(512);
assert_eq!(finding.family, Family::ExFat);
assert_eq!(finding.category, anomaly.category.as_str());
}
}
#[test]
fn every_category_names_itself() {
for category in [
Category::BootRegion,
Category::AllocationTable,
Category::AllocationBitmap,
Category::UpcaseTable,
Category::Directory,
Category::Source,
] {
assert!(!category.as_str().is_empty());
}
}
/// A little-endian 64-bit field of `bytes` at `at`, for a case that reads one back raw.
fn bytes_u64(bytes: &[u8], at: usize) -> u64 {
u64::from_le_bytes(bytes[at..at + 8].try_into().expect("eight bytes"))
}
#[test]
fn the_recommended_table_is_what_a_volume_this_crate_wrote_folds_through() {
// The writer lays down the mapping every implementation writes, and the reader reads
// whatever is there — so on this crate's own volumes the two are the same table, and
// that is a fact worth asserting rather than assuming.
let bytes = image();
let r = reader(&bytes);
let recommended = UpcaseTable::recommended();
assert_eq!(r.upcase().folded_units(), recommended.folded_units());
for unit in [b'a' as u16, 0x00E9, 0x03B1, 0x0430, 0x00DF] {
assert_eq!(r.upcase().fold_unit(unit), recommended.fold_unit(unit));
}
assert_eq!(RECOMMENDED_UPCASE_TABLE.len(), 2918);
assert_eq!(BOOT_CHECKSUM_SKIPS.len(), 3);
}
}