summaryrefslogtreecommitdiffstats
path: root/src/VBox/Runtime/common/fs/isomaker.cpp
blob: 9a1c4f8d19638544128dee2db6934cbb8975aefd (plain)
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
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
/* $Id: isomaker.cpp $ */
/** @file
 * IPRT - ISO Image Maker.
 */

/*
 * Copyright (C) 2017-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
 * in the VirtualBox distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 *
 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP RTLOGGROUP_FS
#include "internal/iprt.h"
#include <iprt/fsisomaker.h>

#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/buildconfig.h>
#include <iprt/err.h>
#include <iprt/ctype.h>
#include <iprt/md5.h>
#include <iprt/file.h>
#include <iprt/list.h>
#include <iprt/log.h>
#include <iprt/mem.h>
#include <iprt/path.h>
#include <iprt/string.h>
#include <iprt/vfs.h>
#include <iprt/vfslowlevel.h>
#include <iprt/zero.h>
#include <iprt/formats/iso9660.h>

#include <internal/magics.h>


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** Asserts valid handle, returns @a a_rcRet if not. */
#define RTFSISOMAKER_ASSERT_VALID_HANDLE_RET_EX(a_pThis, a_rcRet) \
    do { AssertPtrReturn(a_pThis, a_rcRet); \
         AssertReturn((a_pThis)->uMagic == RTFSISOMAKERINT_MAGIC, a_rcRet); \
    } while (0)

/** Asserts valid handle, returns VERR_INVALID_HANDLE if not. */
#define RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(a_pThis) RTFSISOMAKER_ASSERT_VALID_HANDLE_RET_EX(a_pThis, VERR_INVALID_HANDLE)

/** The sector size. */
#define RTFSISOMAKER_SECTOR_SIZE                _2K
/** The sector offset mask. */
#define RTFSISOMAKER_SECTOR_OFFSET_MASK         (_2K - 1)
/** Maximum number of objects. */
#define RTFSISOMAKER_MAX_OBJECTS                _16M
/** Maximum number of objects per directory. */
#define RTFSISOMAKER_MAX_OBJECTS_PER_DIR        _256K /**< @todo check limit */

/** Number of bytes to store per dir record when using multiple extents. */
#define RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE    UINT32_C(0xfffff800)

/** UTF-8 name buffer.  */
#define RTFSISOMAKER_MAX_NAME_BUF               768

/** Max symbolic link target length.  */
#define RTFSISOMAKER_MAX_SYMLINK_TARGET_LEN     260

/** TRANS.TBL left padding length.
 * We keep the amount of padding low to avoid wasing memory when generating
 * these long obsolete files. */
#define RTFSISOMAKER_TRANS_TBL_LEFT_PAD         12

/** Tests if @a a_ch is in the set of d-characters. */
#define RTFSISOMAKER_IS_IN_D_CHARS(a_ch)        (RT_C_IS_UPPER(a_ch) || RT_C_IS_DIGIT(a_ch) || (a_ch) == '_')

/** Tests if @a a_ch is in the set of d-characters when uppercased. */
#define RTFSISOMAKER_IS_UPPER_IN_D_CHARS(a_ch)  (RT_C_IS_ALNUM(a_ch) || (a_ch) == '_')


/** Calculates the path table record size given the name length.
 * @note  The root directory length is 1 (name byte is 0x00), we make sure this
 *        is the case in rtFsIsoMakerNormalizeNameForNamespace. */
#define RTFSISOMAKER_CALC_PATHREC_SIZE(a_cbNameInDirRec) \
    ( RT_UOFFSETOF_DYN(ISO9660PATHREC, achDirId[(a_cbNameInDirRec) + ((a_cbNameInDirRec) & 1)]) )



/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/** Pointer to an ISO maker object name space node. */
typedef struct RTFSISOMAKERNAME *PRTFSISOMAKERNAME;
/** Pointer to a const ISO maker object name space node. */
typedef struct RTFSISOMAKERNAME const *PCRTFSISOMAKERNAME;
/** Pointer to an ISO maker object name space node pointer. */
typedef PRTFSISOMAKERNAME *PPRTFSISOMAKERNAME;

/** Pointer to a common ISO image maker file system object. */
typedef struct RTFSISOMAKEROBJ *PRTFSISOMAKEROBJ;
/** Pointer to a const common ISO image maker file system object. */
typedef struct RTFSISOMAKEROBJ const *PCRTFSISOMAKEROBJ;

/** Pointer to a ISO maker file object. */
typedef struct RTFSISOMAKERFILE *PRTFSISOMAKERFILE;
/** Pointer to a const ISO maker file object. */
typedef struct RTFSISOMAKERFILE const *PCRTFSISOMAKERFILE;

/**
 * Filesystem object type.
 */
typedef enum RTFSISOMAKEROBJTYPE
{
    RTFSISOMAKEROBJTYPE_INVALID = 0,
    RTFSISOMAKEROBJTYPE_DIR,
    RTFSISOMAKEROBJTYPE_FILE,
    RTFSISOMAKEROBJTYPE_SYMLINK,
    RTFSISOMAKEROBJTYPE_END
} RTFSISOMAKEROBJTYPE;

/**
 * Extra name space information required for directories.
 */
typedef struct RTFSISOMAKERNAMEDIR
{
    /** The location of the directory data. */
    uint64_t                offDir;
    /** The size of the directory. */
    uint32_t                cbDir;
    /** Number of children. */
    uint32_t                cChildren;
    /** Sorted array of children. */
    PPRTFSISOMAKERNAME      papChildren;
    /** The translate table file. */
    PRTFSISOMAKERFILE       pTransTblFile;

    /** The offset in the path table (ISO-9660).
     * This is set when finalizing the image.  */
    uint32_t                offPathTable;
    /** The path table identifier of this directory (ISO-9660).
    * This is set when finalizing the image.  */
    uint16_t                idPathTable;
    /** The size of the first directory record (0x00 - '.'). */
    uint8_t                 cbDirRec00;
    /** The size of the second directory record (0x01 - '..'). */
    uint8_t                 cbDirRec01;
    /** Pointer to back to the namespace node this belongs to (for the finalized
     *  entry list). */
    PRTFSISOMAKERNAME       pName;
    /** Entry in the list of finalized directories. */
    RTLISTNODE              FinalizedEntry;
} RTFSISOMAKERNAMEDIR;
/** Pointer to directory specfic namespace node info. */
typedef RTFSISOMAKERNAMEDIR *PRTFSISOMAKERNAMEDIR;
/** Pointer to const directory specfic namespace node info. */
typedef const RTFSISOMAKERNAMEDIR *PCRTFSISOMAKERNAMEDIR;


/**
 * ISO maker object namespace node.
 */
typedef struct RTFSISOMAKERNAME
{
    /** Pointer to the file system object. */
    PRTFSISOMAKEROBJ        pObj;
    /** Pointer to the partent directory, NULL if root dir. */
    PRTFSISOMAKERNAME       pParent;

    /** Pointer to the directory information if this is a directory, NULL if not a
     * directory. This is allocated together with this structure, so it doesn't need
     * freeing. */
    PRTFSISOMAKERNAMEDIR    pDir;

    /** The name specified when creating this namespace node.  Helps navigating
     * the namespace when we mangle or otherwise change the names.
     * Allocated together with of this structure, no spearate free necessary. */
    const char             *pszSpecNm;

    /** Alternative rock ridge name. */
    char                   *pszRockRidgeNm;
    /** Alternative TRANS.TBL name. */
    char                   *pszTransNm;
    /** Length of pszSpecNm. */
    uint16_t                cchSpecNm;
    /** Length of pszRockRidgeNm. */
    uint16_t                cchRockRidgeNm;
    /** Length of pszTransNm. */
    uint16_t                cchTransNm;

    /** The depth in the namespace tree of this name. */
    uint8_t                 uDepth;
    /** Set if pszTransNm is allocated separately.  Normally same as pszSpecNm. */
    bool                    fRockRidgeNmAlloced : 1;
    /** Set if pszTransNm is allocated separately.  Normally same as pszSpecNm. */
    bool                    fTransNmAlloced : 1;
    /** Set if we need to emit an ER entry (root only). */
    bool                    fRockNeedER : 1;
    /** Set if we need to emit a RR entry in the directory record. */
    bool                    fRockNeedRRInDirRec : 1;
    /** Set if we need to emit a RR entry in the spill file. */
    bool                    fRockNeedRRInSpill : 1;

    /** The mode mask.
     * Starts out as a copy of RTFSISOMAKEROBJ::fMode. */
    RTFMODE                 fMode;
    /** The owner ID.
     * Starts out as a copy of RTFSISOMAKEROBJ::uid. */
    RTUID                   uid;
    /** The group ID.
     * Starts out as a copy of RTFSISOMAKEROBJ::gid. */
    RTGID                   gid;
    /** The device number if a character or block device.
     * This is for Rock Ridge.  */
    RTDEV                   Device;
    /** The number of hardlinks to report in the file stats.
     * This is for Rock Ridge.  */
    uint32_t                cHardlinks;

    /** The offset of the directory entry in the parent directory. */
    uint32_t                offDirRec;
    /** Size of the directory record (ISO-9660).
     * This is set when the image is being finalized. */
    uint16_t                cbDirRec;
    /** Number of directory records needed to cover the entire file size.  */
    uint16_t                cDirRecs;
    /** The total directory record size (cbDirRec * cDirRecs), including end of
     *  sector zero padding. */
    uint16_t                cbDirRecTotal;

    /** Rock ridge flags (ISO9660RRIP_RR_F_XXX). */
    uint8_t                 fRockEntries;
    /** Number of rock ridge data bytes in the directory record.  Unaligned! */
    uint8_t                 cbRockInDirRec;
    /** Rock ridge spill file data offset, UINT32_MAX if placed in dir record. */
    uint32_t                offRockSpill;
    /** Size of rock data in spill file. */
    uint16_t                cbRockSpill;

    /** The number of bytes the name requires in the directory record. */
    uint16_t                cbNameInDirRec;
    /** The name length. */
    uint16_t                cchName;
    /** The name. */
    RT_FLEXIBLE_ARRAY_EXTENSION
    char                    szName[RT_FLEXIBLE_ARRAY];
} RTFSISOMAKERNAME;

/**
 * A ISO maker namespace.
 */
typedef struct RTFSISOMAKERNAMESPACE
{
    /** The namespace root. */
    PRTFSISOMAKERNAME       pRoot;
    /** Total number of name nodes in the namespace. */
    uint32_t                cNames;
    /** Total number of directories in the namespace.
     * @note Appears to be unused.  */
    uint32_t                cDirs;
    /** The namespace selector (RTFSISOMAKER_NAMESPACE_XXX). */
    uint32_t                fNamespace;
    /** Offset into RTFSISOMAKERNAMESPACE of the name member. */
    uint32_t                offName;
    /** The configuration level for this name space.
     *     - For UDF and HFS namespaces this is either @c true or @c false.
     *     - For the primary ISO-9660 namespace this is 1, 2, or 3.
     *     - For the joliet namespace this 0 (joliet disabled), 1, 2, or 3. */
    uint8_t                 uLevel;
    /** The rock ridge level: 1 - enabled; 2 - with ER tag.
     * Linux behaves a little different when seeing the ER tag. */
    uint8_t                 uRockRidgeLevel;
    /** The TRANS.TBL filename if enabled, NULL if disabled.
     * When not NULL, this may be pointing to heap or g_szTransTbl. */
    char                   *pszTransTbl;
    /** The system ID (ISO9660PRIMARYVOLDESC::achSystemId). Empty if NULL.
     * When not NULL, this may be pointing to heap of g_szSystemId. */
    char                   *pszSystemId;
    /** The volume ID / label (ISO9660PRIMARYVOLDESC::achVolumeId).
     * A string representation of RTFSISOMAKERINT::ImageCreationTime if NULL. */
    char                   *pszVolumeId;
    /** The volume set ID (ISO9660PRIMARYVOLDESC::achVolumeSetId). Empty if NULL. */
    char                   *pszVolumeSetId;
    /** The publisher ID or (root) file reference (ISO9660PRIMARYVOLDESC::achPublisherId).  Empty if NULL.  */
    char                   *pszPublisherId;
    /* The data preperer ID or (root) file reference (ISO9660PRIMARYVOLDESC::achDataPreparerId). Empty if NULL. */
    char                   *pszDataPreparerId;
    /* The application ID or (root) file reference (ISO9660PRIMARYVOLDESC::achApplicationId).
     * Defaults to g_szAppIdPrimaryIso or g_szAppIdJoliet. */
    char                   *pszApplicationId;
    /** The copyright (root) file identifier (ISO9660PRIMARYVOLDESC::achCopyrightFileId).  None if NULL. */
    char                   *pszCopyrightFileId;
    /** The abstract (root) file identifier (ISO9660PRIMARYVOLDESC::achAbstractFileId). None if NULL. */
    char                   *pszAbstractFileId;
    /** The bibliographic (root) file identifier (ISO9660PRIMARYVOLDESC::achBibliographicFileId).  None if NULL. */
    char                   *pszBibliographicFileId;
} RTFSISOMAKERNAMESPACE;
/** Pointer to a namespace. */
typedef RTFSISOMAKERNAMESPACE *PRTFSISOMAKERNAMESPACE;
/** Pointer to a const namespace. */
typedef RTFSISOMAKERNAMESPACE const *PCRTFSISOMAKERNAMESPACE;


/**
 * Common base structure for the file system objects.
 *
 * The times are shared across all namespaces, while the uid, gid and mode are
 * duplicates in each namespace.
 */
typedef struct RTFSISOMAKEROBJ
{
    /** The linear list entry of the image content. */
    RTLISTNODE              Entry;
    /** The object index. */
    uint32_t                idxObj;
    /** The type of this object. */
    RTFSISOMAKEROBJTYPE     enmType;

    /** The primary ISO-9660 name space name. */
    PRTFSISOMAKERNAME       pPrimaryName;
    /** The joliet name space name. */
    PRTFSISOMAKERNAME       pJolietName;
    /** The UDF name space name. */
    PRTFSISOMAKERNAME       pUdfName;
    /** The HFS name space name. */
    PRTFSISOMAKERNAME       pHfsName;

    /** Birth (creation) time. */
    RTTIMESPEC              BirthTime;
    /** Attribute change time. */
    RTTIMESPEC              ChangeTime;
    /** Modification time. */
    RTTIMESPEC              ModificationTime;
    /** Accessed time. */
    RTTIMESPEC              AccessedTime;

    /** Owner ID. */
    RTUID                   uid;
    /** Group ID. */
    RTGID                   gid;
    /** Attributes (unix permissions bits mainly). */
    RTFMODE                 fMode;

    /** Used to make sure things like the boot catalog stays in the image even if
     * it's not mapped into any of the namespaces. */
    uint32_t                cNotOrphan;
} RTFSISOMAKEROBJ;


/**
 * File source type.
 */
typedef enum RTFSISOMAKERSRCTYPE
{
    RTFSISOMAKERSRCTYPE_INVALID = 0,
    RTFSISOMAKERSRCTYPE_PATH,
    RTFSISOMAKERSRCTYPE_VFS_FILE,
    RTFSISOMAKERSRCTYPE_COMMON,
    RTFSISOMAKERSRCTYPE_TRANS_TBL,
    RTFSISOMAKERSRCTYPE_RR_SPILL,
    RTFSISOMAKERSRCTYPE_END
} RTFSISOMAKERSRCTYPE;

/**
 * ISO maker file object.
 */
typedef struct RTFSISOMAKERFILE
{
    /** The common bit. */
    RTFSISOMAKEROBJ         Core;
    /** The file data size. */
    uint64_t                cbData;
    /** Byte offset of the data in the image.
     * UINT64_MAX until the location is finalized. */
    uint64_t                offData;

    /** The type of source object. */
    RTFSISOMAKERSRCTYPE     enmSrcType;
    /** The source data. */
    union
    {
        /** Path to the source file.
         * Allocated together with this structure.  */
        const char         *pszSrcPath;
        /** Source VFS file. */
        RTVFSFILE           hVfsFile;
        /** Source is a part of a common VFS file. */
        struct
        {
            /** The offset into the file */
            uint64_t        offData;
            /** The index of the common file. */
            uint32_t        idxSrc;
        } Common;
        /** The directory the translation table belongs to. */
        PRTFSISOMAKERNAME   pTransTblDir;
        /** The namespace for a rock ridge spill file.. */
        PRTFSISOMAKERNAMESPACE pRockSpillNamespace;
    } u;

    /** Boot info table to patch into the file.
     * This is calculated during file finalization as it needs the file location. */
    PISO9660SYSLINUXINFOTABLE pBootInfoTable;

    /** Entry in the list of finalized directories. */
    RTLISTNODE              FinalizedEntry;
} RTFSISOMAKERFILE;


/**
 * ISO maker directory object.
 *
 * Unlike files, the allocation info is name space specific and lives in the
 * corresponding RTFSISOMAKERNAMEDIR structures.
 */
typedef struct RTFSISOMAKERDIR
{
    /** The common bit. */
    RTFSISOMAKEROBJ         Core;
} RTFSISOMAKERDIR;
/** Pointer to an ISO maker directory object.  */
typedef RTFSISOMAKERDIR *PRTFSISOMAKERDIR;


/**
 * ISO maker symlink object.
 */
typedef struct RTFSISOMAKERSYMLINK
{
    /** The common bit. */
    RTFSISOMAKEROBJ         Core;
    /** The size of the rock ridge 'SL' records for this link. */
    uint16_t                cbSlRockRidge;
    /** The symbolic link target length. */
    uint16_t                cchTarget;
    /** The symbolic link target. */
    RT_FLEXIBLE_ARRAY_EXTENSION
    char                    szTarget[RT_FLEXIBLE_ARRAY];
} RTFSISOMAKERSYMLINK;
/** Pointer to an ISO maker directory object.  */
typedef RTFSISOMAKERSYMLINK *PRTFSISOMAKERSYMLINK;
/** Pointer to a const ISO maker directory object.  */
typedef const RTFSISOMAKERSYMLINK *PCRTFSISOMAKERSYMLINK;



/**
 * Instance data for a ISO image maker.
 */
typedef struct RTFSISOMAKERINT
{
    /** Magic value (RTFSISOMAKERINT_MAGIC). */
    uint32_t                uMagic;
    /** Reference counter. */
    uint32_t volatile       cRefs;

    /** Set after we've been fed the first bit of content.
     * This means that the namespace configuration has been finalized and can no
     * longer be changed because it's simply too much work to do adjustments
     * after having started to add files. */
    bool                    fSeenContent;
    /** Set once we've finalized the image structures.
     * After this no more changes are allowed.  */
    bool                    fFinalized;

    /** The primary ISO-9660 namespace. */
    RTFSISOMAKERNAMESPACE   PrimaryIso;
    /** The joliet namespace. */
    RTFSISOMAKERNAMESPACE   Joliet;
    /** The UDF namespace. */
    RTFSISOMAKERNAMESPACE   Udf;
    /** The hybrid HFS+ namespace. */
    RTFSISOMAKERNAMESPACE   Hfs;

    /** The list of objects (RTFSISOMAKEROBJ). */
    RTLISTANCHOR            ObjectHead;
    /** Number of objects in the image (ObjectHead).
     * This is used to number them, i.e. create RTFSISOMAKEROBJ::idxObj.  */
    uint32_t                cObjects;

    /** Amount of file data. */
    uint64_t                cbData;
    /** Number of volume descriptors. */
    uint32_t                cVolumeDescriptors;
    /** The image (trail) padding in bytes. */
    uint32_t                cbImagePadding;

    /** The 'now' timestamp we use for the whole image.
     * This way we'll save lots of RTTimeNow calls and have similar timestamps
     * over the whole image. */
    RTTIMESPEC              ImageCreationTime;
    /** Indicates strict or non-strict attribute handling style.
     * See RTFsIsoMakerSetAttributeStyle() for details.  */
    bool                    fStrictAttributeStyle;
    /** The default owner ID. */
    RTUID                   uidDefault;
    /** The default group ID. */
    RTGID                   gidDefault;
    /** The default file mode mask. */
    RTFMODE                 fDefaultFileMode;
    /** The default file mode mask. */
    RTFMODE                 fDefaultDirMode;

    /** Forced file mode mask (permissions only). */
    RTFMODE                 fForcedFileMode;
    /** Set if fForcedFileMode is active. */
    bool                    fForcedFileModeActive;
    /** Set if fForcedDirMode is active. */
    bool                    fForcedDirModeActive;
    /** Forced directory mode mask (permissions only). */
    RTFMODE                 fForcedDirMode;

    /** Number of common source files. */
    uint32_t                cCommonSources;
    /** Array of common source file handles. */
    PRTVFSFILE              paCommonSources;

    /** @name Boot related stuff
     * @{ */
    /** The boot catalog file. */
    PRTFSISOMAKERFILE       pBootCatFile;
    /** Per boot catalog entry data needed for updating offsets when finalizing. */
    struct
    {
        /** The type (ISO9660_ELTORITO_HEADER_ID_VALIDATION_ENTRY,
         * ISO9660_ELTORITO_HEADER_ID_SECTION_HEADER,
         * ISO9660_ELTORITO_HEADER_ID_FINAL_SECTION_HEADER,
         * ISO9660_ELTORITO_BOOT_INDICATOR_BOOTABLE or
         * ISO9660_ELTORITO_BOOT_INDICATOR_NOT_BOOTABLE). */
        uint8_t             bType;
        /** Number of entries related to this one.  This is zero for unused entries,
         *  2 for the validation entry, 2+ for section headers, and 1 for images. */
        uint8_t             cEntries;
        /** The boot file. */
        PRTFSISOMAKERFILE   pBootFile;
    }                       aBootCatEntries[64];
    /** @} */

    /** @name Finalized image stuff
     * @{ */
    /** The finalized image size. */
    uint64_t                cbFinalizedImage;
    /** System area content (sectors 0 thur 15).  This is NULL if the system area
     * are all zeros, which is often the case.   Hybrid ISOs have an MBR followed by
     * a GUID partition table here, helping making the image bootable when
     * transfered to a USB stick. */
    uint8_t                *pbSysArea;
    /** Number of non-zero system area bytes pointed to by pbSysArea.  */
    size_t                  cbSysArea;

    /** Pointer to the buffer holding the volume descriptors. */
    uint8_t                *pbVolDescs;
    /** Pointer to the primary volume descriptor. */
    PISO9660PRIMARYVOLDESC  pPrimaryVolDesc;
    /** El Torito volume descriptor. */
    PISO9660BOOTRECORDELTORITO pElToritoDesc;
    /** Pointer to the primary volume descriptor. */
    PISO9660SUPVOLDESC      pJolietVolDesc;
    /** Terminating ISO-9660 volume descriptor. */
    PISO9660VOLDESCHDR      pTerminatorVolDesc;

    /** Finalized ISO-9660 directory structures. */
    struct RTFSISOMAKERFINALIZEDDIRS
    {
        /** The image byte offset of the first directory. */
        uint64_t            offDirs;
        /** The image byte offset of the little endian path table.
         * This always follows offDirs.  */
        uint64_t            offPathTableL;
        /** The image byte offset of the big endian path table.
         * This always follows offPathTableL.  */
        uint64_t            offPathTableM;
        /** The size of the path table.   */
        uint32_t            cbPathTable;
        /** List of finalized directories for this namespace.
         * The list is in path table order so it can be generated on the fly.  The
         * directories will be ordered in the same way. */
        RTLISTANCHOR        FinalizedDirs;
        /** Rock ridge spill file. */
        PRTFSISOMAKERFILE   pRRSpillFile;
    }
    /** The finalized directory data for the primary ISO-9660 namespace. */
                            PrimaryIsoDirs,
    /** The finalized directory data for the joliet namespace. */
                            JolietDirs;

    /** The image byte offset of the first file. */
    uint64_t                offFirstFile;
    /** Finalized file head (RTFSISOMAKERFILE).
     * The list is ordered by disk location.  Files are following the
     * directories and path tables. */
    RTLISTANCHOR            FinalizedFiles;
    /** @} */

} RTFSISOMAKERINT;
/** Pointer to an ISO maker instance. */
typedef RTFSISOMAKERINT *PRTFSISOMAKERINT;

/** Pointer to the data for finalized ISO-9660 (primary / joliet) dirs. */
typedef struct RTFSISOMAKERINT::RTFSISOMAKERFINALIZEDDIRS *PRTFSISOMAKERFINALIZEDDIRS;


/**
 * Instance data of an ISO maker output file.
 */
typedef struct RTFSISOMAKEROUTPUTFILE
{
    /** The ISO maker (owns a reference). */
    PRTFSISOMAKERINT        pIsoMaker;
    /** The current file position. */
    uint64_t                offCurPos;
    /** Current file hint. */
    PRTFSISOMAKERFILE       pFileHint;
    /** Source file corresponding to pFileHint.
     * This is used when dealing with a RTFSISOMAKERSRCTYPE_VFS_FILE or
     * RTFSISOMAKERSRCTYPE_TRANS_TBL file. */
    RTVFSFILE               hVfsSrcFile;
    /** Current directory hint for the primary ISO namespace. */
    PRTFSISOMAKERNAMEDIR    pDirHintPrimaryIso;
    /** Current directory hint for the joliet namespace. */
    PRTFSISOMAKERNAMEDIR    pDirHintJoliet;
    /** Joliet directory child index hint. */
    uint32_t                iChildPrimaryIso;
    /** Joliet directory child index hint. */
    uint32_t                iChildJoliet;
} RTFSISOMAKEROUTPUTFILE;
/** Pointer to the instance data of an ISO maker output file. */
typedef RTFSISOMAKEROUTPUTFILE *PRTFSISOMAKEROUTPUTFILE;


/**
 * Directory entry type.
 */
typedef enum RTFSISOMAKERDIRTYPE
{
    /** Invalid directory entry. */
    RTFSISOMAKERDIRTYPE_INVALID = 0,
    /** Entry for the current directory, aka ".". */
    RTFSISOMAKERDIRTYPE_CURRENT,
    /** Entry for the parent directory, aka "..". */
    RTFSISOMAKERDIRTYPE_PARENT,
    /** Entry for a regular directory entry. */
    RTFSISOMAKERDIRTYPE_OTHER
} RTFSISOMAKERDIRTYPE;



/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * Help for iterating over namespaces.
 */
static const struct
{
    /** The RTFSISOMAKER_NAMESPACE_XXX indicator.  */
    uint32_t        fNamespace;
    /** Offset into RTFSISOMAKERINT of the namespace member. */
    uintptr_t       offNamespace;
    /** Offset into RTFSISOMAKERNAMESPACE of the name member. */
    uintptr_t       offName;
    /** Namespace name for debugging purposes. */
    const char     *pszName;
} g_aRTFsIsoNamespaces[] =
{
    {   RTFSISOMAKER_NAMESPACE_ISO_9660, RT_UOFFSETOF(RTFSISOMAKERINT, PrimaryIso), RT_UOFFSETOF(RTFSISOMAKEROBJ, pPrimaryName), "iso-9660" },
    {   RTFSISOMAKER_NAMESPACE_JOLIET,   RT_UOFFSETOF(RTFSISOMAKERINT, Joliet),     RT_UOFFSETOF(RTFSISOMAKEROBJ, pJolietName),  "joliet" },
    {   RTFSISOMAKER_NAMESPACE_UDF,      RT_UOFFSETOF(RTFSISOMAKERINT, Udf),        RT_UOFFSETOF(RTFSISOMAKEROBJ, pUdfName),     "udf" },
    {   RTFSISOMAKER_NAMESPACE_HFS,      RT_UOFFSETOF(RTFSISOMAKERINT, Hfs),        RT_UOFFSETOF(RTFSISOMAKEROBJ, pHfsName),     "hfs" },
};

/**
 * Translates a single namespace flag (RTFSISOMAKER_NAMESPACE_XXX) to an
 * index into g_aRTFsIsoNamespaces.
 */
static const uint8_t g_aidxRTFsIsoNamespaceFlagToIdx[] =
{
    /*[0]                               = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[RTFSISOMAKER_NAMESPACE_ISO_9660] = */ 0,
    /*[RTFSISOMAKER_NAMESPACE_JOLIET]   = */ 1,
    /*[3]                               = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[RTFSISOMAKER_NAMESPACE_UDF]      = */ 2,
    /*[5]                               = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[6]                               = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[7]                               = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[RTFSISOMAKER_NAMESPACE_HFS]      = */ 3,
    /*[9]                               = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[10]                              = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[11]                              = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[12]                              = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[13]                              = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[14]                              = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
    /*[15]                              = */ RT_ELEMENTS(g_aRTFsIsoNamespaces),
};

/** The default translation table filename. */
static const char   g_szTransTbl[] = "TRANS.TBL";
/** The default application ID for the primary ISO-9660 volume descriptor. */
static char         g_szAppIdPrimaryIso[64] = "";
/** The default application ID for the joliet volume descriptor. */
static char         g_szAppIdJoliet[64]     = "";
/** The default system ID the primary ISO-9660 volume descriptor. */
static char         g_szSystemId[64] = "";



/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static int rtFsIsoMakerObjSetName(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAMESPACE pNamespace, PRTFSISOMAKEROBJ pObj,
                                  PRTFSISOMAKERNAME pParent, const char *pchSpec, size_t cchSpec, bool fNoNormalize,
                                  PPRTFSISOMAKERNAME ppNewName);
static int rtFsIsoMakerObjUnsetName(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAMESPACE pNamespace, PRTFSISOMAKEROBJ pObj);
static int rtFsIsoMakerAddUnnamedDirWorker(PRTFSISOMAKERINT pThis, PCRTFSOBJINFO pObjInfo, PRTFSISOMAKERDIR *ppDir);
static int rtFsIsoMakerAddUnnamedFileWorker(PRTFSISOMAKERINT pThis, PCRTFSOBJINFO pObjInfo, size_t cbExtra,
                                            PRTFSISOMAKERFILE *ppFile);
static int rtFsIsoMakerObjRemoveWorker(PRTFSISOMAKERINT pThis, PRTFSISOMAKEROBJ pObj);

static ssize_t rtFsIsoMakerOutFile_RockRidgeGenSL(const char *pszTarget, uint8_t *pbBuf, size_t cbBuf);
static DECLCALLBACK(int) rtFsIsoMakerOutFile_Seek(void *pvThis, RTFOFF offSeek, unsigned uMethod, PRTFOFF poffActual);



/**
 * Creates an ISO maker instance.
 *
 * @returns IPRT status code.
 * @param   phIsoMaker          Where to return the handle to the new ISO maker.
 */
RTDECL(int) RTFsIsoMakerCreate(PRTFSISOMAKER phIsoMaker)
{
    /*
     * Do some integrity checks first.
     */
    AssertReturn(g_aRTFsIsoNamespaces[g_aidxRTFsIsoNamespaceFlagToIdx[RTFSISOMAKER_NAMESPACE_ISO_9660]].fNamespace == RTFSISOMAKER_NAMESPACE_ISO_9660,
                 VERR_ISOMK_IPE_TABLE);
    AssertReturn(g_aRTFsIsoNamespaces[g_aidxRTFsIsoNamespaceFlagToIdx[RTFSISOMAKER_NAMESPACE_JOLIET]].fNamespace   == RTFSISOMAKER_NAMESPACE_JOLIET,
                 VERR_ISOMK_IPE_TABLE);
    AssertReturn(g_aRTFsIsoNamespaces[g_aidxRTFsIsoNamespaceFlagToIdx[RTFSISOMAKER_NAMESPACE_UDF]].fNamespace      == RTFSISOMAKER_NAMESPACE_UDF,
                 VERR_ISOMK_IPE_TABLE);
    AssertReturn(g_aRTFsIsoNamespaces[g_aidxRTFsIsoNamespaceFlagToIdx[RTFSISOMAKER_NAMESPACE_HFS]].fNamespace      == RTFSISOMAKER_NAMESPACE_HFS,
                 VERR_ISOMK_IPE_TABLE);

    if (g_szAppIdPrimaryIso[0] == '\0')
        RTStrPrintf(g_szAppIdPrimaryIso, sizeof(g_szAppIdPrimaryIso), "IPRT ISO MAKER V%u.%u.%u R%s",
                    RTBldCfgVersionMajor(), RTBldCfgVersionMinor(), RTBldCfgVersionBuild(), RTBldCfgRevisionStr());
    if (g_szAppIdJoliet[0] == '\0')
        RTStrPrintf(g_szAppIdJoliet, sizeof(g_szAppIdJoliet),
                    "IPRT ISO Maker v%s r%s", RTBldCfgVersion(), RTBldCfgRevisionStr());
    if (g_szSystemId[0] == '\0')
    {
        RTStrCopy(g_szSystemId, sizeof(g_szSystemId), RTBldCfgTargetDotArch());
        RTStrToUpper(g_szSystemId);
    }

    /*
     * Create the instance with defaults.
     */
    int              rc;
    PRTFSISOMAKERINT pThis = (PRTFSISOMAKERINT)RTMemAllocZ(sizeof(*pThis));
    if (pThis)
    {
        pThis->uMagic                       = RTFSISOMAKERINT_MAGIC;
        pThis->cRefs                        = 1;
        //pThis->fSeenContent               = false;
        //pThis->fFinalized                 = false;

        pThis->PrimaryIso.fNamespace        = RTFSISOMAKER_NAMESPACE_ISO_9660;
        pThis->PrimaryIso.offName           = RT_UOFFSETOF(RTFSISOMAKEROBJ, pPrimaryName);
        pThis->PrimaryIso.uLevel            = 3; /* 30 char names, large files */
        pThis->PrimaryIso.uRockRidgeLevel   = 1;
        pThis->PrimaryIso.pszTransTbl       = (char *)g_szTransTbl;
        pThis->PrimaryIso.pszSystemId       = g_szSystemId;
        //pThis->PrimaryIso.pszVolumeId     = NULL;
        //pThis->PrimaryIso.pszSetVolumeId  = NULL;
        //pThis->PrimaryIso.pszPublisherId  = NULL;
        //pThis->PrimaryIso.pszDataPreparerId = NULL;
        pThis->PrimaryIso.pszApplicationId  = g_szAppIdPrimaryIso;
        //pThis->PrimaryIso.pszCopyrightFileId = NULL;
        //pThis->PrimaryIso.pszAbstractFileId = NULL;
        //pThis->PrimaryIso.pszBibliographicFileId = NULL;

        pThis->Joliet.fNamespace            = RTFSISOMAKER_NAMESPACE_JOLIET;
        pThis->Joliet.offName               = RT_UOFFSETOF(RTFSISOMAKEROBJ, pJolietName);
        pThis->Joliet.uLevel                = 3;
        //pThis->Joliet.uRockRidgeLevel     = 0;
        //pThis->Joliet.pszTransTbl         = NULL;
        //pThis->Joliet.pszSystemId         = NULL;
        //pThis->Joliet.pszVolumeId         = NULL;
        //pThis->Joliet.pszSetVolumeId      = NULL;
        //pThis->Joliet.pszPublisherId      = NULL;
        //pThis->Joliet.pszDataPreparerId   = NULL;
        pThis->Joliet.pszApplicationId      = g_szAppIdJoliet;
        //pThis->Joliet.pszCopyrightFileId  = NULL;
        //pThis->Joliet.pszAbstractFileId   = NULL;
        //pThis->Joliet.pszBibliographicFileId = NULL;

        pThis->Udf.fNamespace               = RTFSISOMAKER_NAMESPACE_UDF;
        pThis->Udf.offName                  = RT_UOFFSETOF(RTFSISOMAKEROBJ, pUdfName);
        //pThis->Udf.uLevel                 = 0;
        //pThis->Udf.uRockRidgeLevel        = 0;
        //pThis->Udf.pszTransTbl            = NULL;
        //pThis->Udf.uRockRidgeLevel        = 0;
        //pThis->Udf.pszTransTbl            = NULL;
        //pThis->Udf.pszSystemId            = NULL;
        //pThis->Udf.pszVolumeId            = NULL;
        //pThis->Udf.pszSetVolumeId         = NULL;
        //pThis->Udf.pszPublisherId         = NULL;
        //pThis->Udf.pszDataPreparerId      = NULL;
        //pThis->Udf.pszApplicationId       = NULL;
        //pThis->Udf.pszCopyrightFileId     = NULL;
        //pThis->Udf.pszAbstractFileId      = NULL;
        //pThis->Udf.pszBibliographicFileId = NULL;

        pThis->Hfs.fNamespace               = RTFSISOMAKER_NAMESPACE_HFS;
        pThis->Hfs.offName                  = RT_UOFFSETOF(RTFSISOMAKEROBJ, pHfsName);
        //pThis->Hfs.uLevel                 = 0;
        //pThis->Hfs.uRockRidgeLevel        = 0;
        //pThis->Hfs.pszTransTbl            = NULL;
        //pThis->Hfs.pszSystemId            = NULL;
        //pThis->Hfs.pszVolumeId            = NULL;
        //pThis->Hfs.pszSetVolumeId         = NULL;
        //pThis->Hfs.pszPublisherId         = NULL;
        //pThis->Hfs.pszDataPreparerId      = NULL;
        //pThis->Hfs.pszApplicationId       = NULL;
        //pThis->Hfs.pszCopyrightFileId     = NULL;
        //pThis->Hfs.pszAbstractFileId      = NULL;
        //pThis->Hfs.pszBibliographicFileId = NULL;

        RTListInit(&pThis->ObjectHead);
        //pThis->cObjects                   = 0;
        //pThis->cbData                     = 0;

        pThis->cVolumeDescriptors           = 3; /* primary, secondary joliet, terminator. */
        pThis->cbImagePadding               = 150 * RTFSISOMAKER_SECTOR_SIZE;

        //pThis->fStrictAttributeStyle      = false;
        //pThis->uidDefault                 = 0;
        //pThis->gidDefault                 = 0;
        pThis->fDefaultFileMode             = 0444 | RTFS_TYPE_FILE      | RTFS_DOS_ARCHIVED  | RTFS_DOS_READONLY;
        pThis->fDefaultDirMode              = 0555 | RTFS_TYPE_DIRECTORY | RTFS_DOS_DIRECTORY | RTFS_DOS_READONLY;

        //pThis->fForcedFileMode            = 0;
        //pThis->fForcedFileModeActive      = false;
        //pThis->fForcedDirModeActive       = false;
        //pThis->fForcedDirMode             = 0;

        //pThis->cCommonSources             = 0;
        //pThis->paCommonSources            = NULL;

        //pThis->pBootCatFile               = NULL;

        pThis->cbFinalizedImage             = UINT64_MAX;
        //pThis->pbSysArea                  = NULL;
        //pThis->cbSysArea                  = 0;
        //pThis->pbVolDescs                 = NULL;
        //pThis->pPrimaryVolDesc            = NULL;
        //pThis->pElToritoDesc              = NULL;
        //pThis->pJolietVolDesc             = NULL;

        pThis->PrimaryIsoDirs.offDirs       = UINT64_MAX;
        pThis->PrimaryIsoDirs.offPathTableL = UINT64_MAX;
        pThis->PrimaryIsoDirs.offPathTableM = UINT64_MAX;
        pThis->PrimaryIsoDirs.cbPathTable   = 0;
        RTListInit(&pThis->PrimaryIsoDirs.FinalizedDirs);
        //pThis->PrimaryIsoDirs.pRRSpillFile = NULL;

        pThis->JolietDirs.offDirs           = UINT64_MAX;
        pThis->JolietDirs.offPathTableL     = UINT64_MAX;
        pThis->JolietDirs.offPathTableM     = UINT64_MAX;
        pThis->JolietDirs.cbPathTable       = 0;
        RTListInit(&pThis->JolietDirs.FinalizedDirs);
        //pThis->JolietDirs.pRRSpillFile    = NULL;

        pThis->offFirstFile                 = UINT64_MAX;
        RTListInit(&pThis->FinalizedFiles);

        RTTimeNow(&pThis->ImageCreationTime);

        /*
         * Add the root directory node with idObj == 0.
         */
        PRTFSISOMAKERDIR pDirRoot;
        rc = rtFsIsoMakerAddUnnamedDirWorker(pThis, NULL /*pObjInfo*/, &pDirRoot);
        if (RT_SUCCESS(rc))
        {
            *phIsoMaker = pThis;
            return VINF_SUCCESS;
        }

        RTMemFree(pThis);
    }
    else
        rc = VERR_NO_MEMORY;
    return rc;
}


/**
 * Frees an object.
 *
 * This is a worker for rtFsIsoMakerDestroy and RTFsIsoMakerObjRemove.
 *
 * @param   pObj                The object to free.
 */
DECLINLINE(void) rtFsIsoMakerObjDestroy(PRTFSISOMAKEROBJ pObj)
{
    if (pObj->enmType == RTFSISOMAKEROBJTYPE_FILE)
    {
        PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pObj;
        switch (pFile->enmSrcType)
        {
            case RTFSISOMAKERSRCTYPE_PATH:
                pFile->u.pszSrcPath = NULL;
                break;

            case RTFSISOMAKERSRCTYPE_TRANS_TBL:
                pFile->u.pTransTblDir = NULL;
                break;

            case RTFSISOMAKERSRCTYPE_VFS_FILE:
                RTVfsFileRelease(pFile->u.hVfsFile);
                pFile->u.hVfsFile = NIL_RTVFSFILE;
                break;

            case RTFSISOMAKERSRCTYPE_COMMON:
            case RTFSISOMAKERSRCTYPE_RR_SPILL:
                break;

            case RTFSISOMAKERSRCTYPE_INVALID:
            case RTFSISOMAKERSRCTYPE_END:
                AssertFailed();
                break;

            /* no default, want warnings */
        }
        if (pFile->pBootInfoTable)
        {
            RTMemFree(pFile->pBootInfoTable);
            pFile->pBootInfoTable = NULL;
        }
    }

    RTMemFree(pObj);
}


/**
 * Frees a namespace node.
 *
 * This is a worker for rtFsIsoMakerDestroyTree and rtFsIsoMakerObjUnsetName.
 *
 * @param   pName               The node to free.
 */
DECLINLINE(void) rtFsIsoMakerDestroyName(PRTFSISOMAKERNAME pName)
{
    if (pName->fRockRidgeNmAlloced)
    {
        RTMemFree(pName->pszRockRidgeNm);
        pName->pszRockRidgeNm = NULL;
    }
    if (pName->fTransNmAlloced)
    {
        RTMemFree(pName->pszTransNm);
        pName->pszTransNm = NULL;
    }
    PRTFSISOMAKERNAMEDIR pDir = pName->pDir;
    if (pDir != NULL)
    {
        Assert(pDir->cChildren == 0);
        RTMemFree(pDir->papChildren);
        pDir->papChildren = NULL;
    }
    RTMemFree(pName);
}


/**
 * Destroys a namespace.
 *
 * @param   pNamespace          The namespace to destroy.
 */
static void rtFsIsoMakerDestroyTree(PRTFSISOMAKERNAMESPACE pNamespace)
{
    /*
     * Recursively destroy the tree first.
     */
    PRTFSISOMAKERNAME pCur = pNamespace->pRoot;
    if (pCur)
    {
        Assert(!pCur->pParent);
        for (;;)
        {
            if (   pCur->pDir
                && pCur->pDir->cChildren)
                pCur = pCur->pDir->papChildren[pCur->pDir->cChildren - 1];
            else
            {
                PRTFSISOMAKERNAME pNext = pCur->pParent;
                rtFsIsoMakerDestroyName(pCur);

                /* Unlink from parent, we're the last entry. */
                if (pNext)
                {
                    Assert(pNext->pDir->cChildren > 0);
                    pNext->pDir->cChildren--;
                    Assert(pNext->pDir->papChildren[pNext->pDir->cChildren] == pCur);
                    pNext->pDir->papChildren[pNext->pDir->cChildren] = NULL;
                    pCur = pNext;
                }
                else
                {
                    Assert(pNamespace->pRoot == pCur);
                    break;
                }
            }
        }
        pNamespace->pRoot = NULL;
    }

    /*
     * Free the translation table filename if allocated.
     */
    if (pNamespace->pszTransTbl)
    {
        if (pNamespace->pszTransTbl != g_szTransTbl)
            RTStrFree(pNamespace->pszTransTbl);
        pNamespace->pszTransTbl = NULL;
    }

    /*
     * Free string IDs.
     */
    if (pNamespace->pszSystemId)
    {
        if (pNamespace->pszSystemId != g_szSystemId)
            RTStrFree(pNamespace->pszSystemId);
        pNamespace->pszSystemId = NULL;
    }

    if (pNamespace->pszVolumeId)
    {
        RTStrFree(pNamespace->pszVolumeId);
        pNamespace->pszVolumeId = NULL;
    }

    if (pNamespace->pszVolumeSetId)
    {
        RTStrFree(pNamespace->pszVolumeSetId);
        pNamespace->pszVolumeSetId = NULL;
    }

    if (pNamespace->pszPublisherId)
    {
        RTStrFree(pNamespace->pszPublisherId);
        pNamespace->pszPublisherId = NULL;
    }

    if (pNamespace->pszDataPreparerId)
    {
        RTStrFree(pNamespace->pszDataPreparerId);
        pNamespace->pszDataPreparerId = NULL;
    }

    if (pNamespace->pszApplicationId)
    {
        if (   pNamespace->pszApplicationId != g_szAppIdPrimaryIso
            && pNamespace->pszApplicationId != g_szAppIdJoliet)
            RTStrFree(pNamespace->pszApplicationId);
        pNamespace->pszApplicationId = NULL;
    }

    if (pNamespace->pszCopyrightFileId)
    {
        RTStrFree(pNamespace->pszCopyrightFileId);
        pNamespace->pszCopyrightFileId = NULL;
    }

    if (pNamespace->pszAbstractFileId)
    {
        RTStrFree(pNamespace->pszAbstractFileId);
        pNamespace->pszAbstractFileId = NULL;
    }

    if (pNamespace->pszBibliographicFileId)
    {
        RTStrFree(pNamespace->pszBibliographicFileId);
        pNamespace->pszBibliographicFileId = NULL;
    }
}


/**
 * Destroys an ISO maker instance.
 *
 * @param   pThis               The ISO maker instance to destroy.
 */
static void rtFsIsoMakerDestroy(PRTFSISOMAKERINT pThis)
{
    rtFsIsoMakerDestroyTree(&pThis->PrimaryIso);
    rtFsIsoMakerDestroyTree(&pThis->Joliet);
    rtFsIsoMakerDestroyTree(&pThis->Udf);
    rtFsIsoMakerDestroyTree(&pThis->Hfs);

    PRTFSISOMAKEROBJ pCur;
    PRTFSISOMAKEROBJ pNext;
    RTListForEachSafe(&pThis->ObjectHead, pCur, pNext, RTFSISOMAKEROBJ, Entry)
    {
        RTListNodeRemove(&pCur->Entry);
        rtFsIsoMakerObjDestroy(pCur);
    }

    if (pThis->paCommonSources)
    {
        RTMemFree(pThis->paCommonSources);
        pThis->paCommonSources = NULL;
    }

    if (pThis->pbVolDescs)
    {
        RTMemFree(pThis->pbVolDescs);
        pThis->pbVolDescs = NULL;
    }

    if (pThis->pbSysArea)
    {
        RTMemFree(pThis->pbSysArea);
        pThis->pbSysArea = NULL;
    }

    pThis->uMagic = ~RTFSISOMAKERINT_MAGIC;
    RTMemFree(pThis);
}


/**
 * Retains a references to an ISO maker instance.
 *
 * @returns New reference count on success, UINT32_MAX if invalid handle.
 * @param   hIsoMaker           The ISO maker handle.
 */
RTDECL(uint32_t) RTFsIsoMakerRetain(RTFSISOMAKER hIsoMaker)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    AssertPtrReturn(pThis, UINT32_MAX);
    AssertReturn(pThis->uMagic == RTFSISOMAKERINT_MAGIC, UINT32_MAX);
    uint32_t cRefs = ASMAtomicIncU32(&pThis->cRefs);
    Assert(cRefs > 1);
    Assert(cRefs < _64K);
    return cRefs;
}


/**
 * Releases a references to an ISO maker instance.
 *
 * @returns New reference count on success, UINT32_MAX if invalid handle.
 * @param   hIsoMaker           The ISO maker handle.  NIL is ignored.
 */
RTDECL(uint32_t) RTFsIsoMakerRelease(RTFSISOMAKER hIsoMaker)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    uint32_t         cRefs;
    if (pThis == NIL_RTFSISOMAKER)
        cRefs = 0;
    else
    {
        AssertPtrReturn(pThis, UINT32_MAX);
        AssertReturn(pThis->uMagic == RTFSISOMAKERINT_MAGIC, UINT32_MAX);
        cRefs = ASMAtomicDecU32(&pThis->cRefs);
        Assert(cRefs < _64K);
        if (!cRefs)
            rtFsIsoMakerDestroy(pThis);
    }
    return cRefs;
}


/**
 * Sets the ISO-9660 level.
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   uIsoLevel           The level, 1-3.
 */
RTDECL(int) RTFsIsoMakerSetIso9660Level(RTFSISOMAKER hIsoMaker, uint8_t uIsoLevel)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(uIsoLevel <= 3, VERR_INVALID_PARAMETER);
    AssertReturn(uIsoLevel > 0, VERR_INVALID_PARAMETER); /* currently not possible to disable this */
    AssertReturn(!pThis->fSeenContent, VERR_WRONG_ORDER);

    pThis->PrimaryIso.uLevel = uIsoLevel;
    return VINF_SUCCESS;
}


/**
 * Gets the ISO-9660 level.
 *
 * @returns The level, UINT8_MAX if invalid handle.
 * @param   hIsoMaker           The ISO maker handle.
 */
RTDECL(uint8_t) RTFsIsoMakerGetIso9660Level(RTFSISOMAKER hIsoMaker)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET_EX(pThis, UINT8_MAX);
    return pThis->PrimaryIso.uLevel;
}


/**
 * Sets the joliet level.
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   uJolietLevel        The joliet UCS-2 level 1-3, or 0 to disable
 *                              joliet.
 */
RTDECL(int) RTFsIsoMakerSetJolietUcs2Level(RTFSISOMAKER hIsoMaker, uint8_t uJolietLevel)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(uJolietLevel <= 3, VERR_INVALID_PARAMETER);
    AssertReturn(!pThis->fSeenContent, VERR_WRONG_ORDER);

    if (pThis->Joliet.uLevel != uJolietLevel)
    {
        if (uJolietLevel == 0)
            pThis->cVolumeDescriptors--;
        else if (pThis->Joliet.uLevel == 0)
            pThis->cVolumeDescriptors++;
        pThis->Joliet.uLevel = uJolietLevel;
    }
    return VINF_SUCCESS;
}


/**
 * Sets the rock ridge support level (on the primary ISO-9660 namespace).
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   uLevel              0 if disabled, 1 to just enable, 2 to enable and
 *                              write the ER tag.
 */
RTDECL(int) RTFsIsoMakerSetRockRidgeLevel(RTFSISOMAKER hIsoMaker, uint8_t uLevel)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(uLevel <= 2, VERR_INVALID_PARAMETER);
    AssertReturn(   !pThis->fSeenContent
                 || (uLevel >= pThis->PrimaryIso.uRockRidgeLevel && pThis->PrimaryIso.uRockRidgeLevel > 0), VERR_WRONG_ORDER);
    AssertReturn(!pThis->fSeenContent, VERR_WRONG_ORDER);

    pThis->PrimaryIso.uRockRidgeLevel = uLevel;
    return VINF_SUCCESS;
}


/**
 * Sets the rock ridge support level on the joliet namespace (experimental).
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   uLevel              0 if disabled, 1 to just enable, 2 to enable and
 *                              write the ER tag.
 */
RTDECL(int) RTFsIsoMakerSetJolietRockRidgeLevel(RTFSISOMAKER hIsoMaker, uint8_t uLevel)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(uLevel <= 2, VERR_INVALID_PARAMETER);
    AssertReturn(   !pThis->fSeenContent
                 || (uLevel >= pThis->Joliet.uRockRidgeLevel && pThis->Joliet.uRockRidgeLevel > 0), VERR_WRONG_ORDER);

    pThis->Joliet.uRockRidgeLevel = uLevel;
    return VINF_SUCCESS;
}


/**
 * Gets the rock ridge support level (on the primary ISO-9660 namespace).
 *
 * @returns 0 if disabled, 1 just enabled, 2 if enabled with ER tag, and
 *          UINT8_MAX if the handle is invalid.
 * @param   hIsoMaker           The ISO maker handle.
 */
RTDECL(uint8_t) RTFsIsoMakerGetRockRidgeLevel(RTFSISOMAKER hIsoMaker)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET_EX(pThis, UINT8_MAX);
    return pThis->PrimaryIso.uRockRidgeLevel;
}


/**
 * Gets the rock ridge support level on the joliet namespace (experimental).
 *
 * @returns 0 if disabled, 1 just enabled, 2 if enabled with ER tag, and
 *          UINT8_MAX if the handle is invalid.
 * @param   hIsoMaker           The ISO maker handle.
 */
RTDECL(uint8_t) RTFsIsoMakerGetJolietRockRidgeLevel(RTFSISOMAKER hIsoMaker)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET_EX(pThis, UINT8_MAX);
    return pThis->Joliet.uRockRidgeLevel;
}


/**
 * Changes the file attribute (mode, owner, group) inherit style (from source).
 *
 * The strict style will use the exact attributes from the source, where as the
 * non-strict (aka rational and default) style will use 0 for the owner and
 * group IDs and normalize the mode bits along the lines of 'chmod a=rX',
 * stripping set-uid/gid bitson files but preserving sticky ones on directories.
 *
 * When disabling strict style, the default dir and file modes will be restored
 * to default values.
 *
 * @returns IRPT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   fStrict             Indicates strict (true) or non-strict (false)
 *                              style.
 */
RTDECL(int) RTFsIsoMakerSetAttribInheritStyle(RTFSISOMAKER hIsoMaker, bool fStrict)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);

    pThis->fStrictAttributeStyle = fStrict;
    if (!fStrict)
    {
        pThis->fDefaultFileMode = 0444 | RTFS_TYPE_FILE      | RTFS_DOS_ARCHIVED  | RTFS_DOS_READONLY;
        pThis->fDefaultDirMode  = 0555 | RTFS_TYPE_DIRECTORY | RTFS_DOS_DIRECTORY | RTFS_DOS_READONLY;
    }

    return VINF_SUCCESS;
}


/**
 * Sets the default file mode settings.
 *
 * @returns IRPT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   fMode               The default file mode.
 */
RTDECL(int) RTFsIsoMakerSetDefaultFileMode(RTFSISOMAKER hIsoMaker, RTFMODE fMode)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    Assert(!(fMode & ~RTFS_UNIX_ALL_PERMS));

    pThis->fDefaultFileMode &= ~RTFS_UNIX_ALL_PERMS;
    pThis->fDefaultFileMode |= fMode & RTFS_UNIX_ALL_PERMS;
    return VINF_SUCCESS;
}


/**
 * Sets the default dir mode settings.
 *
 * @returns IRPT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   fMode               The default dir mode.
 */
RTDECL(int) RTFsIsoMakerSetDefaultDirMode(RTFSISOMAKER hIsoMaker, RTFMODE fMode)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    Assert(!(fMode & ~RTFS_UNIX_ALL_PERMS));

    pThis->fDefaultDirMode &= ~RTFS_UNIX_ALL_PERMS;
    pThis->fDefaultDirMode |= fMode & RTFS_UNIX_ALL_PERMS;
    return VINF_SUCCESS;
}


/**
 * Sets the forced file mode, if @a fForce is true also the default mode is set.
 *
 * @returns IRPT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   fMode               The file mode.
 * @param   fForce              Indicate whether forced mode is active or not.
 */
RTDECL(int) RTFsIsoMakerSetForcedFileMode(RTFSISOMAKER hIsoMaker, RTFMODE fMode, bool fForce)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    Assert(!(fMode & ~RTFS_UNIX_ALL_PERMS));

    pThis->fForcedFileMode       = fMode & RTFS_UNIX_ALL_PERMS;
    pThis->fForcedFileModeActive = fForce;
    if (fForce)
    {
        pThis->fDefaultFileMode &= ~RTFS_UNIX_ALL_PERMS;
        pThis->fDefaultFileMode |= fMode & RTFS_UNIX_ALL_PERMS;
    }
    return VINF_SUCCESS;
}


/**
 * Sets the forced dir mode, if @a fForce is true also the default mode is set.
 *
 * @returns IRPT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   fMode               The dir mode.
 * @param   fForce              Indicate whether forced mode is active or not.
 */
RTDECL(int) RTFsIsoMakerSetForcedDirMode(RTFSISOMAKER hIsoMaker, RTFMODE fMode, bool fForce)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    Assert(!(fMode & ~RTFS_UNIX_ALL_PERMS));

    pThis->fForcedDirModeActive  = fForce;
    pThis->fForcedDirMode        = fMode & RTFS_UNIX_ALL_PERMS;
    if (fForce)
    {
        pThis->fDefaultDirMode  &= ~RTFS_UNIX_ALL_PERMS;
        pThis->fDefaultDirMode  |= fMode & RTFS_UNIX_ALL_PERMS;
    }
    return VINF_SUCCESS;
}


/**
 * Sets the content of the system area, i.e. the first 32KB of the image.
 *
 * This can be used to put generic boot related stuff.
 *
 * @note    Other settings may overwrite parts of the content (yet to be
 *          determined which).
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   pvContent           The content to put in the system area.
 * @param   cbContent           The size of the content.
 * @param   off                 The offset into the system area.
 */
RTDECL(int) RTFsIsoMakerSetSysAreaContent(RTFSISOMAKER hIsoMaker, void const *pvContent, size_t cbContent, uint32_t off)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);
    AssertReturn(cbContent > 0, VERR_OUT_OF_RANGE);
    AssertReturn(cbContent <= _32K, VERR_OUT_OF_RANGE);
    AssertReturn(off < _32K, VERR_OUT_OF_RANGE);
    size_t cbSysArea = off + cbContent;
    AssertReturn(cbSysArea <= _32K, VERR_OUT_OF_RANGE);

    /*
     * Adjust the allocation and copy over the new/additional content.
     */
    if (pThis->cbSysArea < cbSysArea)
    {
        void *pvNew = RTMemRealloc(pThis->pbSysArea, cbSysArea);
        AssertReturn(pvNew, VERR_NO_MEMORY);
        pThis->pbSysArea = (uint8_t *)pvNew;
        memset(&pThis->pbSysArea[pThis->cbSysArea], 0, cbSysArea - pThis->cbSysArea);
    }

    memcpy(&pThis->pbSysArea[off], pvContent, cbContent);

    return VINF_SUCCESS;
}


/**
 * Sets a string property in one or more namespaces.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker       The ISO maker handle.
 * @param   enmStringProp   The string property to set.
 * @param   fNamespaces     The namespaces to set it in.
 * @param   pszValue        The value to set it to.  NULL is treated like an
 *                          empty string.  The value will be silently truncated
 *                          to fit the available space.
 */
RTDECL(int) RTFsIsoMakerSetStringProp(RTFSISOMAKER hIsoMaker, RTFSISOMAKERSTRINGPROP enmStringProp,
                                      uint32_t fNamespaces, const char *pszValue)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(    enmStringProp > RTFSISOMAKERSTRINGPROP_INVALID
                  && enmStringProp < RTFSISOMAKERSTRINGPROP_END, VERR_INVALID_PARAMETER);
    AssertReturn(!(fNamespaces & ~RTFSISOMAKER_NAMESPACE_VALID_MASK), VERR_INVALID_FLAGS);
    if (pszValue)
    {
        AssertPtrReturn(pszValue, VERR_INVALID_POINTER);
        if (*pszValue == '\0')
            pszValue = NULL;
    }
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Work the namespaces.
     */
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
        if (fNamespaces & g_aRTFsIsoNamespaces[i].fNamespace)
        {
            PRTFSISOMAKERNAMESPACE pNamespace = (PRTFSISOMAKERNAMESPACE)((uintptr_t)pThis + g_aRTFsIsoNamespaces[i].offNamespace);
            if (pNamespace->uLevel > 0)
            {
                /* Get a pointer to the field. */
                char **ppszValue;
                switch (enmStringProp)
                {
                    case RTFSISOMAKERSTRINGPROP_SYSTEM_ID:              ppszValue = &pNamespace->pszSystemId; break;
                    case RTFSISOMAKERSTRINGPROP_VOLUME_ID:              ppszValue = &pNamespace->pszVolumeId; break;
                    case RTFSISOMAKERSTRINGPROP_VOLUME_SET_ID:          ppszValue = &pNamespace->pszVolumeSetId; break;
                    case RTFSISOMAKERSTRINGPROP_PUBLISHER_ID:           ppszValue = &pNamespace->pszPublisherId; break;
                    case RTFSISOMAKERSTRINGPROP_DATA_PREPARER_ID:       ppszValue = &pNamespace->pszDataPreparerId; break;
                    case RTFSISOMAKERSTRINGPROP_APPLICATION_ID:         ppszValue = &pNamespace->pszApplicationId; break;
                    case RTFSISOMAKERSTRINGPROP_COPYRIGHT_FILE_ID:      ppszValue = &pNamespace->pszCopyrightFileId; break;
                    case RTFSISOMAKERSTRINGPROP_ABSTRACT_FILE_ID:       ppszValue = &pNamespace->pszAbstractFileId; break;
                    case RTFSISOMAKERSTRINGPROP_BIBLIOGRAPHIC_FILE_ID:  ppszValue = &pNamespace->pszBibliographicFileId; break;
                    default:                                            AssertFailedReturn(VERR_IPE_NOT_REACHED_DEFAULT_CASE);
                }

                /* Free the old value. */
                char *pszOld = *ppszValue;
                if (   pszOld
                    && pszOld != g_szAppIdPrimaryIso
                    && pszOld != g_szAppIdJoliet
                    && pszOld != g_szSystemId)
                    RTStrFree(pszOld);

                /* Set the new value. */
                if (!pszValue)
                    *ppszValue = NULL;
                else
                {
                    *ppszValue = RTStrDup(pszValue);
                    AssertReturn(*ppszValue, VERR_NO_STR_MEMORY);
                }
            }
        }
    return VINF_SUCCESS;
}


/**
 * Specifies image padding.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   cSectors            Number of sectors to pad the image with.
 */
RTDECL(int) RTFsIsoMakerSetImagePadding(RTFSISOMAKER hIsoMaker, uint32_t cSectors)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(cSectors <= _64K, VERR_OUT_OF_RANGE);
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    pThis->cbImagePadding = cSectors * RTFSISOMAKER_SECTOR_SIZE;
    return VINF_SUCCESS;
}





/*
 *
 * Name space related internals.
 * Name space related internals.
 * Name space related internals.
 *
 */


/**
 * Gets the pointer to the name member for the given namespace.
 *
 * @returns Pointer to name member.
 * @param   pObj                The object to find a name member in.
 * @param   pNamespace          The namespace which name to calculate.
 */
DECLINLINE(PPRTFSISOMAKERNAME) rtFsIsoMakerObjGetNameForNamespace(PRTFSISOMAKEROBJ pObj, PCRTFSISOMAKERNAMESPACE pNamespace)
{
    return (PPRTFSISOMAKERNAME)((uintptr_t)pObj + pNamespace->offName);
}


/**
 * Locates a child object by its namespace name.
 *
 * @returns Pointer to the child if found, NULL if not.
 * @param   pDirObj             The directory object to search.
 * @param   pszEntry            The (namespace) entry name.
 * @param   cchEntry            The length of the name.
 */
static PRTFSISOMAKERNAME rtFsIsoMakerFindObjInDir(PRTFSISOMAKERNAME pDirObj, const char *pszEntry, size_t cchEntry)
{
    if (pDirObj)
    {
        PRTFSISOMAKERNAMEDIR pDir = pDirObj->pDir;
        AssertReturn(pDir, NULL);

        uint32_t i = pDir->cChildren;
        while (i-- > 0)
        {
            PRTFSISOMAKERNAME pChild = pDir->papChildren[i];
            if (   pChild->cchName == cchEntry
                && RTStrNICmp(pChild->szName, pszEntry, cchEntry) == 0)
                return pChild;
        }
    }
    return NULL;
}


/**
 * Compares the two names according to ISO-9660 directory sorting rules.
 *
 * As long as we don't want to do case insensitive joliet sorting, this works
 * for joliet names to, I think.
 *
 * @returns 0 if equal, -1 if pszName1 comes first, 1 if pszName2 comes first.
 * @param   pszName1            The first name.
 * @param   pszName2            The second name.
 */
DECLINLINE(int) rtFsIsoMakerCompareIso9660Names(const char *pszName1, const char *pszName2)
{
    for (;;)
    {
        char const ch1 = *pszName1++;
        char const ch2 = *pszName2++;
        if (ch1 == ch2)
        {
            if (ch1)
            { /* likely */ }
            else
                return 0;
        }
        else if (ch1 == ';' || ch2 == ';')
            return ch1 == ';' ? -1 : 1;
        else if (ch1 == '.' || ch2 == '.')
            return ch1 == '.' ? -1 : 1;
        else
            return (unsigned char)ch1 < (unsigned char)ch2 ? -1 : 1;
    }
}


/**
 * Finds the index into papChildren where the given name should be inserted.
 *
 * @returns Index of the given name.
 * @param   pNamespace          The namspace.
 * @param   pParent             The parent namespace node.
 * @param   pszName             The name.
 */
static uint32_t rtFsIsoMakerFindInsertIndex(PRTFSISOMAKERNAMESPACE pNamespace, PRTFSISOMAKERNAME pParent, const char *pszName)
{
    uint32_t idxRet = pParent->pDir->cChildren;
    if (idxRet > 0)
    {
        /*
         * The idea is to do binary search using a namespace specific compare
         * function.  However, it looks like we can get away with using the
         * same compare function for all namespaces.
         */
        uint32_t            idxStart = 0;
        uint32_t            idxEnd   = idxRet;
        PPRTFSISOMAKERNAME  papChildren = pParent->pDir->papChildren;
        switch (pNamespace->fNamespace)
        {
            case RTFSISOMAKER_NAMESPACE_ISO_9660:
            case RTFSISOMAKER_NAMESPACE_JOLIET:
            case RTFSISOMAKER_NAMESPACE_UDF:
            case RTFSISOMAKER_NAMESPACE_HFS:
                for (;;)
                {
                    idxRet = idxStart + (idxEnd - idxStart) / 2;
                    PRTFSISOMAKERNAME pCur = papChildren[idxRet];
                    int iDiff = rtFsIsoMakerCompareIso9660Names(pszName, pCur->szName);
                    if (iDiff < 0)
                    {
                        if (idxRet > idxStart)
                            idxEnd = idxRet;
                        else
                            break;
                    }
                    else
                    {
                        idxRet++;
                        if (   iDiff != 0
                            && idxRet < idxEnd)
                            idxStart = idxRet;
                        else
                            break;
                    }
                }
                break;

            default:
                AssertFailed();
                break;
        }
    }
    return idxRet;
}



/**
 * Locates a child entry by its specified name.
 *
 * @returns Pointer to the child if found, NULL if not.
 * @param   pDirName            The directory name to search.
 * @param   pszEntry            The (specified) entry name.
 * @param   cchEntry            The length of the name.
 */
static PRTFSISOMAKERNAME rtFsIsoMakerFindEntryInDirBySpec(PRTFSISOMAKERNAME pDirName, const char *pszEntry, size_t cchEntry)
{
    if (pDirName)
    {
        PRTFSISOMAKERNAMEDIR pDir = pDirName->pDir;
        AssertReturn(pDir, NULL);

        uint32_t i = pDir->cChildren;
        while (i-- > 0)
        {
            PRTFSISOMAKERNAME pChild = pDir->papChildren[i];
            if (   pChild->cchSpecNm == cchEntry
                && RTStrNICmp(pChild->pszSpecNm, pszEntry, cchEntry) == 0)
                return pChild;
        }
    }
    return NULL;
}


/**
 * Locates a subdir object in any namespace by its specified name.
 *
 * This is used to avoid having one instance of RTFSISOMAKERDIR in each
 * namespace for the same directory.
 *
 * @returns Pointer to the subdir object if found, NULL if not.
 * @param   pDirObj             The directory object to search.
 * @param   pszEntry            The (specified) entry name.
 * @param   cchEntry            The length of the name.
 * @param   fSkipNamespaces     Namespaces to skip.
 * @sa      rtFsIsoMakerFindEntryInDirBySpec
 */
static PRTFSISOMAKERDIR rtFsIsoMakerFindSubdirBySpec(PRTFSISOMAKERDIR pDirObj, const char *pszEntry, size_t cchEntry,
                                                     uint32_t fSkipNamespaces)
{
    AssertReturn(pDirObj, NULL);
    AssertReturn(pDirObj->Core.enmType == RTFSISOMAKEROBJTYPE_DIR, NULL);
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
        if (!(fSkipNamespaces & g_aRTFsIsoNamespaces[i].fNamespace))
        {
            PRTFSISOMAKERNAME pDirName = *(PPRTFSISOMAKERNAME)((uintptr_t)pDirObj + g_aRTFsIsoNamespaces[i].offName);
            if (pDirName)
            {
                PRTFSISOMAKERNAMEDIR pDir = pDirName->pDir;
                AssertStmt(pDir, continue);

                uint32_t iChild = pDir->cChildren;
                while (iChild-- > 0)
                {
                    PRTFSISOMAKERNAME pChild = pDir->papChildren[iChild];
                    if (   pChild->cchSpecNm == cchEntry
                        && pChild->pDir      != NULL
                        && RTStrNICmp(pChild->pszSpecNm, pszEntry, cchEntry) == 0)
                        return (PRTFSISOMAKERDIR)pChild->pObj;
                }
            }
        }
    return NULL;
}


/**
 * Walks the given path by specified object names in a namespace.
 *
 * @returns IPRT status code.
 * @param   pNamespace  The namespace to walk the path in.
 * @param   pszPath     The path to walk.
 * @param   ppName      Where to return the name node that the path ends with.
 */
static int rtFsIsoMakerWalkPathBySpec(PRTFSISOMAKERNAMESPACE pNamespace, const char *pszPath, PPRTFSISOMAKERNAME ppName)
{
    *ppName = NULL;
    AssertReturn(RTPATH_IS_SLASH(*pszPath), VERR_INVALID_NAME);

    /*
     * Deal with the special case of the root.
     */
    while (RTPATH_IS_SLASH(*pszPath))
        pszPath++;

    PRTFSISOMAKERNAME pCur = pNamespace->pRoot;
    if (!pCur)
        return *pszPath ? VERR_PATH_NOT_FOUND : VERR_FILE_NOT_FOUND;
    if (!*pszPath)
    {
        *ppName = pCur;
        return VINF_SUCCESS;
    }

    /*
     * Now, do the rest of the path.
     */
    for (;;)
    {
        /*
         * Find the end of the component.
         */
        char ch;
        size_t cchComponent = 0;
        while ((ch = pszPath[cchComponent]) != '\0' && !RTPATH_IS_SLASH(ch))
            cchComponent++;
        if (!cchComponent)
        {
            *ppName = pCur;
            return VINF_SUCCESS;
        }

        size_t offNext = cchComponent;
        while (RTPATH_IS_SLASH(ch))
            ch = pszPath[++offNext];

        /*
         * Deal with dot and dot-dot.
         */
        if (cchComponent == 1 && pszPath[0] == '.')
        { /* nothing to do */ }
        else if (cchComponent == 2 && pszPath[0] == '.' && pszPath[1] == '.')
        {
            if (pCur->pParent)
                pCur = pCur->pParent;
        }
        /*
         * Look up the name.
         */
        else
        {
            PRTFSISOMAKERNAME pChild = rtFsIsoMakerFindEntryInDirBySpec(pCur, pszPath, cchComponent);
            if (!pChild)
                return pszPath[offNext] ? VERR_PATH_NOT_FOUND : VERR_FILE_NOT_FOUND;
            if (   (offNext > cchComponent)
                && !pChild->pDir)
                return VERR_NOT_A_DIRECTORY;
            pCur = pChild;
        }

        /*
         * Skip ahead in the path.
         */
        pszPath += offNext;
    }
}


/**
 * Copy and convert a name to valid ISO-9660 (d-characters only).
 *
 * Worker for rtFsIsoMakerNormalizeNameForNamespace.  ASSUMES it deals with
 * dots.
 *
 * @returns Length of the resulting string.
 * @param   pszDst      The output buffer.
 * @param   cchDstMax   The maximum number of (d-chars) to put in the output
 *                      buffer.
 * @param   pchSrc      The UTF-8 source string (not neccessarily terminated).
 * @param   cchSrc      The maximum number of chars to copy from the source
 *                      string.
 */
static size_t rtFsIsoMakerCopyIso9660Name(char *pszDst, size_t cchDstMax, const char *pchSrc, size_t cchSrc)
{
    const char *pchSrcIn = pchSrc;
    size_t      offDst = 0;
    while ((size_t)(pchSrc - pchSrcIn) < cchSrc)
    {
        RTUNICP uc;
        int rc = RTStrGetCpEx(&pchSrc, &uc);
        if (RT_SUCCESS(rc))
        {
            if (   uc < 128
                && RTFSISOMAKER_IS_UPPER_IN_D_CHARS((char)uc))
            {
                pszDst[offDst++] = RT_C_TO_UPPER((char)uc);
                if (offDst >= cchDstMax)
                    break;
            }
        }
    }
    pszDst[offDst] = '\0';
    return offDst;
}


/**
 * Normalizes a name for the primary ISO-9660 namespace.
 *
 * @returns IPRT status code.
 * @param   pThis           The ISO maker instance.
 * @param   pParent         The parent directory.  NULL if root.
 * @param   pchSrc          The specified name to normalize (not necessarily zero
 *                          terminated).
 * @param   cchSrc          The length of the specified name.
 * @param   fNoNormalize    Don't normalize the name very strictly (imported or
 *                          such).
 * @param   fIsDir          Indicates whether it's a directory or file (like).
 * @param   pszDst          The output buffer.  Must be at least 32 bytes.
 * @param   cbDst           The size of the output buffer.
 * @param   pcchDst         Where to return the length of the returned string (i.e.
 *                          not counting the terminator).
 * @param   pcbInDirRec     Where to return the name size in the directory record.
 */
static int rtFsIsoMakerNormalizeNameForPrimaryIso9660(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAME pParent,
                                                      const char *pchSrc, size_t cchSrc, bool fNoNormalize, bool fIsDir,
                                                      char *pszDst, size_t cbDst, size_t *pcchDst, size_t *pcbInDirRec)
{
    AssertReturn(cbDst > ISO9660_MAX_NAME_LEN + 2, VERR_ISOMK_IPE_BUFFER_SIZE);

    /* Skip leading dots. */
    while (cchSrc > 0 && *pchSrc == '.')
        pchSrc++, cchSrc--;
    if (!cchSrc)
    {
        pchSrc = "DOTS";
        cchSrc = 4;
    }

    /*
     * Produce a first name.
     */
    uint8_t const uIsoLevel = !fNoNormalize ? pThis->PrimaryIso.uLevel : RT_MAX(pThis->PrimaryIso.uLevel, 3);
    size_t cchDst;
    size_t offDstDot;
    if (fIsDir && !fNoNormalize)
        offDstDot = cchDst = rtFsIsoMakerCopyIso9660Name(pszDst, uIsoLevel >= 2 ? ISO9660_MAX_NAME_LEN : 8,
                                                         pchSrc, cchSrc);
    else
    {
        /* Look for the last dot and try preserve the extension when doing the conversion. */
        size_t offLastDot = cchSrc;
        for (size_t off = 0; off < cchSrc; off++)
            if (pchSrc[off] == '.')
                offLastDot = off;

        if (fNoNormalize)
        {
            /* Try preserve the imported name, though, put the foot down if too long. */
            offDstDot = offLastDot;
            cchDst    = cchSrc;
            if (cchSrc > ISO9660_MAX_NAME_LEN)
            {
                cchDst = ISO9660_MAX_NAME_LEN;
                if (offDstDot > cchDst)
                    offDstDot = cchDst;
            }
            memcpy(pszDst, pchSrc, cchDst);
            pszDst[cchDst] = '\0';
        }
        else if (offLastDot == cchSrc)
            offDstDot = cchDst = rtFsIsoMakerCopyIso9660Name(pszDst, uIsoLevel >= 2 ? ISO9660_MAX_NAME_LEN : 8,
                                                             pchSrc, cchSrc);
        else
        {
            const char * const pchSrcExt = &pchSrc[offLastDot + 1];
            size_t       const cchSrcExt = cchSrc - offLastDot - 1;
            if (uIsoLevel < 2)
            {
                cchDst = rtFsIsoMakerCopyIso9660Name(pszDst, 8, pchSrc, cchSrc);
                offDstDot = cchDst;
                pszDst[cchDst++] = '.';
                cchDst += rtFsIsoMakerCopyIso9660Name(&pszDst[cchDst], 3, pchSrcExt, cchSrcExt);
            }
            else
            {
                size_t cchDstExt = rtFsIsoMakerCopyIso9660Name(pszDst, ISO9660_MAX_NAME_LEN - 2, pchSrcExt, cchSrcExt);
                if (cchDstExt > 0)
                {
                    size_t cchBasename = rtFsIsoMakerCopyIso9660Name(pszDst, ISO9660_MAX_NAME_LEN - 2,
                                                                     pchSrc, offLastDot);
                    if (cchBasename + 1 + cchDstExt <= ISO9660_MAX_NAME_LEN)
                        cchDst = cchBasename;
                    else
                        cchDst = ISO9660_MAX_NAME_LEN - 1 - RT_MIN(cchDstExt, 4);
                    offDstDot = cchDst;
                    pszDst[cchDst++] = '.';
                    cchDst += rtFsIsoMakerCopyIso9660Name(&pszDst[cchDst], ISO9660_MAX_NAME_LEN - 1 - cchDst,
                                                          pchSrcExt, cchSrcExt);
                }
                else
                    offDstDot = cchDst = rtFsIsoMakerCopyIso9660Name(pszDst, ISO9660_MAX_NAME_LEN, pchSrc, cchSrc);
            }
        }
    }

    /* Append version if not directory */
    if (!fIsDir)
    {
        pszDst[cchDst++] = ';';
        pszDst[cchDst++] = '1';
        pszDst[cchDst]   = '\0';
    }

    /*
     * Unique name?
     */
    if (!rtFsIsoMakerFindObjInDir(pParent, pszDst, cchDst))
    {
        *pcchDst     = cchDst;
        *pcbInDirRec = cchDst;
        return VINF_SUCCESS;
    }

    /*
     * Mangle the name till we've got a unique one.
     */
    size_t const cchMaxBasename = (uIsoLevel >= 2 ? ISO9660_MAX_NAME_LEN : 8) - (cchDst - offDstDot);
    size_t       cchInserted = 0;
    for (uint32_t i = 0; i < _32K; i++)
    {
        /* Add a numberic infix. */
        char szOrd[64];
        size_t cchOrd = RTStrFormatU32(szOrd, sizeof(szOrd), i + 1, 10, -1, -1, 0 /*fFlags*/);
        Assert((ssize_t)cchOrd > 0);

        /* Do we need to shuffle the suffix? */
        if (cchOrd > cchInserted)
        {
            if (offDstDot < cchMaxBasename)
            {
                memmove(&pszDst[offDstDot + 1], &pszDst[offDstDot], cchDst + 1 - offDstDot);
                cchDst++;
                offDstDot++;
            }
            cchInserted = cchOrd;
        }

        /* Insert the new infix and try again. */
        memcpy(&pszDst[offDstDot - cchOrd], szOrd, cchOrd);
        if (!rtFsIsoMakerFindObjInDir(pParent, pszDst, cchDst))
        {
            *pcchDst     = cchDst;
            *pcbInDirRec = cchDst;
            return VINF_SUCCESS;
        }
    }
    AssertFailed();
    return VERR_DUPLICATE;
}


/**
 * Normalizes a name for the specified name space.
 *
 * @returns IPRT status code.
 * @param   pThis           The ISO maker instance.
 * @param   pNamespace      The namespace which rules to normalize it according to.
 * @param   pParent         The parent directory.  NULL if root.
 * @param   pchSrc          The specified name to normalize (not necessarily zero
 *                          terminated).
 * @param   cchSrc          The length of the specified name.
 * @param   fIsDir          Indicates whether it's a directory or file (like).
 * @param   fNoNormalize    Don't normalize the name very strictly (imported or
 *                          such).
 * @param   pszDst          The output buffer.  Must be at least 32 bytes.
 * @param   cbDst           The size of the output buffer.
 * @param   pcchDst         Where to return the length of the returned string (i.e.
 *                          not counting the terminator).
 * @param   pcbInDirRec     Where to return the name size in the directory record.
 */
static int rtFsIsoMakerNormalizeNameForNamespace(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAMESPACE pNamespace,
                                                 PRTFSISOMAKERNAME pParent, const char *pchSrc, size_t cchSrc,
                                                 bool fNoNormalize, bool fIsDir,
                                                 char *pszDst, size_t cbDst, size_t *pcchDst, size_t *pcbInDirRec)
{
    if (cchSrc > 0)
    {
        /*
         * Check that the object doesn't already exist.
         */
        AssertReturn(!rtFsIsoMakerFindEntryInDirBySpec(pParent, pchSrc, cchSrc), VERR_ALREADY_EXISTS);
        switch (pNamespace->fNamespace)
        {
            /*
             * This one is a lot of work, so separate function.
             */
            case RTFSISOMAKER_NAMESPACE_ISO_9660:
                return rtFsIsoMakerNormalizeNameForPrimaryIso9660(pThis, pParent, pchSrc, cchSrc, fNoNormalize, fIsDir,
                                                                  pszDst, cbDst, pcchDst, pcbInDirRec);

            /*
             * At the moment we don't give darn about UCS-2 limitations here...
             */
            case RTFSISOMAKER_NAMESPACE_JOLIET:
            {
/** @todo Joliet name limit and check for duplicates.   */
                AssertReturn(cbDst > cchSrc, VERR_BUFFER_OVERFLOW);
                memcpy(pszDst, pchSrc, cchSrc);
                pszDst[cchSrc] = '\0';
                *pcchDst     = cchSrc;
                *pcbInDirRec = RTStrCalcUtf16Len(pszDst) * sizeof(RTUTF16);
                return VINF_SUCCESS;
            }

            case RTFSISOMAKER_NAMESPACE_UDF:
            case RTFSISOMAKER_NAMESPACE_HFS:
                AssertFailedReturn(VERR_NOT_IMPLEMENTED);

            default:
                AssertFailedReturn(VERR_IPE_NOT_REACHED_DEFAULT_CASE);
        }
    }
    else
    {
        /*
         * Root special case.
         *
         * For ISO-9660 and joliet, we enter it with a length of 1 byte.  The
         * value byte value is zero.  The path tables we generate won't be
         * accepted by windows unless we do this.
         */
        *pszDst      = '\0';
        *pcchDst     = 0;
        *pcbInDirRec = pNamespace->fNamespace & (RTFSISOMAKER_NAMESPACE_ISO_9660 | RTFSISOMAKER_NAMESPACE_JOLIET) ? 1 : 0;
        AssertReturn(!pParent, VERR_ISOMK_IPE_NAMESPACE_3);
        return VINF_SUCCESS;
    }
}


/**
 * Creates a TRANS.TBL file object for a newly named directory.
 *
 * The file is associated with the namespace node for the directory.  The file
 * will be generated on the fly from the directory object.
 *
 * @returns IPRT status code.
 * @param   pThis       The ISO maker instance.
 * @param   pNamespace  The namespace.
 * @param   pDirName    The new name space node for the directory.
 */
static int rtFsIsoMakerAddTransTblFileToNewDir(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAMESPACE pNamespace,
                                               PRTFSISOMAKERNAME pDirName)
{
    /*
     * Create a file object for it.
     */
    PRTFSISOMAKERFILE pFile;
    int rc = rtFsIsoMakerAddUnnamedFileWorker(pThis, NULL, 0, &pFile);
    if (RT_SUCCESS(rc))
    {
        pFile->enmSrcType     = RTFSISOMAKERSRCTYPE_TRANS_TBL;
        pFile->u.pTransTblDir = pDirName;
        pFile->pBootInfoTable = NULL;
        pDirName->pDir->pTransTblFile = pFile;

        /*
         * Add it to the directory.
         */
        PRTFSISOMAKERNAME pTransTblNm;
        rc = rtFsIsoMakerObjSetName(pThis, pNamespace, &pFile->Core, pDirName, pNamespace->pszTransTbl,
                                    strlen(pNamespace->pszTransTbl), false /*fNoNormalize*/, &pTransTblNm);
        if (RT_SUCCESS(rc))
        {
            pTransTblNm->cchTransNm = 0;
            return VINF_SUCCESS;
        }

        /*
         * Bail.
         */
        pDirName->pDir->pTransTblFile = NULL;
        rtFsIsoMakerObjRemoveWorker(pThis, &pFile->Core);
    }
    return rc;
}


/**
 * Sets the name of an object in a namespace.
 *
 * If the object is already named in the name space, it will first be removed
 * from that namespace.  Should we run out of memory or into normalization
 * issues after removing it, its original state will _not_ be restored.
 *
 * @returns IPRT status code.
 * @param   pThis           The ISO maker instance.
 * @param   pNamespace      The namespace.
 * @param   pObj            The object to name.
 * @param   pParent         The parent namespace entry
 * @param   pchSpec         The specified name (not necessarily terminated).
 * @param   cchSpec         The specified name length.
 * @param   fNoNormalize    Don't normalize the name (imported or such).
 * @param   ppNewName       Where to return the name entry.  Optional.
 */
static int rtFsIsoMakerObjSetName(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAMESPACE pNamespace, PRTFSISOMAKEROBJ pObj,
                                  PRTFSISOMAKERNAME pParent, const char *pchSpec, size_t cchSpec, bool fNoNormalize,
                                  PPRTFSISOMAKERNAME ppNewName)
{
    Assert(cchSpec < _32K);

    /*
     * If this is a file, check the size against the ISO level.
     * This ASSUMES that only files which size we already know will be 4GB+ sized.
     */
    if (   (pNamespace->fNamespace & RTFSISOMAKER_NAMESPACE_ISO_9660)
        && pNamespace->uLevel < 3
        && pObj->enmType == RTFSISOMAKEROBJTYPE_FILE)
    {
        PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pObj;
        if (pFile->cbData >= _4G)
            return VERR_ISOMK_FILE_TOO_BIG_REQ_ISO_LEVEL_3;
    }

    /*
     * If this is a symbolic link, refuse to add it to a namespace that isn't
     * configured to support symbolic links.
     */
    if (   pObj->enmType == RTFSISOMAKEROBJTYPE_SYMLINK
        && (pNamespace->fNamespace & (RTFSISOMAKER_NAMESPACE_ISO_9660 | RTFSISOMAKER_NAMESPACE_JOLIET))
        && pNamespace->uRockRidgeLevel == 0)
        return VERR_ISOMK_SYMLINK_REQ_ROCK_RIDGE;

    /*
     * If the object is already named, unset that name before continuing.
     */
    if (*rtFsIsoMakerObjGetNameForNamespace(pObj, pNamespace))
    {
        int rc = rtFsIsoMakerObjUnsetName(pThis, pNamespace, pObj);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * To avoid need to revert anything, make sure papChildren in the parent is
     * large enough.  If root object, make sure we haven't got a root already.
     */
    if (pParent)
    {
        AssertReturn(pParent->pDir, VERR_ISOMK_IPE_NAMESPACE_1);
        uint32_t cChildren = pParent->pDir->cChildren;
        if (cChildren & 31)
        { /* likely */ }
        else
        {
            AssertReturn(cChildren < RTFSISOMAKER_MAX_OBJECTS_PER_DIR, VERR_TOO_MUCH_DATA);
            void *pvNew = RTMemRealloc(pParent->pDir->papChildren, (cChildren + 32) * sizeof(pParent->pDir->papChildren[0]));
            AssertReturn(pvNew, VERR_NO_MEMORY);
            pParent->pDir->papChildren = (PPRTFSISOMAKERNAME)pvNew;
        }
    }
    else
        AssertReturn(pNamespace->pRoot == NULL, VERR_ISOMK_IPE_NAMESPACE_2);

    /*
     * Normalize the name for this namespace.
     */
    size_t cchName        = 0;
    size_t cbNameInDirRec = 0;
    char   szName[RTFSISOMAKER_MAX_NAME_BUF];
    int rc = rtFsIsoMakerNormalizeNameForNamespace(pThis, pNamespace, pParent, pchSpec, cchSpec, fNoNormalize,
                                                   pObj->enmType == RTFSISOMAKEROBJTYPE_DIR,
                                                   szName, sizeof(szName), &cchName, &cbNameInDirRec);
    if (RT_SUCCESS(rc))
    {
        Assert(cbNameInDirRec > 0);

        size_t cbName = sizeof(RTFSISOMAKERNAME)
                      + cchName + 1
                      + cchSpec + 1;
        if (pObj->enmType == RTFSISOMAKEROBJTYPE_DIR)
            cbName = RT_ALIGN_Z(cbName, 8) + sizeof(RTFSISOMAKERNAMEDIR);
        PRTFSISOMAKERNAME pName = (PRTFSISOMAKERNAME)RTMemAllocZ(cbName);
        if (pName)
        {
            pName->pObj                 = pObj;
            pName->pParent              = pParent;
            pName->cbNameInDirRec       = (uint16_t)cbNameInDirRec;
            pName->cchName              = (uint16_t)cchName;

            char *pszDst = &pName->szName[cchName + 1];
            memcpy(pszDst, pchSpec, cchSpec);
            pszDst[cchSpec] = '\0';
            pName->pszSpecNm            = pszDst;
            pName->pszRockRidgeNm       = pszDst;
            pName->pszTransNm           = pszDst;
            pName->cchSpecNm            = (uint16_t)cchSpec;
            pName->cchRockRidgeNm       = (uint16_t)cchSpec;
            pName->cchTransNm           = (uint16_t)cchSpec;
            pName->uDepth               = pParent ? pParent->uDepth + 1 : 0;
            pName->fRockRidgeNmAlloced  = false;
            pName->fTransNmAlloced      = false;
            pName->fRockNeedER          = false;
            pName->fRockNeedRRInDirRec  = false;
            pName->fRockNeedRRInSpill   = false;

            pName->fMode                = pObj->fMode;
            pName->uid                  = pObj->uid;
            pName->gid                  = pObj->gid;
            pName->Device               = 0;
            pName->cHardlinks           = 1;
            pName->offDirRec            = UINT32_MAX;
            pName->cbDirRec             = 0;
            pName->cDirRecs             = 1;
            pName->cbDirRecTotal        = 0;
            pName->fRockEntries         = 0;
            pName->cbRockInDirRec       = 0;
            pName->offRockSpill         = UINT32_MAX;
            pName->cbRockSpill          = 0;

            memcpy(pName->szName, szName, cchName);
            pName->szName[cchName] = '\0';

            if (pObj->enmType != RTFSISOMAKEROBJTYPE_DIR)
                pName->pDir             = NULL;
            else
            {
                size_t offDir = RT_UOFFSETOF(RTFSISOMAKERNAME, szName) + cchName + 1 + cchSpec + 1;
                offDir = RT_ALIGN_Z(offDir, 8);
                PRTFSISOMAKERNAMEDIR pDir = (PRTFSISOMAKERNAMEDIR)((uintptr_t)pName + offDir);
                pDir->offDir        = UINT64_MAX;
                pDir->cbDir         = 0;
                pDir->cChildren     = 0;
                pDir->papChildren   = NULL;
                pDir->pTransTblFile = NULL;
                pDir->pName         = pName;
                pDir->offPathTable  = UINT32_MAX;
                pDir->idPathTable   = UINT16_MAX;
                pDir->cbDirRec00    = 0;
                pDir->cbDirRec01    = 0;
                RTListInit(&pDir->FinalizedEntry);
                pName->pDir = pDir;

                /* Create the TRANS.TBL file object and enter it into this directory as the first entry. */
                if (pNamespace->pszTransTbl)
                {
                    rc = rtFsIsoMakerAddTransTblFileToNewDir(pThis, pNamespace, pName);
                    if (RT_FAILURE(rc))
                    {
                        RTMemFree(pName);
                        return rc;
                    }
                }
            }

            /*
             * Do the linking and stats.  We practice insertion sorting.
             */
            if (pParent)
            {
                uint32_t idxName   = rtFsIsoMakerFindInsertIndex(pNamespace, pParent, pName->szName);
                uint32_t cChildren = pParent->pDir->cChildren;
                if (idxName < cChildren)
                    memmove(&pParent->pDir->papChildren[idxName + 1], &pParent->pDir->papChildren[idxName],
                            (cChildren - idxName) * sizeof(pParent->pDir->papChildren[0]));
                pParent->pDir->papChildren[idxName] = pName;
                pParent->pDir->cChildren++;
            }
            else
                pNamespace->pRoot = pName;
            *rtFsIsoMakerObjGetNameForNamespace(pObj, pNamespace) = pName;
            pNamespace->cNames++;

            /*
             * Done.
             */
            if (ppNewName)
                *ppNewName = pName;
            return VINF_SUCCESS;
        }
    }
    return rc;
}


/**
 * Walks the path up to the parent, creating missing directories as needed.
 *
 * As usual, we walk the specified names rather than the mangled ones.
 *
 * @returns IPRT status code.
 * @param   pThis       The ISO maker instance.
 * @param   pNamespace  The namespace to walk.
 * @param   pszPath     The path to walk.
 * @param   ppParent    Where to return the pointer to the parent
 *                      namespace node.
 * @param   ppszEntry   Where to return the pointer to the final name component.
 * @param   pcchEntry   Where to return the length of the final name component.
 */
static int rtFsIsoMakerCreatePathToParent(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAMESPACE pNamespace, const char *pszPath,
                                          PPRTFSISOMAKERNAME ppParent, const char **ppszEntry, size_t *pcchEntry)
{
    *ppParent  = NULL; /* shut up gcc */
    *ppszEntry = NULL; /* shut up gcc */
    *pcchEntry = 0;    /* shut up gcc */

    int rc;
    AssertReturn(RTPATH_IS_SLASH(*pszPath), VERR_ISOMK_IPE_ROOT_SLASH);

    /*
     * Deal with the special case of the root.
     */
    while (RTPATH_IS_SLASH(*pszPath))
        pszPath++;
    AssertReturn(*pszPath, VERR_ISOMK_IPE_EMPTY_PATH); /* We should not be called on a root path. */

    PRTFSISOMAKERNAME pParent = pNamespace->pRoot;
    if (!pParent)
    {
        PRTFSISOMAKERDIR pDir = RTListGetFirst(&pThis->ObjectHead, RTFSISOMAKERDIR, Core.Entry);
#ifdef RT_STRICT
        Assert(pDir);
        Assert(pDir->Core.idxObj == 0);
        Assert(pDir->Core.enmType == RTFSISOMAKEROBJTYPE_DIR);
        Assert(*rtFsIsoMakerObjGetNameForNamespace(&pDir->Core, pNamespace) == NULL);
#endif

        rc = rtFsIsoMakerObjSetName(pThis, pNamespace, &pDir->Core, NULL /*pParent*/, "", 0, false /*fNoNormalize*/, &pParent);
        AssertRCReturn(rc, rc);
        pParent = pNamespace->pRoot;
        AssertReturn(pParent, VERR_ISOMK_IPE_NAMESPACE_4);
    }

    /*
     * Now, do the rest of the path.
     */
    for (;;)
    {
        /*
         * Find the end of the component and see if its the final one or not.
         */
        char ch;
        size_t cchComponent = 0;
        while ((ch = pszPath[cchComponent]) != '\0' && !RTPATH_IS_SLASH(ch))
            cchComponent++;
        AssertReturn(cchComponent > 0, VERR_ISOMK_IPE_EMPTY_COMPONENT);

        size_t offNext = cchComponent;
        while (RTPATH_IS_SLASH(ch))
            ch = pszPath[++offNext];

        if (ch == '\0')
        {
            /*
             * Final component.  Make sure it is not dot or dot-dot before returning.
             */
            AssertReturn(   pszPath[0] != '.'
                         || cchComponent > 2
                         || (   cchComponent == 2
                             && pszPath[1] != '.'),
                         VERR_INVALID_NAME);

            *ppParent  = pParent;
            *ppszEntry = pszPath;
            *pcchEntry = cchComponent;
            return VINF_SUCCESS;
        }

        /*
         * Deal with dot and dot-dot.
         */
        if (cchComponent == 1 && pszPath[0] == '.')
        { /* nothing to do */ }
        else if (cchComponent == 2 && pszPath[0] == '.' && pszPath[1] == '.')
        {
            if (pParent->pParent)
                pParent = pParent->pParent;
        }
        /*
         * Look it up.
         */
        else
        {
            PRTFSISOMAKERNAME pChild = rtFsIsoMakerFindEntryInDirBySpec(pParent, pszPath, cchComponent);
            if (pChild)
            {
                if (pChild->pDir)
                    pParent = pChild;
                else
                    return VERR_NOT_A_DIRECTORY;
            }
            else
            {
                /* Try see if we've got a directory with the same spec name in a different namespace.
                   (We don't want to waste heap by creating a directory instance per namespace.) */
                PRTFSISOMAKERDIR pChildObj = rtFsIsoMakerFindSubdirBySpec((PRTFSISOMAKERDIR)pParent->pObj,
                                                                           pszPath, cchComponent, pNamespace->fNamespace);
                if (pChildObj)
                {
                    PPRTFSISOMAKERNAME ppChildName = rtFsIsoMakerObjGetNameForNamespace(&pChildObj->Core, pNamespace);
                    if (!*ppChildName)
                    {
                        rc = rtFsIsoMakerObjSetName(pThis, pNamespace, &pChildObj->Core, pParent, pszPath, cchComponent,
                                                    false /*fNoNormalize*/, &pChild);
                        if (RT_FAILURE(rc))
                            return rc;
                        AssertReturn(pChild != NULL, VERR_ISOMK_IPE_NAMESPACE_5);
                    }
                }
                /* If we didn't have luck in other namespaces, create a new directory. */
                if (!pChild)
                {
                    rc = rtFsIsoMakerAddUnnamedDirWorker(pThis, NULL /*pObjInfo*/, &pChildObj);
                    if (RT_SUCCESS(rc))
                        rc = rtFsIsoMakerObjSetName(pThis, pNamespace, &pChildObj->Core, pParent, pszPath, cchComponent,
                                                    false /*fNoNormalize*/, &pChild);
                    if (RT_FAILURE(rc))
                        return rc;
                    AssertReturn(pChild != NULL, VERR_ISOMK_IPE_NAMESPACE_5);
                }
                pParent = pChild;
            }
        }

        /*
         * Skip ahead in the path.
         */
        pszPath += offNext;
    }
}


/**
 * Worker for RTFsIsoMakerObjSetPath that operates on a single namespace.
 *
 * @returns IPRT status code.
 * @param   pThis           The ISO maker instance.
 * @param   pNamespace      The namespace to name it in.
 * @param   pObj            The filesystem object to name.
 * @param   pszPath         The path to the entry in the namespace.
 */
static int rtFsIsoMakerObjSetPathInOne(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAMESPACE pNamespace,
                                       PRTFSISOMAKEROBJ pObj, const char *pszPath)
{
    AssertReturn(*rtFsIsoMakerObjGetNameForNamespace(pObj, pNamespace) == NULL, VERR_WRONG_ORDER);
    AssertReturn(RTPATH_IS_SLASH(*pszPath), VERR_ISOMK_IPE_ROOT_SLASH);

    /*
     * Figure out where the parent is.
     * This will create missing parent name space entries and directory nodes.
     */
    PRTFSISOMAKERNAME   pParent;
    const char         *pszEntry;
    size_t              cchEntry;
    int                 rc;
    if (pszPath[1] != '\0')
        rc = rtFsIsoMakerCreatePathToParent(pThis, pNamespace, pszPath, &pParent, &pszEntry, &cchEntry);
    else
    {
        /*
         * Special case for the root directory.
         */
        Assert(pObj->enmType == RTFSISOMAKEROBJTYPE_DIR);
        AssertReturn(pNamespace->pRoot == NULL, VERR_WRONG_ORDER);
        pszEntry = "/";
        cchEntry = 0;
        pParent  = NULL;
        rc       = VINF_SUCCESS;
    }

    /*
     * Do the job on the final path component.
     */
    if (RT_SUCCESS(rc))
    {
        AssertReturn(!RTPATH_IS_SLASH(pszEntry[cchEntry]) || pObj->enmType == RTFSISOMAKEROBJTYPE_DIR,
                     VERR_NOT_A_DIRECTORY);
        rc = rtFsIsoMakerObjSetName(pThis, pNamespace, pObj, pParent, pszEntry, cchEntry, false /*fNoNormalize*/, NULL);
    }
    return rc;
}


/**
 * Removes an object from the given namespace.
 *
 * @returns IPRT status code.
 * @param   pThis       The ISO maker instance.
 * @param   pNamespace  The namespace.
 * @param   pObj        The object to name.
 */
static int rtFsIsoMakerObjUnsetName(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAMESPACE pNamespace, PRTFSISOMAKEROBJ pObj)
{
    LogFlow(("rtFsIsoMakerObjUnsetName: idxObj=#%#x\n", pObj->idxObj));

    /*
     * First check if there is anything to do here at all.
     */
    PPRTFSISOMAKERNAME ppName = rtFsIsoMakerObjGetNameForNamespace(pObj, pNamespace);
    PRTFSISOMAKERNAME  pName = *ppName;
    if (!pName)
        return VINF_SUCCESS;

    /*
     * We don't support this on the root.
     */
    AssertReturn(pName->pParent, VERR_ACCESS_DENIED);

    /*
     * If this is a directory, we're in for some real fun here as we need to
     * unset the names of all the children too.
     */
    PRTFSISOMAKERNAMEDIR pDir = pName->pDir;
    if (pDir)
    {
        uint32_t iChild = pDir->cChildren;
        while (iChild-- > 0)
        {
            int rc = rtFsIsoMakerObjUnsetName(pThis, pNamespace, pDir->papChildren[iChild]->pObj);
            if (RT_FAILURE(rc))
                return rc;
        }
        AssertReturn(pDir->cChildren == 0, VERR_DIR_NOT_EMPTY);
    }

    /*
     * Unlink the pName from the parent.
     */
    pDir = pName->pParent->pDir;
    uint32_t iChild = pDir->cChildren;
    while (iChild-- > 0)
        if (pDir->papChildren[iChild] == pName)
        {
            uint32_t cToMove = pDir->cChildren - iChild - 1;
            if (cToMove > 0)
                memmove(&pDir->papChildren[iChild], &pDir->papChildren[iChild + 1], cToMove * sizeof(pDir->papChildren[0]));
            pDir->cChildren--;
            pNamespace->cNames--;

            /*
             * NULL the name member in the object and free the structure.
             */
            *ppName = NULL;
            RTMemFree(pName);

            return VINF_SUCCESS;
        }

    /* Not found. This can't happen. */
    AssertFailed();
    return VERR_ISOMK_IPE_NAMESPACE_6;
}


/**
 * Gets currently populated namespaces.
 *
 * @returns Set of namespaces (RTFSISOMAKER_NAMESPACE_XXX), UINT32_MAX on error.
 * @param   hIsoMaker           The ISO maker handle.
 */
RTDECL(uint32_t) RTFsIsoMakerGetPopulatedNamespaces(RTFSISOMAKER hIsoMaker)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET_EX(pThis, UINT32_MAX);

    uint32_t fRet = 0;
    if (pThis->PrimaryIso.cNames > 0)
        fRet |= RTFSISOMAKER_NAMESPACE_ISO_9660;
    if (pThis->Joliet.cNames     > 0)
        fRet |= RTFSISOMAKER_NAMESPACE_JOLIET;
    if (pThis->Udf.cNames        > 0)
        fRet |= RTFSISOMAKER_NAMESPACE_UDF;
    if (pThis->Hfs.cNames        > 0)
        fRet |= RTFSISOMAKER_NAMESPACE_HFS;

    return fRet;
}




/*
 *
 * Object level config
 * Object level config
 * Object level config
 *
 */


/**
 * Translates an object index number to an object pointer, slow path.
 *
 * @returns Pointer to object, NULL if not found.
 * @param   pThis               The ISO maker instance.
 * @param   idxObj              The object index too resolve.
 */
DECL_NO_INLINE(static, PRTFSISOMAKEROBJ) rtFsIsoMakerIndexToObjSlow(PRTFSISOMAKERINT pThis, uint32_t idxObj)
{
    PRTFSISOMAKEROBJ pObj;
    RTListForEachReverse(&pThis->ObjectHead, pObj, RTFSISOMAKEROBJ, Entry)
    {
        if (pObj->idxObj == idxObj)
            return pObj;
    }
    return NULL;
}


/**
 * Translates an object index number to an object pointer.
 *
 * @returns Pointer to object, NULL if not found.
 * @param   pThis               The ISO maker instance.
 * @param   idxObj              The object index too resolve.
 */
DECLINLINE(PRTFSISOMAKEROBJ) rtFsIsoMakerIndexToObj(PRTFSISOMAKERINT pThis, uint32_t idxObj)
{
    PRTFSISOMAKEROBJ pObj = RTListGetLast(&pThis->ObjectHead, RTFSISOMAKEROBJ, Entry);
    if (!pObj || RT_LIKELY(pObj->idxObj == idxObj))
        return pObj;
    return rtFsIsoMakerIndexToObjSlow(pThis, idxObj);
}


/**
 * Resolves a path into a object ID.
 *
 * This will be doing the looking up using the specified object names rather
 * than the version adjusted and mangled according to the namespace setup.
 *
 * @returns The object ID corresponding to @a pszPath, or UINT32_MAX if not
 *          found or invalid parameters.
 * @param   hIsoMaker           The ISO maker instance.
 * @param   fNamespaces         The namespace to resolve @a pszPath in.  It's
 *                              possible to specify multiple namespaces here, of
 *                              course, but that's inefficient.
 * @param   pszPath             The path to the object.
 */
RTDECL(uint32_t) RTFsIsoMakerGetObjIdxForPath(RTFSISOMAKER hIsoMaker, uint32_t fNamespaces, const char *pszPath)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET_EX(pThis, UINT32_MAX);

    /*
     * Do the searching.
     */
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
        if (fNamespaces & g_aRTFsIsoNamespaces[i].fNamespace)
        {
            PRTFSISOMAKERNAMESPACE pNamespace = (PRTFSISOMAKERNAMESPACE)((uintptr_t)pThis + g_aRTFsIsoNamespaces[i].offNamespace);
            if (pNamespace->pRoot)
            {
                PRTFSISOMAKERNAME pName;
                int rc = rtFsIsoMakerWalkPathBySpec(pNamespace, pszPath, &pName);
                if (RT_SUCCESS(rc))
                    return pName->pObj->idxObj;
            }
        }

    return UINT32_MAX;
}


/**
 * Removes the specified object from the image.
 *
 * This is a worker for RTFsIsoMakerObjRemove and
 * rtFsIsoMakerFinalizeRemoveOrphans.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker instance.
 * @param   pObj                The object to remove from the image.
 */
static int rtFsIsoMakerObjRemoveWorker(PRTFSISOMAKERINT pThis, PRTFSISOMAKEROBJ pObj)
{
    /*
     * Don't allow removing trans.tbl files and the boot catalog.
     */
    if (pObj->enmType == RTFSISOMAKEROBJTYPE_FILE)
    {
        PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pObj;
        if (pFile->enmSrcType == RTFSISOMAKERSRCTYPE_TRANS_TBL)
            return VWRN_DANGLING_OBJECTS; /* HACK ALERT! AssertReturn(pFile->enmSrcType != RTFSISOMAKERSRCTYPE_TRANS_TBL, VERR_ACCESS_DENIED); */
        AssertReturn(pFile != pThis->pBootCatFile, VERR_ACCESS_DENIED);
    }

    /*
     * Remove the object from all name spaces.
     */
    int rc = VINF_SUCCESS;
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
    {
        PRTFSISOMAKERNAMESPACE pNamespace = (PRTFSISOMAKERNAMESPACE)((uintptr_t)pThis + g_aRTFsIsoNamespaces[i].offNamespace);
        int rc2 = rtFsIsoMakerObjUnsetName(pThis, pNamespace, pObj);
        if (RT_SUCCESS(rc2) || RT_FAILURE(rc))
            continue;
        rc = rc2;
    }

    /*
     * If that succeeded, remove the object itself.
     */
    if (RT_SUCCESS(rc))
    {
        RTListNodeRemove(&pObj->Entry);
        if (pObj->enmType == RTFSISOMAKEROBJTYPE_FILE)
        {
            uint64_t cbData = ((PRTFSISOMAKERFILE)pObj)->cbData;
            pThis->cbData -= RT_ALIGN_64(cbData, RTFSISOMAKER_SECTOR_SIZE);
        }
        pThis->cObjects--;
        rtFsIsoMakerObjDestroy(pObj);
    }
    return rc;
}


/**
 * Removes the specified object from the image.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker instance.
 * @param   idxObj              The index of the object to remove.
 */
RTDECL(int) RTFsIsoMakerObjRemove(RTFSISOMAKER hIsoMaker, uint32_t idxObj)
{
    /*
     * Validate and translate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    PRTFSISOMAKEROBJ pObj = rtFsIsoMakerIndexToObj(pThis, idxObj);
    AssertReturn(pObj, VERR_OUT_OF_RANGE);
    AssertReturn(   pObj->enmType != RTFSISOMAKEROBJTYPE_FILE
                 || ((PRTFSISOMAKERFILE)pObj)->enmSrcType != RTFSISOMAKERSRCTYPE_RR_SPILL, VERR_ACCESS_DENIED);
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Call worker.
     */
    return rtFsIsoMakerObjRemoveWorker(pThis, pObj);
}


/**
 * Sets the path (name) of an object in the selected namespaces.
 *
 * The name will be transformed as necessary.
 *
 * The initial implementation does not allow this function to be called more
 * than once on an object.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idxObj              The configuration index of to name.
 * @param   fNamespaces         The namespaces to apply the path to
 *                              (RTFSISOMAKER_NAMESPACE_XXX).
 * @param   pszPath             The path.
 */
RTDECL(int) RTFsIsoMakerObjSetPath(RTFSISOMAKER hIsoMaker, uint32_t idxObj, uint32_t fNamespaces, const char *pszPath)
{
    /*
     * Validate and translate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(!(fNamespaces & ~RTFSISOMAKER_NAMESPACE_VALID_MASK), VERR_INVALID_FLAGS);
    AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
    AssertReturn(RTPATH_IS_SLASH(*pszPath), VERR_INVALID_NAME);
    PRTFSISOMAKEROBJ pObj = rtFsIsoMakerIndexToObj(pThis, idxObj);
    AssertReturn(pObj, VERR_OUT_OF_RANGE);
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Execute requested actions.
     */
    uint32_t cAdded = 0;
    int      rc = VINF_SUCCESS;
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
        if (fNamespaces & g_aRTFsIsoNamespaces[i].fNamespace)
        {
            PRTFSISOMAKERNAMESPACE pNamespace = (PRTFSISOMAKERNAMESPACE)((uintptr_t)pThis + g_aRTFsIsoNamespaces[i].offNamespace);
            if (pNamespace->uLevel > 0)
            {
                int rc2 = rtFsIsoMakerObjSetPathInOne(pThis, pNamespace, pObj, pszPath);
                if (RT_SUCCESS(rc2))
                    cAdded++;
                else if (RT_SUCCESS(rc) || rc == VERR_ISOMK_SYMLINK_REQ_ROCK_RIDGE)
                    rc = rc2;
            }
        }
    return rc != VERR_ISOMK_SYMLINK_REQ_ROCK_RIDGE || cAdded == 0 ? rc : VINF_ISOMK_SYMLINK_REQ_ROCK_RIDGE;
}


/**
 * Sets the name of an object in the selected namespaces, placing it under the
 * given directory.
 *
 * The name will be transformed as necessary.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idxObj              The configuration index of to name.
 * @param   idxParentObj        The parent directory object.
 * @param   fNamespaces         The namespaces to apply the path to
 *                              (RTFSISOMAKER_NAMESPACE_XXX).
 * @param   pszName             The name.
 * @param   fNoNormalize        Don't normalize the name (imported or such).
 */
RTDECL(int) RTFsIsoMakerObjSetNameAndParent(RTFSISOMAKER hIsoMaker, uint32_t idxObj, uint32_t idxParentObj,
                                            uint32_t fNamespaces, const char *pszName, bool fNoNormalize)
{
    /*
     * Validate and translate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(!(fNamespaces & ~RTFSISOMAKER_NAMESPACE_VALID_MASK), VERR_INVALID_FLAGS);
    AssertPtrReturn(pszName, VERR_INVALID_POINTER);
    size_t cchName = strlen(pszName);
    AssertReturn(cchName > 0, VERR_INVALID_NAME);
    AssertReturn(memchr(pszName, '/', cchName) == NULL, VERR_INVALID_NAME);
    PRTFSISOMAKEROBJ pObj = rtFsIsoMakerIndexToObj(pThis, idxObj);
    AssertReturn(pObj, VERR_OUT_OF_RANGE);
    PRTFSISOMAKEROBJ pParentObj = rtFsIsoMakerIndexToObj(pThis, idxParentObj);
    AssertReturn(pParentObj, VERR_OUT_OF_RANGE);
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Execute requested actions.
     */
    uint32_t cAdded = 0;
    int rc = VINF_SUCCESS;
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
        if (fNamespaces & g_aRTFsIsoNamespaces[i].fNamespace)
        {
            PRTFSISOMAKERNAMESPACE pNamespace = (PRTFSISOMAKERNAMESPACE)((uintptr_t)pThis + g_aRTFsIsoNamespaces[i].offNamespace);
            if (pNamespace->uLevel > 0)
            {
                PRTFSISOMAKERNAME pParentName = *rtFsIsoMakerObjGetNameForNamespace(pParentObj, pNamespace);
                if (pParentName)
                {
                    int rc2 = rtFsIsoMakerObjSetName(pThis, pNamespace, pObj, pParentName, pszName, cchName,
                                                     fNoNormalize, NULL /*ppNewName*/);
                    if (RT_SUCCESS(rc2))
                        cAdded++;
                    else if (RT_SUCCESS(rc) || rc == VERR_ISOMK_SYMLINK_REQ_ROCK_RIDGE)
                        rc = rc2;
                }
            }
        }
    return rc != VERR_ISOMK_SYMLINK_REQ_ROCK_RIDGE || cAdded == 0 ? rc : VINF_ISOMK_SYMLINK_REQ_ROCK_RIDGE;
}


/**
 * Changes the rock ridge name for the object in the selected namespaces.
 *
 * The object must already be enetered into the namespaces by
 * RTFsIsoMakerObjSetNameAndParent, RTFsIsoMakerObjSetPath or similar.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idxObj              The configuration index of to name.
 * @param   fNamespaces         The namespaces to apply the path to
 *                              (RTFSISOMAKER_NAMESPACE_XXX).
 * @param   pszRockName         The rock ridge name.  Passing NULL will restore
 *                              it back to the specified name, while an empty
 *                              string will restore it to the namespace name.
 */
RTDECL(int) RTFsIsoMakerObjSetRockName(RTFSISOMAKER hIsoMaker, uint32_t idxObj, uint32_t fNamespaces, const char *pszRockName)
{
    /*
     * Validate and translate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(!(fNamespaces & ~RTFSISOMAKER_NAMESPACE_VALID_MASK), VERR_INVALID_FLAGS);
    size_t cchRockName;
    if (pszRockName)
    {
        AssertPtrReturn(pszRockName, VERR_INVALID_POINTER);
        cchRockName = strlen(pszRockName);
        AssertReturn(cchRockName < _1K, VERR_FILENAME_TOO_LONG);
        AssertReturn(memchr(pszRockName, '/', cchRockName) == NULL, VERR_INVALID_NAME);
    }
    else
        cchRockName = 0;
    PRTFSISOMAKEROBJ pObj = rtFsIsoMakerIndexToObj(pThis, idxObj);
    AssertReturn(pObj, VERR_OUT_OF_RANGE);
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Execute requested actions.
     */
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
        if (fNamespaces & g_aRTFsIsoNamespaces[i].fNamespace)
        {
            PRTFSISOMAKERNAMESPACE pNamespace = (PRTFSISOMAKERNAMESPACE)((uintptr_t)pThis + g_aRTFsIsoNamespaces[i].offNamespace);
            if (   pNamespace->uLevel > 0
                && pNamespace->uRockRidgeLevel > 0)
            {
                PRTFSISOMAKERNAME pName = *rtFsIsoMakerObjGetNameForNamespace(pObj, pNamespace);
                if (pName)
                {
                    /* Free the old rock ridge name. */
                    if (pName->fRockRidgeNmAlloced)
                    {
                        RTMemFree(pName->pszRockRidgeNm);
                        pName->pszRockRidgeNm      = NULL;
                        pName->fRockRidgeNmAlloced = false;
                    }

                    /* Set new rock ridge name. */
                    if (cchRockName > 0)
                    {
                        pName->pszRockRidgeNm = (char *)RTMemDup(pszRockName, cchRockName + 1);
                        if (!pName->pszRockRidgeNm)
                        {
                            pName->pszRockRidgeNm = (char *)pName->pszSpecNm;
                            pName->cchRockRidgeNm = pName->cchSpecNm;
                            return VERR_NO_MEMORY;
                        }
                        pName->cchRockRidgeNm = (uint16_t)cchRockName;
                        pName->fRockRidgeNmAlloced = true;
                    }
                    else if (pszRockName == NULL)
                    {
                        pName->pszRockRidgeNm = (char *)pName->pszSpecNm;
                        pName->cchRockRidgeNm = pName->cchSpecNm;
                    }
                    else
                    {
                        pName->pszRockRidgeNm = pName->szName;
                        pName->cchRockRidgeNm = pName->cchName;
                    }
                }
            }
        }
    return VINF_SUCCESS;
}


/**
 * Enables or disable syslinux boot info table patching of a file.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idxObj              The configuration index.
 * @param   fEnable             Whether to enable or disable patching.
 */
RTDECL(int) RTFsIsoMakerObjEnableBootInfoTablePatching(RTFSISOMAKER hIsoMaker, uint32_t idxObj, bool fEnable)
{
    /*
     * Validate and translate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);
    PRTFSISOMAKEROBJ pObj = rtFsIsoMakerIndexToObj(pThis, idxObj);
    AssertReturn(pObj, VERR_OUT_OF_RANGE);
    AssertReturn(pObj->enmType == RTFSISOMAKEROBJTYPE_FILE, VERR_WRONG_TYPE);
    PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pObj;
    AssertReturn(   pFile->enmSrcType == RTFSISOMAKERSRCTYPE_PATH
                 || pFile->enmSrcType == RTFSISOMAKERSRCTYPE_VFS_FILE
                 || pFile->enmSrcType == RTFSISOMAKERSRCTYPE_COMMON,
                 VERR_WRONG_TYPE);

    /*
     * Do the job.
     */
    if (fEnable)
    {
        if (!pFile->pBootInfoTable)
        {
            pFile->pBootInfoTable = (PISO9660SYSLINUXINFOTABLE)RTMemAllocZ(sizeof(*pFile->pBootInfoTable));
            AssertReturn(pFile->pBootInfoTable, VERR_NO_MEMORY);
        }
    }
    else if (pFile->pBootInfoTable)
    {
        RTMemFree(pFile->pBootInfoTable);
        pFile->pBootInfoTable = NULL;
    }
    return VINF_SUCCESS;
}


/**
 * Gets the data size of an object.
 *
 * Currently only supported on file objects.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idxObj              The configuration index.
 * @param   pcbData             Where to return the size.
 */
RTDECL(int) RTFsIsoMakerObjQueryDataSize(RTFSISOMAKER hIsoMaker, uint32_t idxObj, uint64_t *pcbData)
{
    /*
     * Validate and translate input.
     */
    AssertPtrReturn(pcbData, VERR_INVALID_POINTER);
    *pcbData = UINT64_MAX;
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    PRTFSISOMAKEROBJ pObj = rtFsIsoMakerIndexToObj(pThis, idxObj);
    AssertReturn(pObj, VERR_OUT_OF_RANGE);

    /*
     * Do the job.
     */
    if (pObj->enmType == RTFSISOMAKEROBJTYPE_FILE)
    {
        PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pObj;
        if (   pFile->enmSrcType != RTFSISOMAKERSRCTYPE_TRANS_TBL
            && pFile->enmSrcType != RTFSISOMAKERSRCTYPE_RR_SPILL)
        {
            *pcbData = ((PRTFSISOMAKERFILE)pObj)->cbData;
            return VINF_SUCCESS;
        }
    }
    return VERR_WRONG_TYPE;
}


/**
 * Initalizes the common part of a file system object and links it into global
 * chain.
 *
 * @returns IPRT status code
 * @param   pThis               The ISO maker instance.
 * @param   pObj                The common object.
 * @param   enmType             The object type.
 * @param   pObjInfo            The object information (typically source).
 *                              Optional.
 */
static int rtFsIsoMakerInitCommonObj(PRTFSISOMAKERINT pThis, PRTFSISOMAKEROBJ pObj,
                                     RTFSISOMAKEROBJTYPE enmType, PCRTFSOBJINFO pObjInfo)
{
    Assert(!pThis->fFinalized);
    AssertReturn(pThis->cObjects < RTFSISOMAKER_MAX_OBJECTS, VERR_OUT_OF_RANGE);

    pObj->enmType       = enmType;
    pObj->pPrimaryName  = NULL;
    pObj->pJolietName   = NULL;
    pObj->pUdfName      = NULL;
    pObj->pHfsName      = NULL;
    pObj->idxObj        = pThis->cObjects++;
    pObj->cNotOrphan    = 0;
    if (pObjInfo)
    {
        pObj->BirthTime         = pObjInfo->BirthTime;
        pObj->ChangeTime        = pObjInfo->ChangeTime;
        pObj->ModificationTime  = pObjInfo->ModificationTime;
        pObj->AccessedTime      = pObjInfo->AccessTime;
        if (!pThis->fStrictAttributeStyle)
        {
            if (enmType == RTFSISOMAKEROBJTYPE_DIR)
                pObj->fMode     = (pObjInfo->Attr.fMode & ~07222) | 0555;
            else
            {
                pObj->fMode     = (pObjInfo->Attr.fMode & ~00222) | 0444;
                if (pObj->fMode & 0111)
                    pObj->fMode |= 0111;
            }
            pObj->uid           = pThis->uidDefault;
            pObj->gid           = pThis->gidDefault;
        }
        else
        {
            pObj->fMode         = pObjInfo->Attr.fMode;
            pObj->uid           = pObjInfo->Attr.u.Unix.uid != NIL_RTUID ? pObjInfo->Attr.u.Unix.uid : pThis->uidDefault;
            pObj->gid           = pObjInfo->Attr.u.Unix.gid != NIL_RTGID ? pObjInfo->Attr.u.Unix.gid : pThis->gidDefault;
        }
        if (enmType == RTFSISOMAKEROBJTYPE_DIR ? pThis->fForcedDirModeActive : pThis->fForcedFileModeActive)
            pObj->fMode = (pObj->fMode & ~RTFS_UNIX_ALL_PERMS)
                        | (enmType == RTFSISOMAKEROBJTYPE_DIR ? pThis->fForcedDirMode : pThis->fForcedFileMode);
    }
    else
    {
        pObj->BirthTime         = pThis->ImageCreationTime;
        pObj->ChangeTime        = pThis->ImageCreationTime;
        pObj->ModificationTime  = pThis->ImageCreationTime;
        pObj->AccessedTime      = pThis->ImageCreationTime;
        pObj->fMode             = enmType == RTFSISOMAKEROBJTYPE_DIR ? pThis->fDefaultDirMode : pThis->fDefaultFileMode;
        pObj->uid               = pThis->uidDefault;
        pObj->gid               = pThis->gidDefault;
    }

    RTListAppend(&pThis->ObjectHead, &pObj->Entry);
    return VINF_SUCCESS;
}


/**
 * Internal function for adding an unnamed directory.
 *
 * @returns IPRT status code.
 * @param   pThis               The ISO make instance.
 * @param   pObjInfo            Pointer to object attributes, must be set to
 *                              UNIX.  The size and hardlink counts are ignored.
 *                              Optional.
 * @param   ppDir               Where to return the directory.
 */
static int rtFsIsoMakerAddUnnamedDirWorker(PRTFSISOMAKERINT pThis, PCRTFSOBJINFO pObjInfo, PRTFSISOMAKERDIR *ppDir)
{
    PRTFSISOMAKERDIR pDir = (PRTFSISOMAKERDIR)RTMemAllocZ(sizeof(*pDir));
    AssertReturn(pDir, VERR_NO_MEMORY);
    int rc = rtFsIsoMakerInitCommonObj(pThis, &pDir->Core, RTFSISOMAKEROBJTYPE_DIR, pObjInfo);
    if (RT_SUCCESS(rc))
    {
        *ppDir = pDir;
        return VINF_SUCCESS;
    }
    RTMemFree(pDir);
    return rc;

}


/**
 * Adds an unnamed directory to the image.
 *
 * The directory must explictly be entered into the desired namespaces.
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   pObjInfo            Pointer to object attributes, must be set to
 *                              UNIX.  The size and hardlink counts are ignored.
 *                              Optional.
 * @param   pidxObj             Where to return the configuration index of the
 *                              directory.
 * @sa      RTFsIsoMakerAddDir, RTFsIsoMakerObjSetPath
 */
RTDECL(int) RTFsIsoMakerAddUnnamedDir(RTFSISOMAKER hIsoMaker, PCRTFSOBJINFO pObjInfo, uint32_t *pidxObj)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pidxObj, VERR_INVALID_POINTER);
    if (pObjInfo)
    {
        AssertPtrReturn(pObjInfo, VERR_INVALID_POINTER);
        AssertReturn(pObjInfo->Attr.enmAdditional == RTFSOBJATTRADD_UNIX, VERR_INVALID_PARAMETER);
        AssertReturn(RTFS_IS_DIRECTORY(pObjInfo->Attr.fMode), VERR_INVALID_FLAGS);
    }
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    PRTFSISOMAKERDIR pDir;
    int rc = rtFsIsoMakerAddUnnamedDirWorker(pThis, pObjInfo, &pDir);
    *pidxObj = RT_SUCCESS(rc) ? pDir->Core.idxObj : UINT32_MAX;
    return rc;
}


/**
 * Adds a directory to the image in all namespaces and default attributes.
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   pszDir              The path (UTF-8) to the directory in the ISO.
 *
 * @param   pidxObj             Where to return the configuration index of the
 *                              directory.  Optional.
 * @sa      RTFsIsoMakerAddUnnamedDir, RTFsIsoMakerObjSetPath
 */
RTDECL(int) RTFsIsoMakerAddDir(RTFSISOMAKER hIsoMaker, const char *pszDir, uint32_t *pidxObj)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pszDir, VERR_INVALID_POINTER);
    AssertReturn(RTPATH_IS_SLASH(*pszDir), VERR_INVALID_NAME);

    uint32_t idxObj;
    int rc = RTFsIsoMakerAddUnnamedDir(hIsoMaker, NULL /*pObjInfo*/, &idxObj);
    if (RT_SUCCESS(rc))
    {
        rc = RTFsIsoMakerObjSetPath(hIsoMaker, idxObj, RTFSISOMAKER_NAMESPACE_ALL, pszDir);
        if (RT_SUCCESS(rc))
        {
            if (pidxObj)
                *pidxObj = idxObj;
        }
        else
            RTFsIsoMakerObjRemove(hIsoMaker, idxObj);
    }
    return rc;
}


/**
 * Internal function for adding an unnamed file.
 *
 * @returns IPRT status code.
 * @param   pThis               The ISO make instance.
 * @param   pObjInfo            Object information.  Optional.
 * @param   cbExtra             Extra space for additional data (e.g. source
 *                              path string copy).
 * @param   ppFile              Where to return the file.
 */
static int rtFsIsoMakerAddUnnamedFileWorker(PRTFSISOMAKERINT pThis, PCRTFSOBJINFO pObjInfo, size_t cbExtra,
                                            PRTFSISOMAKERFILE *ppFile)
{
    PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)RTMemAllocZ(sizeof(*pFile) + cbExtra);
    AssertReturn(pFile, VERR_NO_MEMORY);
    int rc = rtFsIsoMakerInitCommonObj(pThis, &pFile->Core, RTFSISOMAKEROBJTYPE_FILE, pObjInfo);
    if (RT_SUCCESS(rc))
    {
        pFile->cbData       = pObjInfo ? pObjInfo->cbObject : 0;
        pThis->cbData      += RT_ALIGN_64(pFile->cbData, RTFSISOMAKER_SECTOR_SIZE);
        pFile->offData      = UINT64_MAX;
        pFile->enmSrcType   = RTFSISOMAKERSRCTYPE_INVALID;
        pFile->u.pszSrcPath = NULL;
        pFile->pBootInfoTable = NULL;
        RTListInit(&pFile->FinalizedEntry);

        *ppFile = pFile;
        return VINF_SUCCESS;
    }
    RTMemFree(pFile);
    return rc;

}


/**
 * Adds an unnamed file to the image that's backed by a host file.
 *
 * The file must explictly be entered into the desired namespaces.
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   pszSrcFile          The source file path.  VFS chain spec allowed.
 * @param   pidxObj             Where to return the configuration index of the
 *                              directory.
 * @sa      RTFsIsoMakerAddFile, RTFsIsoMakerObjSetPath
 */
RTDECL(int) RTFsIsoMakerAddUnnamedFileWithSrcPath(RTFSISOMAKER hIsoMaker, const char *pszSrcFile, uint32_t *pidxObj)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pidxObj, VERR_INVALID_POINTER);
    *pidxObj = UINT32_MAX;
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Check that the source file exists and is a file.
     */
    uint32_t    offError = 0;
    RTFSOBJINFO ObjInfo;
    int rc = RTVfsChainQueryInfo(pszSrcFile, &ObjInfo, RTFSOBJATTRADD_UNIX, RTPATH_F_FOLLOW_LINK, &offError, NULL);
    AssertMsgRCReturn(rc, ("%s -> %Rrc offError=%u\n", pszSrcFile, rc, offError), rc);
    AssertMsgReturn(RTFS_IS_FILE(ObjInfo.Attr.fMode), ("%#x - %s\n", ObjInfo.Attr.fMode, pszSrcFile), VERR_NOT_A_FILE);

    /*
     * Create a file object for it.
     */
    size_t const      cbSrcFile = strlen(pszSrcFile) + 1;
    PRTFSISOMAKERFILE pFile;
    rc = rtFsIsoMakerAddUnnamedFileWorker(pThis, &ObjInfo, cbSrcFile, &pFile);
    if (RT_SUCCESS(rc))
    {
        pFile->enmSrcType   = RTFSISOMAKERSRCTYPE_PATH;
        pFile->u.pszSrcPath = (char *)memcpy(pFile + 1, pszSrcFile, cbSrcFile);

        *pidxObj = pFile->Core.idxObj;
    }
    return rc;
}


/**
 * Adds an unnamed file to the image that's backed by a VFS file.
 *
 * The file must explictly be entered into the desired namespaces.
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   hVfsFileSrc         The source file handle.
 * @param   pidxObj             Where to return the configuration index of the
 *                              directory.
 * @sa      RTFsIsoMakerAddUnnamedFileWithSrcPath, RTFsIsoMakerObjSetPath
 */
RTDECL(int) RTFsIsoMakerAddUnnamedFileWithVfsFile(RTFSISOMAKER hIsoMaker, RTVFSFILE hVfsFileSrc, uint32_t *pidxObj)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pidxObj, VERR_INVALID_POINTER);
    *pidxObj = UINT32_MAX;
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Get the VFS file info.  This implicitly validates the handle.
     */
    RTFSOBJINFO ObjInfo;
    int rc = RTVfsFileQueryInfo(hVfsFileSrc, &ObjInfo, RTFSOBJATTRADD_UNIX);
    AssertMsgRCReturn(rc, ("RTVfsFileQueryInfo(%p) -> %Rrc\n", hVfsFileSrc, rc), rc);

    /*
     * Retain a reference to the file.
     */
    uint32_t cRefs = RTVfsFileRetain(hVfsFileSrc);
    AssertReturn(cRefs != UINT32_MAX, VERR_INVALID_HANDLE);

    /*
     * Create a file object for it.
     */
    PRTFSISOMAKERFILE pFile;
    rc = rtFsIsoMakerAddUnnamedFileWorker(pThis, &ObjInfo, 0, &pFile);
    if (RT_SUCCESS(rc))
    {
        pFile->enmSrcType   = RTFSISOMAKERSRCTYPE_VFS_FILE;
        pFile->u.hVfsFile   = hVfsFileSrc;

        *pidxObj = pFile->Core.idxObj;
    }
    else
        RTVfsFileRelease(hVfsFileSrc);
    return rc;
}


/**
 * Adds an unnamed file to the image that's backed by a portion of a common
 * source file.
 *
 * The file must explictly be entered into the desired namespaces.
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idxCommonSrc        The common source file index.
 * @param   offData             The offset of the data in the source file.
 * @param   cbData              The file size.
 * @param   pObjInfo            Pointer to file info.  Optional.
 * @param   pidxObj             Where to return the configuration index of the
 *                              directory.
 * @sa      RTFsIsoMakerAddUnnamedFileWithSrcPath, RTFsIsoMakerObjSetPath
 */
RTDECL(int) RTFsIsoMakerAddUnnamedFileWithCommonSrc(RTFSISOMAKER hIsoMaker, uint32_t idxCommonSrc,
                                                    uint64_t offData, uint64_t cbData, PCRTFSOBJINFO pObjInfo, uint32_t *pidxObj)
{
    /*
     * Validate and fake input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pidxObj, VERR_INVALID_POINTER);
    *pidxObj = UINT32_MAX;
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);
    AssertReturn(idxCommonSrc < pThis->cCommonSources, VERR_INVALID_PARAMETER);
    AssertReturn(offData < (uint64_t)RTFOFF_MAX, VERR_OUT_OF_RANGE);
    AssertReturn(cbData < (uint64_t)RTFOFF_MAX, VERR_OUT_OF_RANGE);
    AssertReturn(offData + cbData < (uint64_t)RTFOFF_MAX, VERR_OUT_OF_RANGE);
    RTFSOBJINFO ObjInfo;
    if (!pObjInfo)
    {
        ObjInfo.cbObject            = cbData;
        ObjInfo.cbAllocated         = cbData;
        ObjInfo.BirthTime           = pThis->ImageCreationTime;
        ObjInfo.ChangeTime          = pThis->ImageCreationTime;
        ObjInfo.ModificationTime    = pThis->ImageCreationTime;
        ObjInfo.AccessTime          = pThis->ImageCreationTime;
        ObjInfo.Attr.fMode          = pThis->fDefaultFileMode;
        ObjInfo.Attr.enmAdditional  = RTFSOBJATTRADD_UNIX;
        ObjInfo.Attr.u.Unix.uid             = NIL_RTUID;
        ObjInfo.Attr.u.Unix.gid             = NIL_RTGID;
        ObjInfo.Attr.u.Unix.cHardlinks      = 1;
        ObjInfo.Attr.u.Unix.INodeIdDevice   = 0;
        ObjInfo.Attr.u.Unix.INodeId         = 0;
        ObjInfo.Attr.u.Unix.fFlags          = 0;
        ObjInfo.Attr.u.Unix.GenerationId    = 0;
        ObjInfo.Attr.u.Unix.Device          = 0;
        pObjInfo = &ObjInfo;
    }
    else
    {
        AssertPtrReturn(pObjInfo, VERR_INVALID_POINTER);
        AssertReturn(pObjInfo->Attr.enmAdditional == RTFSOBJATTRADD_UNIX, VERR_WRONG_TYPE);
        AssertReturn((uint64_t)pObjInfo->cbObject == cbData, VERR_INVALID_PARAMETER);
    }

    /*
     * Create a file object for it.
     */
    PRTFSISOMAKERFILE pFile;
    int rc = rtFsIsoMakerAddUnnamedFileWorker(pThis, pObjInfo, 0, &pFile);
    if (RT_SUCCESS(rc))
    {
        pFile->enmSrcType       = RTFSISOMAKERSRCTYPE_COMMON;
        pFile->u.Common.idxSrc  = idxCommonSrc;
        pFile->u.Common.offData = offData;

        *pidxObj = pFile->Core.idxObj;
    }
    return rc;
}


/**
 * Adds a common source file.
 *
 * Using RTFsIsoMakerAddUnnamedFileWithCommonSrc a sections common source file
 * can be referenced to make up other files.  The typical use case is when
 * importing data from an existing ISO.
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   hVfsFile            VFS handle of the common source.  (A reference
 *                              is added, none consumed.)
 * @param   pidxCommonSrc       Where to return the assigned common source
 *                              index.  This is used to reference the file.
 * @sa      RTFsIsoMakerAddUnnamedFileWithCommonSrc
 */
RTDECL(int) RTFsIsoMakerAddCommonSourceFile(RTFSISOMAKER hIsoMaker, RTVFSFILE hVfsFile, uint32_t *pidxCommonSrc)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pidxCommonSrc, VERR_INVALID_POINTER);
    *pidxCommonSrc = UINT32_MAX;
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Resize the common source array if necessary.
     */
    if ((pThis->cCommonSources & 15) == 0)
    {
        void *pvNew = RTMemRealloc(pThis->paCommonSources, (pThis->cCommonSources + 16) * sizeof(pThis->paCommonSources[0]));
        AssertReturn(pvNew, VERR_NO_MEMORY);
        pThis->paCommonSources = (PRTVFSFILE)pvNew;
    }

    /*
     * Retain a reference to the source file, thereby validating the handle.
     * Then add it to the array.
     */
    uint32_t cRefs = RTVfsFileRetain(hVfsFile);
    AssertReturn(cRefs != UINT32_MAX, VERR_INVALID_HANDLE);

    uint32_t idx = pThis->cCommonSources++;
    pThis->paCommonSources[idx] = hVfsFile;

    *pidxCommonSrc = idx;
    return VINF_SUCCESS;
}


/**
 * Adds a file that's backed by a host file to the image in all namespaces and
 * with attributes taken from the source file.
 *
 * @returns IPRT status code
 * @param   hIsoMaker       The ISO maker handle.
 * @param   pszFile         The path to the file in the image.
 * @param   pszSrcFile      The source file path.  VFS chain spec allowed.
 * @param   pidxObj         Where to return the configuration index of the file.
 *                          Optional
 * @sa      RTFsIsoMakerAddFileWithVfsFile,
 *          RTFsIsoMakerAddUnnamedFileWithSrcPath
 */
RTDECL(int) RTFsIsoMakerAddFileWithSrcPath(RTFSISOMAKER hIsoMaker, const char *pszFile, const char *pszSrcFile, uint32_t *pidxObj)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pszFile, VERR_INVALID_POINTER);
    AssertReturn(RTPATH_IS_SLASH(*pszFile), VERR_INVALID_NAME);

    uint32_t idxObj;
    int rc = RTFsIsoMakerAddUnnamedFileWithSrcPath(hIsoMaker, pszSrcFile, &idxObj);
    if (RT_SUCCESS(rc))
    {
        rc = RTFsIsoMakerObjSetPath(hIsoMaker, idxObj, RTFSISOMAKER_NAMESPACE_ALL, pszFile);
        if (RT_SUCCESS(rc))
        {
            if (pidxObj)
                *pidxObj = idxObj;
        }
        else
            RTFsIsoMakerObjRemove(hIsoMaker, idxObj);
    }
    return rc;
}


/**
 * Adds a file that's backed by a VFS file to the image in all namespaces and
 * with attributes taken from the source file.
 *
 * @returns IPRT status code
 * @param   hIsoMaker       The ISO maker handle.
 * @param   pszFile         The path to the file in the image.
 * @param   hVfsFileSrc     The source file handle.
 * @param   pidxObj         Where to return the configuration index of the file.
 *                          Optional.
 * @sa      RTFsIsoMakerAddUnnamedFileWithVfsFile,
 *          RTFsIsoMakerAddFileWithSrcPath
 */
RTDECL(int) RTFsIsoMakerAddFileWithVfsFile(RTFSISOMAKER hIsoMaker, const char *pszFile, RTVFSFILE hVfsFileSrc, uint32_t *pidxObj)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pszFile, VERR_INVALID_POINTER);
    AssertReturn(RTPATH_IS_SLASH(*pszFile), VERR_INVALID_NAME);

    uint32_t idxObj;
    int rc = RTFsIsoMakerAddUnnamedFileWithVfsFile(hIsoMaker, hVfsFileSrc, &idxObj);
    if (RT_SUCCESS(rc))
    {
        rc = RTFsIsoMakerObjSetPath(hIsoMaker, idxObj, RTFSISOMAKER_NAMESPACE_ALL, pszFile);
        if (RT_SUCCESS(rc))
        {
            if (pidxObj)
                *pidxObj = idxObj;
        }
        else
            RTFsIsoMakerObjRemove(hIsoMaker, idxObj);
    }
    return rc;
}


/**
 * Adds an unnamed symbolic link to the image.
 *
 * The symlink must explictly be entered into the desired namespaces.  Please
 * note that it is not possible to enter a symbolic link into an ISO 9660
 * namespace where rock ridge extensions are disabled, since symbolic links
 * depend on rock ridge.  For HFS and UDF there is no such requirement.
 *
 * Will fail if no namespace is configured that supports symlinks.
 *
 * @returns IPRT status code
 * @retval  VERR_ISOMK_SYMLINK_SUPPORT_DISABLED if not supported.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   pObjInfo            Pointer to object attributes, must be set to
 *                              UNIX.  The size and hardlink counts are ignored.
 *                              Optional.
 * @param   pszTarget           The symbolic link target (UTF-8).
 * @param   pidxObj             Where to return the configuration index of the
 *                              directory.
 * @sa      RTFsIsoMakerAddSymlink, RTFsIsoMakerObjSetPath
 */
RTDECL(int) RTFsIsoMakerAddUnnamedSymlink(RTFSISOMAKER hIsoMaker, PCRTFSOBJINFO pObjInfo, const char *pszTarget, uint32_t *pidxObj)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pidxObj, VERR_INVALID_POINTER);
    if (pObjInfo)
    {
        AssertPtrReturn(pObjInfo, VERR_INVALID_POINTER);
        AssertReturn(pObjInfo->Attr.enmAdditional == RTFSOBJATTRADD_UNIX, VERR_INVALID_PARAMETER);
        AssertReturn(RTFS_IS_SYMLINK(pObjInfo->Attr.fMode), VERR_INVALID_FLAGS);
    }
    AssertPtrReturn(pszTarget, VERR_INVALID_POINTER);
    size_t cchTarget = strlen(pszTarget);
    AssertReturn(cchTarget > 0, VERR_INVALID_NAME);
    AssertReturn(cchTarget < RTFSISOMAKER_MAX_SYMLINK_TARGET_LEN, VERR_FILENAME_TOO_LONG);
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Check that symlinks are supported by some namespace.
     */
    AssertReturn(   (pThis->PrimaryIso.uLevel > 0 && pThis->PrimaryIso.uRockRidgeLevel > 0)
                 || (pThis->Joliet.uLevel     > 0 && pThis->Joliet.uRockRidgeLevel     > 0)
                 || pThis->Udf.uLevel > 0
                 || pThis->Hfs.uLevel > 0,
                 VERR_ISOMK_SYMLINK_SUPPORT_DISABLED);

    /*
     * Calculate the size of the SL entries.
     */
    uint8_t abTmp[_2K + RTFSISOMAKER_MAX_SYMLINK_TARGET_LEN * 3];
    ssize_t cbSlRockRidge = rtFsIsoMakerOutFile_RockRidgeGenSL(pszTarget, abTmp, sizeof(abTmp));
    AssertReturn(cbSlRockRidge > 0, (int)cbSlRockRidge);

    /*
     * Do the adding.
     */
    PRTFSISOMAKERSYMLINK pSymlink = (PRTFSISOMAKERSYMLINK)RTMemAllocZ(RT_UOFFSETOF_DYN(RTFSISOMAKERSYMLINK, szTarget[cchTarget + 1]));
    AssertReturn(pSymlink, VERR_NO_MEMORY);
    int rc = rtFsIsoMakerInitCommonObj(pThis, &pSymlink->Core, RTFSISOMAKEROBJTYPE_SYMLINK, pObjInfo);
    if (RT_SUCCESS(rc))
    {
        pSymlink->cchTarget     = (uint16_t)cchTarget;
        pSymlink->cbSlRockRidge = (uint16_t)cbSlRockRidge;
        memcpy(pSymlink->szTarget, pszTarget, cchTarget);
        pSymlink->szTarget[cchTarget] = '\0';

        *pidxObj = pSymlink->Core.idxObj;
        return VINF_SUCCESS;
    }
    RTMemFree(pSymlink);
    return rc;
}


/**
 * Adds a directory to the image in all namespaces and default attributes.
 *
 * Will fail if no namespace is configured that supports symlinks.
 *
 * @returns IPRT status code
 * @param   hIsoMaker           The ISO maker handle.
 * @param   pszSymlink          The path (UTF-8) to the symlink in the ISO.
 * @param   pszTarget           The symlink target (UTF-8).
 * @param   pidxObj             Where to return the configuration index of the
 *                              directory.  Optional.
 * @sa      RTFsIsoMakerAddUnnamedSymlink, RTFsIsoMakerObjSetPath
 */
RTDECL(int) RTFsIsoMakerAddSymlink(RTFSISOMAKER hIsoMaker, const char *pszSymlink, const char *pszTarget, uint32_t *pidxObj)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pszSymlink, VERR_INVALID_POINTER);
    AssertReturn(RTPATH_IS_SLASH(*pszSymlink), VERR_INVALID_NAME);

    uint32_t idxObj;
    int rc = RTFsIsoMakerAddUnnamedSymlink(hIsoMaker, NULL /*pObjInfo*/, pszTarget, &idxObj);
    if (RT_SUCCESS(rc))
    {
        rc = RTFsIsoMakerObjSetPath(hIsoMaker, idxObj, RTFSISOMAKER_NAMESPACE_ALL, pszSymlink);
        if (RT_SUCCESS(rc))
        {
            if (pidxObj)
                *pidxObj = idxObj;
        }
        else
            RTFsIsoMakerObjRemove(hIsoMaker, idxObj);
    }
    return rc;

}



/*
 *
 * Name space level object config.
 * Name space level object config.
 * Name space level object config.
 *
 */


/**
 * Modifies the mode mask for a given path in one or more namespaces.
 *
 * The mode mask is used by rock ridge, UDF and HFS.
 *
 * @returns IPRT status code.
 * @retval  VWRN_NOT_FOUND if the path wasn't found in any of the specified
 *          namespaces.
 *
 * @param   hIsoMaker           The ISO maker handler.
 * @param   pszPath             The path which mode mask should be modified.
 * @param   fNamespaces         The namespaces to set it in.
 * @param   fSet                The mode bits to set.
 * @param   fUnset              The mode bits to clear (applied first).
 * @param   fFlags              Reserved, MBZ.
 * @param   pcHits              Where to return number of paths found. Optional.
 */
RTDECL(int) RTFsIsoMakerSetPathMode(RTFSISOMAKER hIsoMaker, const char *pszPath, uint32_t fNamespaces,
                                    RTFMODE fSet, RTFMODE fUnset, uint32_t fFlags, uint32_t *pcHits)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
    AssertReturn(RTPATH_IS_SLASH(*pszPath), VERR_INVALID_NAME);
    AssertReturn(!(fNamespaces & ~RTFSISOMAKER_NAMESPACE_VALID_MASK), VERR_INVALID_FLAGS);
    AssertReturn(!(fSet   & ~07777), VERR_INVALID_PARAMETER);
    AssertReturn(!(fUnset & ~07777), VERR_INVALID_PARAMETER);
    AssertReturn(!fFlags, VERR_INVALID_FLAGS);
    AssertPtrNullReturn(pcHits, VERR_INVALID_POINTER);

    /*
     * Make the changes namespace by namespace.
     */
    uint32_t cHits = 0;
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
        if (fNamespaces & g_aRTFsIsoNamespaces[i].fNamespace)
        {
            PRTFSISOMAKERNAMESPACE pNamespace = (PRTFSISOMAKERNAMESPACE)((uintptr_t)pThis + g_aRTFsIsoNamespaces[i].offNamespace);
            if (pNamespace->uLevel > 0)
            {
                PRTFSISOMAKERNAME pName;
                int rc = rtFsIsoMakerWalkPathBySpec(pNamespace, pszPath, &pName);
                if (RT_SUCCESS(rc))
                {
                    pName->fMode = (pName->fMode & ~fUnset) | fSet;
                    cHits++;
                }
            }
        }

   if (pcHits)
       *pcHits = cHits;
   if (cHits > 0)
       return VINF_SUCCESS;
   return VWRN_NOT_FOUND;
}


/**
 * Modifies the owner ID for a given path in one or more namespaces.
 *
 * The owner ID is used by rock ridge, UDF and HFS.
 *
 * @returns IPRT status code.
 * @retval  VWRN_NOT_FOUND if the path wasn't found in any of the specified
 *          namespaces.
 *
 * @param   hIsoMaker           The ISO maker handler.
 * @param   pszPath             The path which mode mask should be modified.
 * @param   fNamespaces         The namespaces to set it in.
 * @param   idOwner             The new owner ID to set.
 * @param   pcHits              Where to return number of paths found. Optional.
 */
RTDECL(int) RTFsIsoMakerSetPathOwnerId(RTFSISOMAKER hIsoMaker, const char *pszPath, uint32_t fNamespaces,
                                       RTUID idOwner, uint32_t *pcHits)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
    AssertReturn(RTPATH_IS_SLASH(*pszPath), VERR_INVALID_NAME);
    AssertReturn(!(fNamespaces & ~RTFSISOMAKER_NAMESPACE_VALID_MASK), VERR_INVALID_FLAGS);
    AssertPtrNullReturn(pcHits, VERR_INVALID_POINTER);

    /*
     * Make the changes namespace by namespace.
     */
    uint32_t cHits = 0;
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
        if (fNamespaces & g_aRTFsIsoNamespaces[i].fNamespace)
        {
            PRTFSISOMAKERNAMESPACE pNamespace = (PRTFSISOMAKERNAMESPACE)((uintptr_t)pThis + g_aRTFsIsoNamespaces[i].offNamespace);
            if (pNamespace->uLevel > 0)
            {
                PRTFSISOMAKERNAME pName;
                int rc = rtFsIsoMakerWalkPathBySpec(pNamespace, pszPath, &pName);
                if (RT_SUCCESS(rc))
                {
                    pName->uid = idOwner;
                    cHits++;
                }
            }
        }

   if (pcHits)
       *pcHits = cHits;
   if (cHits > 0)
       return VINF_SUCCESS;
   return VWRN_NOT_FOUND;
}


/**
 * Modifies the group ID for a given path in one or more namespaces.
 *
 * The group ID is used by rock ridge, UDF and HFS.
 *
 * @returns IPRT status code.
 * @retval  VWRN_NOT_FOUND if the path wasn't found in any of the specified
 *          namespaces.
 *
 * @param   hIsoMaker           The ISO maker handler.
 * @param   pszPath             The path which mode mask should be modified.
 * @param   fNamespaces         The namespaces to set it in.
 * @param   idGroup             The new group ID to set.
 * @param   pcHits              Where to return number of paths found. Optional.
 */
RTDECL(int) RTFsIsoMakerSetPathGroupId(RTFSISOMAKER hIsoMaker, const char *pszPath, uint32_t fNamespaces,
                                       RTGID idGroup, uint32_t *pcHits)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
    AssertReturn(RTPATH_IS_SLASH(*pszPath), VERR_INVALID_NAME);
    AssertReturn(!(fNamespaces & ~RTFSISOMAKER_NAMESPACE_VALID_MASK), VERR_INVALID_FLAGS);
    AssertPtrNullReturn(pcHits, VERR_INVALID_POINTER);

    /*
     * Make the changes namespace by namespace.
     */
    uint32_t cHits = 0;
    for (uint32_t i = 0; i < RT_ELEMENTS(g_aRTFsIsoNamespaces); i++)
        if (fNamespaces & g_aRTFsIsoNamespaces[i].fNamespace)
        {
            PRTFSISOMAKERNAMESPACE pNamespace = (PRTFSISOMAKERNAMESPACE)((uintptr_t)pThis + g_aRTFsIsoNamespaces[i].offNamespace);
            if (pNamespace->uLevel > 0)
            {
                PRTFSISOMAKERNAME pName;
                int rc = rtFsIsoMakerWalkPathBySpec(pNamespace, pszPath, &pName);
                if (RT_SUCCESS(rc))
                {
                    pName->gid = idGroup;
                    cHits++;
                }
            }
        }

   if (pcHits)
       *pcHits = cHits;
   if (cHits > 0)
       return VINF_SUCCESS;
   return VWRN_NOT_FOUND;
}






/*
 *
 * El Torito Booting.
 * El Torito Booting.
 * El Torito Booting.
 * El Torito Booting.
 *
 */

/**
 * Ensures that we've got a boot catalog file.
 *
 * @returns IPRT status code.
 * @param   pThis               The ISO maker instance.
 */
static int rtFsIsoMakerEnsureBootCatFile(PRTFSISOMAKERINT pThis)
{
    if (pThis->pBootCatFile)
        return VINF_SUCCESS;

    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /* Create a VFS memory file for backing up the file. */
    RTVFSFILE hVfsFile;
    int rc = RTVfsMemFileCreate(NIL_RTVFSIOSTREAM, RTFSISOMAKER_SECTOR_SIZE, &hVfsFile);
    if (RT_SUCCESS(rc))
    {
        /* Create an unnamed VFS backed file and mark it as non-orphaned. */
        PRTFSISOMAKERFILE pFile;
        rc = rtFsIsoMakerAddUnnamedFileWorker(pThis, NULL, 0, &pFile);
        if (RT_SUCCESS(rc))
        {
            pFile->enmSrcType       = RTFSISOMAKERSRCTYPE_VFS_FILE;
            pFile->u.hVfsFile       = hVfsFile;
            pFile->Core.cNotOrphan  = 1;

            /* Save file pointer and allocate a volume descriptor. */
            pThis->pBootCatFile = pFile;
            pThis->cVolumeDescriptors++;

            return VINF_SUCCESS;
        }
        RTVfsFileRelease(hVfsFile);
    }
    return rc;
}


/**
 * Queries the configuration index of the boot catalog file object.
 *
 * The boot catalog file is created as necessary, thus this have to be a query
 * rather than a getter since object creation may fail.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   pidxObj             Where to return the configuration index.
 */
RTDECL(int) RTFsIsoMakerQueryObjIdxForBootCatalog(RTFSISOMAKER hIsoMaker, uint32_t *pidxObj)
{
    /*
     * Validate input.
     */
    AssertPtrReturn(pidxObj, VERR_INVALID_POINTER);
    *pidxObj = UINT32_MAX;
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);

    /*
     * Do the job.
     */
    int rc = rtFsIsoMakerEnsureBootCatFile(pThis);
    if (RT_SUCCESS(rc))
        *pidxObj = pThis->pBootCatFile->Core.idxObj;
    return rc;
}


/**
 * Sets the boot catalog backing file.
 *
 * The content of the given file will be discarded and replaced with the boot
 * catalog, the naming and file attributes (other than size) will be retained.
 *
 * This API exists mainly to assist when importing ISOs.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idxObj              The configuration index of the file.
 */
RTDECL(int) RTFsIsoMakerBootCatSetFile(RTFSISOMAKER hIsoMaker, uint32_t idxObj)
{
    /*
     * Validate and translate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);

    PRTFSISOMAKEROBJ pObj = rtFsIsoMakerIndexToObj(pThis, idxObj);
    AssertReturn(pObj, VERR_OUT_OF_RANGE);
    AssertReturn(pObj->enmType == RTFSISOMAKEROBJTYPE_FILE, VERR_WRONG_TYPE);
    PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pObj;
    AssertReturn(   pFile->enmSrcType == RTFSISOMAKERSRCTYPE_PATH
                 || pFile->enmSrcType == RTFSISOMAKERSRCTYPE_COMMON
                 || pFile->enmSrcType == RTFSISOMAKERSRCTYPE_VFS_FILE,
                 VERR_WRONG_TYPE);

    /*
     * To reduce the possible combinations here, make sure there is a boot cat
     * file that we're "replacing".
     */
    int rc = rtFsIsoMakerEnsureBootCatFile(pThis);
    if (RT_SUCCESS(rc))
    {
        /*
         * Grab a reference to the boot cat memory VFS so we can destroy it
         * later using regular destructors.
         */
        PRTFSISOMAKERFILE pOldFile = pThis->pBootCatFile;
        RTVFSFILE         hVfsFile = pOldFile->u.hVfsFile;
        uint32_t          cRefs    = RTVfsFileRetain(hVfsFile);
        if (cRefs != UINT32_MAX)
        {
            /*
             * Try remove the existing boot file.
             */
            pOldFile->Core.cNotOrphan--;
            pThis->pBootCatFile = NULL;
            rc = rtFsIsoMakerObjRemoveWorker(pThis, &pOldFile->Core);
            if (RT_SUCCESS(rc))
            {
                /*
                 * Just morph pFile into a boot catalog file.
                 */
                if (pFile->enmSrcType == RTFSISOMAKERSRCTYPE_VFS_FILE)
                {
                    RTVfsFileRelease(pFile->u.hVfsFile);
                    pFile->u.hVfsFile = NIL_RTVFSFILE;
                }

                pThis->cbData -= RT_ALIGN_64(pFile->cbData, RTFSISOMAKER_SECTOR_SIZE);
                pFile->cbData     = 0;
                pFile->Core.cNotOrphan++;
                pFile->enmSrcType = RTFSISOMAKERSRCTYPE_VFS_FILE;
                pFile->u.hVfsFile = hVfsFile;

                pThis->pBootCatFile = pFile;

                return VINF_SUCCESS;
            }

            pThis->pBootCatFile = pOldFile;
            pOldFile->Core.cNotOrphan++;
            RTVfsFileRelease(hVfsFile);
        }
        else
            rc = VERR_ISOMK_IPE_BOOT_CAT_FILE;
    }
    return rc;
}


/**
 * Set the validation entry of the boot catalog (this is the first entry).
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idPlatform          The platform ID
 *                              (ISO9660_ELTORITO_PLATFORM_ID_XXX).
 * @param   pszString           CD/DVD-ROM identifier.  Optional.
 */
RTDECL(int) RTFsIsoMakerBootCatSetValidationEntry(RTFSISOMAKER hIsoMaker, uint8_t idPlatform, const char *pszString)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    size_t cchString = 0;
    if (pszString)
    {
        cchString = RTStrCalcLatin1Len(pszString);
        AssertReturn(cchString < RT_SIZEOFMEMB(ISO9660ELTORITOVALIDATIONENTRY, achId), VERR_OUT_OF_RANGE);
    }

    /*
     * Make sure we've got a boot file.
     */
    int rc = rtFsIsoMakerEnsureBootCatFile(pThis);
    if (RT_SUCCESS(rc))
    {
        /*
         * Construct the entry data.
         */
        ISO9660ELTORITOVALIDATIONENTRY Entry;
        Entry.bHeaderId = ISO9660_ELTORITO_HEADER_ID_VALIDATION_ENTRY;
        Entry.bPlatformId = idPlatform;
        Entry.u16Reserved = 0;
        RT_ZERO(Entry.achId);
        if (cchString)
        {
            char *pszTmp = Entry.achId;
            rc = RTStrToLatin1Ex(pszString, RTSTR_MAX, &pszTmp, sizeof(Entry.achId), NULL);
            AssertRC(rc);
        }
        Entry.u16Checksum = 0;
        Entry.bKey1 = ISO9660_ELTORITO_KEY_BYTE_1;
        Entry.bKey2 = ISO9660_ELTORITO_KEY_BYTE_2;

        /* Calc checksum. */
        uint16_t uSum = 0;
        uint16_t const *pu16Src = (uint16_t const *)&Entry;
        uint16_t        cLeft   = sizeof(Entry) / sizeof(uint16_t);
        while (cLeft-- > 0)
        {
            uSum += RT_LE2H_U16(*pu16Src);
            pu16Src++;
        }
        Entry.u16Checksum = RT_H2LE_U16((uint16_t)0 - uSum);

        /*
         * Write the entry and update our internal tracker.
         */
        rc = RTVfsFileWriteAt(pThis->pBootCatFile->u.hVfsFile, 0, &Entry, sizeof(Entry), NULL);
        if (RT_SUCCESS(rc))
        {
            pThis->aBootCatEntries[0].bType    = ISO9660_ELTORITO_HEADER_ID_VALIDATION_ENTRY;
            pThis->aBootCatEntries[0].cEntries = 2;
        }
    }
    return rc;
}


/**
 * Set the validation entry of the boot catalog (this is the first entry).
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idxBootCat          The boot catalog entry.  Zero and two are
 *                              invalid.  Must be less than 63.
 * @param   idxImageObj         The configuration index of the boot image.
 * @param   bBootMediaType      The media type and flag (not for entry 1)
 *                              (ISO9660_ELTORITO_BOOT_MEDIA_TYPE_XXX,
 *                              ISO9660_ELTORITO_BOOT_MEDIA_F_XXX).
 * @param   bSystemType         The partitiona table system ID.
 * @param   fBootable           Whether it's a bootable entry or if we just want
 *                              the BIOS to setup the emulation without booting
 *                              it.
 * @param   uLoadSeg            The load address divided by 0x10 (i.e. the real
 *                              mode segment number).
 * @param   cSectorsToLoad      Number of emulated sectors to load.
 * @param   bSelCritType        The selection criteria type, if none pass
 *                              ISO9660_ELTORITO_SEL_CRIT_TYPE_NONE.
 * @param   pvSelCritData       Pointer to the selection criteria data.
 * @param   cbSelCritData       Size of the selection criteria data.
 */
RTDECL(int) RTFsIsoMakerBootCatSetSectionEntry(RTFSISOMAKER hIsoMaker, uint32_t idxBootCat, uint32_t idxImageObj,
                                               uint8_t bBootMediaType, uint8_t bSystemType, bool fBootable,
                                               uint16_t uLoadSeg, uint16_t cSectorsToLoad,
                                               uint8_t bSelCritType, void const *pvSelCritData, size_t cbSelCritData)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)rtFsIsoMakerIndexToObj(pThis, idxImageObj);
    AssertReturn(pFile, VERR_OUT_OF_RANGE);
    AssertReturn((bBootMediaType & ISO9660_ELTORITO_BOOT_MEDIA_TYPE_MASK) <= ISO9660_ELTORITO_BOOT_MEDIA_TYPE_HARD_DISK,
                 VERR_INVALID_PARAMETER);
    AssertReturn(!(bBootMediaType & ISO9660_ELTORITO_BOOT_MEDIA_F_MASK) || idxBootCat != 1,
                 VERR_INVALID_PARAMETER);

    AssertReturn(idxBootCat != 0 && idxBootCat != 2 && idxBootCat < RT_ELEMENTS(pThis->aBootCatEntries) - 1U, VERR_OUT_OF_RANGE);

    size_t cExtEntries = 0;
    if (bSelCritType == ISO9660_ELTORITO_SEL_CRIT_TYPE_NONE)
        AssertReturn(cbSelCritData == 0, VERR_INVALID_PARAMETER);
    else
    {
        AssertReturn(idxBootCat > 2, VERR_INVALID_PARAMETER);
        if (cbSelCritData > 0)
        {
            AssertPtrReturn(pvSelCritData, VERR_INVALID_POINTER);

            if (cbSelCritData <= RT_SIZEOFMEMB(ISO9660ELTORITOSECTIONENTRY, abSelectionCriteria))
                cExtEntries = 0;
            else
            {
                cExtEntries = (cbSelCritData - RT_SIZEOFMEMB(ISO9660ELTORITOSECTIONENTRY, abSelectionCriteria)
                               + RT_SIZEOFMEMB(ISO9660ELTORITOSECTIONENTRYEXT, abSelectionCriteria) - 1)
                            / RT_SIZEOFMEMB(ISO9660ELTORITOSECTIONENTRYEXT, abSelectionCriteria);
                AssertReturn(cExtEntries + 1 < RT_ELEMENTS(pThis->aBootCatEntries) - 1, VERR_TOO_MUCH_DATA);
            }
        }
    }

    /*
     * Make sure we've got a boot file.
     */
    int rc = rtFsIsoMakerEnsureBootCatFile(pThis);
    if (RT_SUCCESS(rc))
    {
        /*
         * Construct the entry.
         */
        union
        {
            ISO9660ELTORITOSECTIONENTRY     Entry;
            ISO9660ELTORITOSECTIONENTRYEXT  ExtEntry;
        } u;
        u.Entry.bBootIndicator            = fBootable ? ISO9660_ELTORITO_BOOT_INDICATOR_BOOTABLE
                                          :             ISO9660_ELTORITO_BOOT_INDICATOR_NOT_BOOTABLE;
        u.Entry.bBootMediaType            = bBootMediaType;
        u.Entry.uLoadSeg                  = RT_H2LE_U16(uLoadSeg);
        u.Entry.bSystemType               = cExtEntries == 0
                                          ? bSystemType & ~ISO9660_ELTORITO_BOOT_MEDIA_F_CONTINUATION
                                          : bSystemType | ISO9660_ELTORITO_BOOT_MEDIA_F_CONTINUATION;
        u.Entry.bUnused                   = 0;
        u.Entry.cEmulatedSectorsToLoad    = RT_H2LE_U16(cSectorsToLoad);
        u.Entry.offBootImage              = 0;
        u.Entry.bSelectionCriteriaType    = bSelCritType;
        RT_ZERO(u.Entry.abSelectionCriteria);
        if (cbSelCritData > 0)
            memcpy(u.Entry.abSelectionCriteria, pvSelCritData, RT_MIN(cbSelCritData, sizeof(u.Entry.abSelectionCriteria)));

        /*
         * Write it and update our internal tracker.
         */
        rc = RTVfsFileWriteAt(pThis->pBootCatFile->u.hVfsFile, ISO9660_ELTORITO_ENTRY_SIZE * idxBootCat,
                              &u.Entry, sizeof(u.Entry), NULL);
        if (RT_SUCCESS(rc))
        {
            if (pThis->aBootCatEntries[idxBootCat].pBootFile != pFile)
            {
                if (pThis->aBootCatEntries[idxBootCat].pBootFile)
                    pThis->aBootCatEntries[idxBootCat].pBootFile->Core.cNotOrphan--;
                pFile->Core.cNotOrphan++;
                pThis->aBootCatEntries[idxBootCat].pBootFile = pFile;
            }

            pThis->aBootCatEntries[idxBootCat].bType    = u.Entry.bBootIndicator;
            pThis->aBootCatEntries[idxBootCat].cEntries = 1;
        }

        /*
         * Do add further extension entries with selection criteria.
         */
        if (cExtEntries)
        {
            uint8_t const *pbSrc = (uint8_t const *)pvSelCritData;
            size_t         cbSrc = cbSelCritData;
            pbSrc += sizeof(u.Entry.abSelectionCriteria);
            cbSrc -= sizeof(u.Entry.abSelectionCriteria);

            while (cbSrc > 0)
            {
                u.ExtEntry.bExtensionId = ISO9660_ELTORITO_SECTION_ENTRY_EXT_ID;
                if (cbSrc > sizeof(u.ExtEntry.abSelectionCriteria))
                {
                    u.ExtEntry.fFlags = ISO9660_ELTORITO_SECTION_ENTRY_EXT_F_MORE;
                    memcpy(u.ExtEntry.abSelectionCriteria, pbSrc, sizeof(u.ExtEntry.abSelectionCriteria));
                    pbSrc += sizeof(u.ExtEntry.abSelectionCriteria);
                    cbSrc -= sizeof(u.ExtEntry.abSelectionCriteria);
                }
                else
                {
                    u.ExtEntry.fFlags = 0;
                    RT_ZERO(u.ExtEntry.abSelectionCriteria);
                    memcpy(u.ExtEntry.abSelectionCriteria, pbSrc, cbSrc);
                    cbSrc = 0;
                }

                idxBootCat++;
                rc = RTVfsFileWriteAt(pThis->pBootCatFile->u.hVfsFile, ISO9660_ELTORITO_ENTRY_SIZE * idxBootCat,
                                      &u.Entry, sizeof(u.Entry), NULL);
                if (RT_FAILURE(rc))
                    break;

                /* update the internal tracker. */
                if (pThis->aBootCatEntries[idxBootCat].pBootFile)
                {
                    pThis->aBootCatEntries[idxBootCat].pBootFile->Core.cNotOrphan--;
                    pThis->aBootCatEntries[idxBootCat].pBootFile = NULL;
                }

                pThis->aBootCatEntries[idxBootCat].bType    = ISO9660_ELTORITO_SECTION_ENTRY_EXT_ID;
                pThis->aBootCatEntries[idxBootCat].cEntries = 1;
            }
        }
    }
    return rc;
}


/**
 * Set the validation entry of the boot catalog (this is the first entry).
 *
 * @returns IPRT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   idxBootCat          The boot catalog entry.
 * @param   cEntries            Number of entries in the section.
 * @param   idPlatform          The platform ID
 *                              (ISO9660_ELTORITO_PLATFORM_ID_XXX).
 * @param   pszString           Section identifier or something.  Optional.
 */
RTDECL(int) RTFsIsoMakerBootCatSetSectionHeaderEntry(RTFSISOMAKER hIsoMaker, uint32_t idxBootCat, uint32_t cEntries,
                                                     uint8_t idPlatform, const char *pszString)
{
    /*
     * Validate input.
     */
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);

    AssertReturn(idxBootCat >= 2 && idxBootCat < RT_ELEMENTS(pThis->aBootCatEntries) - 1U, VERR_OUT_OF_RANGE);
    AssertReturn(cEntries < RT_ELEMENTS(pThis->aBootCatEntries) - 2U - 1U, VERR_OUT_OF_RANGE);
    AssertReturn(idxBootCat + cEntries + 1 < RT_ELEMENTS(pThis->aBootCatEntries), VERR_OUT_OF_RANGE);

    size_t cchString = 0;
    if (pszString)
    {
        cchString = RTStrCalcLatin1Len(pszString);
        AssertReturn(cchString < RT_SIZEOFMEMB(ISO9660ELTORITOVALIDATIONENTRY, achId), VERR_OUT_OF_RANGE);
    }

    /*
     * Make sure we've got a boot file.
     */
    int rc = rtFsIsoMakerEnsureBootCatFile(pThis);
    if (RT_SUCCESS(rc))
    {
        /*
         * Construct the entry data.
         */
        ISO9660ELTORITOSECTIONHEADER Entry;
        Entry.bHeaderId   = ISO9660_ELTORITO_HEADER_ID_SECTION_HEADER;
        Entry.bPlatformId = idPlatform;
        Entry.cEntries    = RT_H2LE_U16(cEntries);
        RT_ZERO(Entry.achSectionId);
        if (cchString)
        {
            char *pszTmp = Entry.achSectionId;
            rc = RTStrToLatin1Ex(pszString, RTSTR_MAX, &pszTmp, sizeof(Entry.achSectionId), NULL);
            AssertRC(rc);
        }

        /*
         * Write the entry and update our internal tracker.
         */
        rc = RTVfsFileWriteAt(pThis->pBootCatFile->u.hVfsFile, ISO9660_ELTORITO_ENTRY_SIZE * idxBootCat,
                              &Entry, sizeof(Entry), NULL);
        if (RT_SUCCESS(rc))
        {
            if (pThis->aBootCatEntries[idxBootCat].pBootFile != NULL)
            {
                pThis->aBootCatEntries[idxBootCat].pBootFile->Core.cNotOrphan--;
                pThis->aBootCatEntries[idxBootCat].pBootFile = NULL;
            }

            pThis->aBootCatEntries[idxBootCat].bType    = ISO9660_ELTORITO_HEADER_ID_SECTION_HEADER;
            pThis->aBootCatEntries[idxBootCat].cEntries = cEntries + 1;
        }
    }
    return rc;
}





/*
 *
 * Image finalization.
 * Image finalization.
 * Image finalization.
 *
 */


/**
 * Remove any orphaned object from the disk.
 *
 * @returns IPRT status code.
 * @param   pThis               The ISO maker instance.
 */
static int rtFsIsoMakerFinalizeRemoveOrphans(PRTFSISOMAKERINT pThis)
{
    for (;;)
    {
        uint32_t         cRemoved = 0;
        PRTFSISOMAKEROBJ pCur;
        PRTFSISOMAKEROBJ pNext;
        RTListForEachSafe(&pThis->ObjectHead, pCur, pNext, RTFSISOMAKEROBJ, Entry)
        {
            if (   pCur->pPrimaryName
                || pCur->pJolietName
                || pCur->pUdfName
                || pCur->pHfsName
                || pCur->cNotOrphan > 0)
            { /* likely */ }
            else
            {
                Log4(("rtFsIsoMakerFinalizeRemoveOrphans: %#x cbData=%#RX64\n", pCur->idxObj,
                      pCur->enmType == RTFSISOMAKEROBJTYPE_FILE ? ((PRTFSISOMAKERFILE)(pCur))->cbData : 0));
                int rc = rtFsIsoMakerObjRemoveWorker(pThis, pCur);
                if (RT_SUCCESS(rc))
                {
                    if (rc != VWRN_DANGLING_OBJECTS) /** */
                        cRemoved++;
                }
                else
                    return rc;
            }
        }
        if (!cRemoved)
            return VINF_SUCCESS;
    }
}


/**
 * Finalizes the El Torito boot stuff, part 1.
 *
 * This includes generating the boot catalog data and fixing the location of all
 * related image files.
 *
 * @returns IPRT status code.
 * @param   pThis               The ISO maker instance.
 */
static int rtFsIsoMakerFinalizeBootStuffPart1(PRTFSISOMAKERINT pThis)
{
    /*
     * Anything?
     */
    if (!pThis->pBootCatFile)
        return VINF_SUCCESS;

    /*
     * Validate the boot catalog file.
     */
    AssertReturn(pThis->aBootCatEntries[0].bType == ISO9660_ELTORITO_HEADER_ID_VALIDATION_ENTRY,
                 VERR_ISOMK_BOOT_CAT_NO_VALIDATION_ENTRY);
    AssertReturn(pThis->aBootCatEntries[1].pBootFile != NULL, VERR_ISOMK_BOOT_CAT_NO_DEFAULT_ENTRY);

    /* Check any sections following the default one. */
    uint32_t cEntries = 2;
    while (   cEntries < RT_ELEMENTS(pThis->aBootCatEntries) - 1U
           && pThis->aBootCatEntries[cEntries].cEntries > 0)
    {
        AssertReturn(pThis->aBootCatEntries[cEntries].bType == ISO9660_ELTORITO_HEADER_ID_SECTION_HEADER,
                     VERR_ISOMK_BOOT_CAT_EXPECTED_SECTION_HEADER);
        for (uint32_t i = 1; i < pThis->aBootCatEntries[cEntries].cEntries; i++)
            AssertReturn(pThis->aBootCatEntries[cEntries].pBootFile != NULL,
                         pThis->aBootCatEntries[cEntries].cEntries == 0
                         ? VERR_ISOMK_BOOT_CAT_EMPTY_ENTRY : VERR_ISOMK_BOOT_CAT_INVALID_SECTION_SIZE);
        cEntries += pThis->aBootCatEntries[cEntries].cEntries;
    }

    /* Save for size setting. */
    uint32_t const cEntriesInFile = cEntries + 1;

    /* Check that the remaining entries are empty. */
    while (cEntries < RT_ELEMENTS(pThis->aBootCatEntries))
    {
        AssertReturn(pThis->aBootCatEntries[cEntries].cEntries == 0, VERR_ISOMK_BOOT_CAT_ERRATIC_ENTRY);
        cEntries++;
    }

    /*
     * Fixate the size of the boot catalog file.
     */
    pThis->pBootCatFile->cbData = cEntriesInFile * ISO9660_ELTORITO_ENTRY_SIZE;
    pThis->cbData  += RT_ALIGN_32(cEntriesInFile * ISO9660_ELTORITO_ENTRY_SIZE, RTFSISOMAKER_SECTOR_SIZE);

    /*
     * Move up the boot images and boot catalog to the start of the image.
     */
    for (uint32_t i = RT_ELEMENTS(pThis->aBootCatEntries) - 2; i > 0; i--)
        if (pThis->aBootCatEntries[i].pBootFile)
        {
            RTListNodeRemove(&pThis->aBootCatEntries[i].pBootFile->Core.Entry);
            RTListPrepend(&pThis->ObjectHead, &pThis->aBootCatEntries[i].pBootFile->Core.Entry);
        }

    /* The boot catalog comes first. */
    RTListNodeRemove(&pThis->pBootCatFile->Core.Entry);
    RTListPrepend(&pThis->ObjectHead, &pThis->pBootCatFile->Core.Entry);

    return VINF_SUCCESS;
}


/**
 * Finalizes the El Torito boot stuff, part 1.
 *
 * This includes generating the boot catalog data and fixing the location of all
 * related image files.
 *
 * @returns IPRT status code.
 * @param   pThis               The ISO maker instance.
 */
static int rtFsIsoMakerFinalizeBootStuffPart2(PRTFSISOMAKERINT pThis)
{
    /*
     * Anything?
     */
    if (!pThis->pBootCatFile)
        return VINF_SUCCESS;

    /*
     * Fill in the descriptor.
     */
    PISO9660BOOTRECORDELTORITO pDesc = pThis->pElToritoDesc;
    pDesc->Hdr.bDescType    = ISO9660VOLDESC_TYPE_BOOT_RECORD;
    pDesc->Hdr.bDescVersion = ISO9660PRIMARYVOLDESC_VERSION;
    memcpy(pDesc->Hdr.achStdId, ISO9660VOLDESC_STD_ID, sizeof(pDesc->Hdr.achStdId));
    memcpy(pDesc->achBootSystemId, RT_STR_TUPLE(ISO9660BOOTRECORDELTORITO_BOOT_SYSTEM_ID));
    pDesc->offBootCatalog   = RT_H2LE_U32((uint32_t)(pThis->pBootCatFile->offData / RTFSISOMAKER_SECTOR_SIZE));

    /*
     * Update the image file locations.
     */
    uint32_t cEntries = 2;
    for (uint32_t i = 1; i < RT_ELEMENTS(pThis->aBootCatEntries) - 1; i++)
        if (pThis->aBootCatEntries[i].pBootFile)
        {
            uint32_t off = pThis->aBootCatEntries[i].pBootFile->offData / RTFSISOMAKER_SECTOR_SIZE;
            off = RT_H2LE_U32(off);
            int rc = RTVfsFileWriteAt(pThis->pBootCatFile->u.hVfsFile,
                                      i * ISO9660_ELTORITO_ENTRY_SIZE + RT_UOFFSETOF(ISO9660ELTORITOSECTIONENTRY, offBootImage),
                                      &off, sizeof(off), NULL /*pcbWritten*/);
            AssertRCReturn(rc, rc);
            if (i == cEntries)
                cEntries = i + 1;
        }

    /*
     * Write end section.
     */
    ISO9660ELTORITOSECTIONHEADER Entry;
    Entry.bHeaderId   = ISO9660_ELTORITO_HEADER_ID_FINAL_SECTION_HEADER;
    Entry.bPlatformId = ISO9660_ELTORITO_PLATFORM_ID_X86;
    Entry.cEntries    = 0;
    RT_ZERO(Entry.achSectionId);
    int rc = RTVfsFileWriteAt(pThis->pBootCatFile->u.hVfsFile, cEntries * ISO9660_ELTORITO_ENTRY_SIZE,
                              &Entry, sizeof(Entry), NULL /*pcbWritten*/);
    AssertRCReturn(rc, rc);

    return VINF_SUCCESS;
}


/**
 * Gathers the dirs for an ISO-9660 namespace (e.g. primary or joliet).
 *
 * @param   pNamespace          The namespace.
 * @param   pFinalizedDirs      The finalized directory structure.  The
 *                              FinalizedDirs will be worked here.
 */
static void rtFsIsoMakerFinalizeGatherDirs(PRTFSISOMAKERNAMESPACE pNamespace, PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs)
{
    RTListInit(&pFinalizedDirs->FinalizedDirs);

    /*
     * Enter the root directory (if we got one).
     */
    if (!pNamespace->pRoot)
        return;
    PRTFSISOMAKERNAMEDIR pCurDir = pNamespace->pRoot->pDir;
    RTListAppend(&pFinalizedDirs->FinalizedDirs, &pCurDir->FinalizedEntry);
    do
    {
        /*
         * Scan pCurDir and add directories.  We don't need to sort anything
         * here because the directory is already in path table compatible order.
         */
        uint32_t            cLeft    = pCurDir->cChildren;
        PPRTFSISOMAKERNAME  ppChild  = pCurDir->papChildren;
        while (cLeft-- > 0)
        {
            PRTFSISOMAKERNAME pChild = *ppChild++;
            if (pChild->pDir)
                RTListAppend(&pFinalizedDirs->FinalizedDirs, &pChild->pDir->FinalizedEntry);
        }

        /*
         * Advance to the next directory.
         */
        pCurDir = RTListGetNext(&pFinalizedDirs->FinalizedDirs, pCurDir, RTFSISOMAKERNAMEDIR, FinalizedEntry);
    } while (pCurDir);
}


/**
 * Allocates space in the rock ridge spill file.
 *
 * @returns Spill file offset, UINT32_MAX on failure.
 * @param   pRRSpillFile    The spill file.
 * @param   cbRock          Number of bytes to allocate.
 */
static uint32_t rtFsIsoMakerFinalizeAllocRockRidgeSpill(PRTFSISOMAKERFILE pRRSpillFile, uint32_t cbRock)
{
    uint32_t off = pRRSpillFile->cbData;
    if (ISO9660_SECTOR_SIZE - (pRRSpillFile->cbData & ISO9660_SECTOR_OFFSET_MASK) >= cbRock)
    { /* likely */ }
    else
    {
        off |= ISO9660_SECTOR_OFFSET_MASK;
        off++;
        AssertLogRelReturn(off > 0, UINT32_MAX);
        pRRSpillFile->cbData = off;
    }
    pRRSpillFile->cbData += RT_ALIGN_32(cbRock, 4);
    return off;
}


/**
 * Finalizes a directory entry (i.e. namespace node).
 *
 * This calculates the directory record size.
 *
 * @returns IPRT status code.
 * @param   pFinalizedDirs  .
 * @param   pName           The directory entry to finalize.
 * @param   offInDir        The offset in the directory of this record.
 * @param   uRockRidgeLevel This is the rock ridge level.
 * @param   fIsRoot         Set if this is the root.
 */
static int rtFsIsoMakerFinalizeIsoDirectoryEntry(PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs, PRTFSISOMAKERNAME pName,
                                                 uint32_t offInDir, uint8_t uRockRidgeLevel, bool fIsRoot)
{
    /* Set directory and translation table offsets.  (These are for
       helping generating data blocks later.) */
    pName->offDirRec = offInDir;

    /* Calculate the minimal directory record size. */
    size_t cbDirRec = RT_UOFFSETOF(ISO9660DIRREC, achFileId) + pName->cbNameInDirRec + !(pName->cbNameInDirRec & 1);
    AssertReturn(cbDirRec <= UINT8_MAX, VERR_FILENAME_TOO_LONG);

    pName->cbDirRec = (uint8_t)cbDirRec;
    pName->cDirRecs = 1;
    if (pName->pObj->enmType == RTFSISOMAKEROBJTYPE_FILE)
    {
        PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pName->pObj;
        if (pFile->cbData > UINT32_MAX)
            pName->cDirRecs = (pFile->cbData + RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE - 1) / RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE;
    }

    /*
     * Calculate the size of the rock ridge bits we need.
     */
    if (uRockRidgeLevel > 0)
    {
        uint16_t cbRock = 0;
        uint8_t  fFlags = 0;

        /* Level two starts with a 'RR' entry. */
        if (uRockRidgeLevel >= 2)
            cbRock += sizeof(ISO9660RRIPRR);

        /* We always do 'PX' and 'TF' w/ 4 timestamps. */
        cbRock += sizeof(ISO9660RRIPPX)
                + RT_UOFFSETOF(ISO9660RRIPTF, abPayload) + 4 * sizeof(ISO9660RECTIMESTAMP);
        fFlags |= ISO9660RRIP_RR_F_PX | ISO9660RRIP_RR_F_TF;

        /* Devices needs 'PN'. */
        if (   RTFS_IS_DEV_BLOCK(pName->pObj->fMode)
            || RTFS_IS_DEV_CHAR(pName->pObj->fMode))
        {
            cbRock += sizeof(ISO9660RRIPPN);
            fFlags |= ISO9660RRIP_RR_F_PN;
        }

        /* Usually we need a 'NM' entry too. */
        if (   pName->pszRockRidgeNm != pName->szName
            && pName->cchRockRidgeNm > 0
            && (   pName->cbNameInDirRec != 1
                || (uint8_t)pName->szName[0] > (uint8_t)0x01) )  /** @todo only root dir ever uses an ID byte here? [RR NM ./..] */
        {
            uint16_t cchNm = pName->cchRockRidgeNm;
            while (cchNm > ISO9660RRIPNM_MAX_NAME_LEN)
            {
                cbRock += (uint16_t)RT_UOFFSETOF(ISO9660RRIPNM, achName) + ISO9660RRIPNM_MAX_NAME_LEN;
                cchNm  -= ISO9660RRIPNM_MAX_NAME_LEN;
            }
            cbRock += (uint16_t)RT_UOFFSETOF(ISO9660RRIPNM, achName) + cchNm;
            fFlags |= ISO9660RRIP_RR_F_NM;
        }

        /* Symbolic links needs a 'SL' entry. */
        if (pName->pObj->enmType == RTFSISOMAKEROBJTYPE_SYMLINK)
        {
            PRTFSISOMAKERSYMLINK pSymlink = (PRTFSISOMAKERSYMLINK)pName->pObj;
            cbRock += pSymlink->cbSlRockRidge;
            fFlags |= ISO9660RRIP_RR_F_SL;
        }

        /*
         * Decide where stuff goes.  The '.' record of the root dir is special.
         */
        pName->fRockEntries = fFlags;
        if (!fIsRoot)
        {
            if (pName->cbDirRec + cbRock < UINT8_MAX)
            {
                pName->cbRockInDirRec      = cbRock;
                pName->cbRockSpill         = 0;
                pName->fRockNeedRRInDirRec = uRockRidgeLevel >= 2;
                pName->fRockNeedRRInSpill  = false;
            }
            else if (pName->cbDirRec + sizeof(ISO9660SUSPCE) < UINT8_MAX)
            {
                /* Try fit the 'RR' entry in the directory record, but don't bother with anything else. */
                if (uRockRidgeLevel >= 2 && pName->cbDirRec + sizeof(ISO9660SUSPCE) + sizeof(ISO9660RRIPRR) < UINT8_MAX)
                {
                    pName->cbRockInDirRec      = (uint16_t)(sizeof(ISO9660SUSPCE) + sizeof(ISO9660RRIPRR));
                    cbRock -= sizeof(ISO9660RRIPRR);
                    pName->cbRockSpill         = cbRock;
                    pName->fRockNeedRRInDirRec = true;
                    pName->fRockNeedRRInSpill  = false;
                }
                else
                {
                    pName->cbRockInDirRec      = (uint16_t)sizeof(ISO9660SUSPCE);
                    pName->cbRockSpill         = cbRock;
                    pName->fRockNeedRRInDirRec = false;
                    pName->fRockNeedRRInSpill  = uRockRidgeLevel >= 2;
                }
                pName->offRockSpill         = rtFsIsoMakerFinalizeAllocRockRidgeSpill(pFinalizedDirs->pRRSpillFile, cbRock);
                AssertReturn(pName->offRockSpill != UINT32_MAX, VERR_ISOMK_RR_SPILL_FILE_FULL);
            }
            else
            {
                LogRel(("RTFsIsoMaker: no space for 'CE' entry: cbDirRec=%#x bytes, name=%s (%#x bytes)\n",
                        pName->cbDirRec, pName->szName, pName->cbNameInDirRec));
                return VERR_ISOMK_RR_NO_SPACE_FOR_CE;
            }
        }
        else
        {
            /* The root starts with a 'SP' record to indicate that SUSP is being used,
               this is always in the directory record.  If we add a 'ER' record (big) too,
               we put all but 'SP' and 'ER' in the spill file too keep things simple. */
            if (uRockRidgeLevel < 2)
            {
                Assert(!(fFlags & (ISO9660RRIP_RR_F_NM | ISO9660RRIP_RR_F_SL | ISO9660RRIP_RR_F_CL | ISO9660RRIP_RR_F_PL | ISO9660RRIP_RR_F_RE)));
                cbRock += sizeof(ISO9660SUSPSP);
                Assert(pName->cbDirRec + cbRock < UINT8_MAX);
                pName->cbRockInDirRec       = cbRock;
                pName->cbRockSpill          = 0;
                pName->fRockNeedER          = false;
                pName->fRockNeedRRInDirRec  = false;
                pName->fRockNeedRRInSpill   = false;
            }
            else
            {
                pName->cbRockInDirRec       = (uint16_t)(sizeof(ISO9660SUSPSP) + sizeof(ISO9660SUSPCE));
                pName->fRockNeedER          = true;
                pName->fRockNeedRRInSpill   = true;
                pName->fRockNeedRRInDirRec  = false;
                cbRock += ISO9660_RRIP_ER_LEN;
                pName->cbRockSpill          = cbRock;
                pName->offRockSpill         = rtFsIsoMakerFinalizeAllocRockRidgeSpill(pFinalizedDirs->pRRSpillFile, cbRock);
            }
        }
        pName->cbDirRec += pName->cbRockInDirRec + (pName->cbRockInDirRec & 1);
        Assert(pName->cbDirRec < UINT8_MAX);
    }

    pName->cbDirRecTotal = pName->cbDirRec * pName->cDirRecs;
    return VINF_SUCCESS;
}


/**
 * Finalizes either a primary and secondary ISO namespace.
 *
 * @returns IPRT status code
 * @param   pThis           The ISO maker instance.
 * @param   pNamespace      The namespace.
 * @param   pFinalizedDirs  The finalized directories structure for the
 *                          namespace.
 * @param   poffData        The data offset.  We will allocate blocks for the
 *                          directories and the path tables.
 */
static int rtFsIsoMakerFinalizeDirectoriesInIsoNamespace(PRTFSISOMAKERINT pThis, PRTFSISOMAKERNAMESPACE pNamespace,
                                                         PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs, uint64_t *poffData)
{
    int rc;

    /* The directory data comes first, so take down it's offset. */
    pFinalizedDirs->offDirs = *poffData;

    /*
     * Reset the rock ridge spill file (in case we allow finalizing more than once)
     * and create a new spill file if rock ridge is enabled.  The directory entry
     * finalize function uses this as a clue that rock ridge is enabled.
     */
    if (pFinalizedDirs->pRRSpillFile)
    {
        pFinalizedDirs->pRRSpillFile->Core.cNotOrphan = 0;
        rtFsIsoMakerObjRemoveWorker(pThis, &pFinalizedDirs->pRRSpillFile->Core);
        pFinalizedDirs->pRRSpillFile = NULL;
    }
    if (pNamespace->uRockRidgeLevel > 0)
    {
        rc = rtFsIsoMakerAddUnnamedFileWorker(pThis, NULL, 0, &pFinalizedDirs->pRRSpillFile);
        AssertRCReturn(rc, rc);
        pFinalizedDirs->pRRSpillFile->enmSrcType            = RTFSISOMAKERSRCTYPE_RR_SPILL;
        pFinalizedDirs->pRRSpillFile->u.pRockSpillNamespace = pNamespace;
        pFinalizedDirs->pRRSpillFile->Core.cNotOrphan       = 1;
    }

    uint16_t idPathTable = 1;
    uint32_t cbPathTable = 0;
    if (pNamespace->pRoot)
    {
        /*
         * Precalc the directory record size for the root directory.
         */
        rc = rtFsIsoMakerFinalizeIsoDirectoryEntry(pFinalizedDirs, pNamespace->pRoot, 0 /*offInDir*/,
                                                   pNamespace->uRockRidgeLevel, true /*fIsRoot*/);
        AssertRCReturn(rc, rc);

        /*
         * Work thru the directories.
         */
        PRTFSISOMAKERNAMEDIR pCurDir;
        RTListForEach(&pFinalizedDirs->FinalizedDirs, pCurDir, RTFSISOMAKERNAMEDIR, FinalizedEntry)
        {
            PRTFSISOMAKERNAME pCurName    = pCurDir->pName;
            PRTFSISOMAKERNAME pParentName = pCurName->pParent ? pCurName->pParent : pCurName;

            /* We don't do anything special for the special '.' and '..' directory
               entries, instead we use the directory entry in the parent directory
               with a 1 byte name (00 or 01). */
            /** @todo r=bird: This causes trouble with RR NM records, since we'll be
             *        emitting the real directory name rather than '.' or '..' (or
             *        whatever we should be emitting for these two special dirs).
             *        FreeBSD got confused with this.  The RTFSISOMAKERDIRTYPE stuff is a
             *        workaround for this, however it doesn't hold up if we have to use
             *        the spill file. [RR NM ./..] */
            Assert(pCurName->cbDirRec != 0);
            Assert(pParentName->cbDirRec != 0);
            pCurDir->cbDirRec00 = pCurName->cbDirRec    - pCurName->cbNameInDirRec    - !(pCurName->cbNameInDirRec    & 1) + 1;
            pCurDir->cbDirRec01 = pParentName->cbDirRec - pParentName->cbNameInDirRec - !(pParentName->cbNameInDirRec & 1) + 1;

            uint32_t offInDir   = (uint32_t)pCurDir->cbDirRec00 + pCurDir->cbDirRec01;

            /* Finalize the directory entries. */
            uint32_t            cSubDirs    = 0;
            uint32_t            cbTransTbl  = 0;
            uint32_t            cLeft       = pCurDir->cChildren;
            PPRTFSISOMAKERNAME  ppChild     = pCurDir->papChildren;
            while (cLeft-- > 0)
            {
                PRTFSISOMAKERNAME pChild = *ppChild++;
                rc = rtFsIsoMakerFinalizeIsoDirectoryEntry(pFinalizedDirs, pChild, offInDir,
                                                           pNamespace->uRockRidgeLevel, false /*fIsRoot*/);
                AssertRCReturn(rc, rc);

                if ((RTFSISOMAKER_SECTOR_SIZE - (offInDir & RTFSISOMAKER_SECTOR_OFFSET_MASK)) < pChild->cbDirRecTotal)
                {
                    Assert(ppChild[-1] == pChild && &ppChild[-1] != pCurDir->papChildren);
                    if (   pChild->cDirRecs == 1
                        || pChild->cDirRecs <= RTFSISOMAKER_SECTOR_SIZE / pChild->cbDirRec)
                    {
                        ppChild[-2]->cbDirRecTotal += RTFSISOMAKER_SECTOR_SIZE - (offInDir & RTFSISOMAKER_SECTOR_OFFSET_MASK);
                        offInDir = (offInDir | RTFSISOMAKER_SECTOR_OFFSET_MASK) + 1; /* doesn't fit, skip to next sector. */
                        Log4(("rtFsIsoMakerFinalizeDirectoriesInIsoNamespace: zero padding dir rec @%#x: %#x -> %#x; offset %#x -> %#x\n",
                              ppChild[-2]->offDirRec, ppChild[-2]->cbDirRec, ppChild[-2]->cbDirRecTotal, pChild->offDirRec, offInDir));
                        pChild->offDirRec = offInDir;
                    }
                    /* else: too complicated and ulikely, so whatever. */
                }

                offInDir += pChild->cbDirRecTotal;
                if (pChild->cchTransNm)
                    cbTransTbl += 2 /* type & space*/
                               +  RT_MAX(pChild->cchName, RTFSISOMAKER_TRANS_TBL_LEFT_PAD)
                               +  1 /* tab */
                               +  pChild->cchTransNm
                               +  1 /* newline */;

                if (RTFS_IS_DIRECTORY(pChild->fMode))
                    cSubDirs++;
            }

            /* Set the directory size and location, advancing the data offset. */
            pCurDir->cbDir  = offInDir;
            pCurDir->offDir = *poffData;
            *poffData += RT_ALIGN_32(offInDir, RTFSISOMAKER_SECTOR_SIZE);

            /* Set the translation table file size. */
            if (pCurDir->pTransTblFile)
            {
                pCurDir->pTransTblFile->cbData = cbTransTbl;
                pThis->cbData += RT_ALIGN_32(cbTransTbl, RTFSISOMAKER_SECTOR_SIZE);
            }

            /* Add to the path table size calculation. */
            pCurDir->offPathTable = cbPathTable;
            pCurDir->idPathTable  = idPathTable++;
            cbPathTable += RTFSISOMAKER_CALC_PATHREC_SIZE(pCurName->cbNameInDirRec);

            /* Set the hardlink count. */
            pCurName->cHardlinks = cSubDirs + 2;

            Log4(("rtFsIsoMakerFinalizeDirectoriesInIsoNamespace: idxObj=#%#x cbDir=%#08x cChildren=%#05x %s\n",
                  pCurDir->pName->pObj->idxObj, pCurDir->cbDir, pCurDir->cChildren, pCurDir->pName->szName));
        }
    }

    /*
     * Remove rock ridge spill file if we haven't got any spill.
     * If we have, round the size up to a whole sector to avoid the slow path
     * when reading from it.
     */
    if (pFinalizedDirs->pRRSpillFile)
    {
        if (pFinalizedDirs->pRRSpillFile->cbData > 0)
        {
            pFinalizedDirs->pRRSpillFile->cbData = RT_ALIGN_64(pFinalizedDirs->pRRSpillFile->cbData, ISO9660_SECTOR_SIZE);
            pThis->cbData += pFinalizedDirs->pRRSpillFile->cbData;
        }
        else
        {
            rc = rtFsIsoMakerObjRemoveWorker(pThis, &pFinalizedDirs->pRRSpillFile->Core);
            if (RT_SUCCESS(rc))
                pFinalizedDirs->pRRSpillFile = NULL;
        }
    }

    /*
     * Calculate the path table offsets and move past them.
     */
    pFinalizedDirs->cbPathTable   = cbPathTable;
    pFinalizedDirs->offPathTableL = *poffData;
    *poffData += RT_ALIGN_64(cbPathTable, RTFSISOMAKER_SECTOR_SIZE);

    pFinalizedDirs->offPathTableM = *poffData;
    *poffData += RT_ALIGN_64(cbPathTable, RTFSISOMAKER_SECTOR_SIZE);

    return VINF_SUCCESS;
}



/**
 * Finalizes directories and related stuff.
 *
 * This will not generate actual directory data, but calculate the size of it
 * once it's generated.  Ditto for the path tables.  The exception is the rock
 * ridge spill file, which will be generated in memory.
 *
 * @returns IPRT status code.
 * @param   pThis               The ISO maker instance.
 * @param   poffData            The data offset (in/out).
 */
static int rtFsIsoMakerFinalizeDirectories(PRTFSISOMAKERINT pThis, uint64_t *poffData)
{
    /*
     * Locate the directories, width first, inserting them in the finalized lists so
     * we can process them efficiently.
     */
    rtFsIsoMakerFinalizeGatherDirs(&pThis->PrimaryIso, &pThis->PrimaryIsoDirs);
    rtFsIsoMakerFinalizeGatherDirs(&pThis->Joliet, &pThis->JolietDirs);

    /*
     * Process the primary ISO and joliet namespaces.
     */
    int rc = rtFsIsoMakerFinalizeDirectoriesInIsoNamespace(pThis, &pThis->PrimaryIso, &pThis->PrimaryIsoDirs, poffData);
    if (RT_SUCCESS(rc))
        rc = rtFsIsoMakerFinalizeDirectoriesInIsoNamespace(pThis, &pThis->Joliet, &pThis->JolietDirs, poffData);
    if (RT_SUCCESS(rc))
    {
        /*
         * Later: UDF, HFS.
         */
    }
    return rc;
}


/**
 * Finalizes data allocations.
 *
 * This will set the RTFSISOMAKERFILE::offData members.
 *
 * @returns IPRT status code.
 * @param   pThis               The ISO maker instance.
 * @param   poffData            The data offset (in/out).
 */
static int rtFsIsoMakerFinalizeData(PRTFSISOMAKERINT pThis, uint64_t *poffData)
{
    pThis->offFirstFile = *poffData;

    /*
     * We currently does not have any ordering prioritizing implemented, so we
     * just store files in the order they were added.
     */
    PRTFSISOMAKEROBJ pCur;
    RTListForEach(&pThis->ObjectHead, pCur, RTFSISOMAKEROBJ, Entry)
    {
        if (pCur->enmType == RTFSISOMAKEROBJTYPE_FILE)
        {
            PRTFSISOMAKERFILE pCurFile = (PRTFSISOMAKERFILE)pCur;
            if (pCurFile->offData == UINT64_MAX)
            {
                pCurFile->offData = *poffData;
                *poffData += RT_ALIGN_64(pCurFile->cbData, RTFSISOMAKER_SECTOR_SIZE);
                RTListAppend(&pThis->FinalizedFiles, &pCurFile->FinalizedEntry);
                Log4(("rtFsIsoMakerFinalizeData: %#x @%#RX64 cbData=%#RX64\n", pCurFile->Core.idxObj, pCurFile->offData, pCurFile->cbData));
            }

            /*
             * Create the boot info table.
             */
            if (pCurFile->pBootInfoTable)
            {
                /*
                 * Checksum the file.
                 */
                int rc;
                RTVFSFILE hVfsFile;
                uint64_t  offBase;
                switch (pCurFile->enmSrcType)
                {
                    case RTFSISOMAKERSRCTYPE_PATH:
                        rc = RTVfsChainOpenFile(pCurFile->u.pszSrcPath, RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
                                                &hVfsFile, NULL, NULL);
                        AssertMsgRCReturn(rc, ("%s -> %Rrc\n", pCurFile->u.pszSrcPath, rc), rc);
                        offBase = 0;
                        break;
                    case RTFSISOMAKERSRCTYPE_VFS_FILE:
                        hVfsFile = pCurFile->u.hVfsFile;
                        offBase = 0;
                        rc = VINF_SUCCESS;
                        break;
                    case RTFSISOMAKERSRCTYPE_COMMON:
                        hVfsFile = pThis->paCommonSources[pCurFile->u.Common.idxSrc];
                        offBase  = pCurFile->u.Common.offData;
                        rc = VINF_SUCCESS;
                        break;
                    default:
                        AssertMsgFailedReturn(("enmSrcType=%d\n", pCurFile->enmSrcType), VERR_IPE_NOT_REACHED_DEFAULT_CASE);
                }

                uint32_t uChecksum = 0;
                uint32_t off       = 64;
                uint32_t cbLeft    = RT_MAX(64, (uint32_t)pCurFile->cbData) - 64;
                while (cbLeft > 0)
                {
                    union
                    {
                        uint8_t     ab[_16K];
                        uint32_t    au32[_16K / sizeof(uint32_t)];
                    }        uBuf;
                    uint32_t cbRead = RT_MIN(sizeof(uBuf), cbLeft);
                    if (cbRead & 3)
                        RT_ZERO(uBuf);
                    rc = RTVfsFileReadAt(hVfsFile, offBase + off, &uBuf, cbRead, NULL);
                    if (RT_FAILURE(rc))
                        break;

                    size_t i = RT_ALIGN_Z(cbRead, sizeof(uint32_t)) / sizeof(uint32_t);
                    while (i-- > 0)
                        uChecksum += RT_LE2H_U32(uBuf.au32[i]);

                    off    += cbRead;
                    cbLeft -= cbRead;
                }

                if (pCurFile->enmSrcType == RTFSISOMAKERSRCTYPE_PATH)
                    RTVfsFileRelease(hVfsFile);
                if (RT_FAILURE(rc))
                    return rc;

                /*
                 * Populate the structure.
                 */
                pCurFile->pBootInfoTable->offPrimaryVolDesc = RT_H2LE_U32(16);
                pCurFile->pBootInfoTable->offBootFile       = RT_H2LE_U32((uint32_t)(pCurFile->offData / RTFSISOMAKER_SECTOR_SIZE));
                pCurFile->pBootInfoTable->cbBootFile        = RT_H2LE_U32((uint32_t)pCurFile->cbData);
                pCurFile->pBootInfoTable->uChecksum         = RT_H2LE_U32(uChecksum);
                RT_ZERO(pCurFile->pBootInfoTable->auReserved);
            }
        }
    }

    return VINF_SUCCESS;
}


/**
 * Copies the given string as UTF-16 and pad unused space in the destination
 * with spaces.
 *
 * @param   pachDst     The destination field.  C type is char, but real life
 *                      type is UTF-16 / UCS-2.
 * @param   cchDst      The size of the destination field.
 * @param   pszSrc      The source string. NULL is treated like empty string.
 */
static void rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(char *pachDst, size_t cchDst, const char *pszSrc)
{
    size_t cwcSrc = 0;
    if (pszSrc)
    {
        RTUTF16  wszSrc[256];
        PRTUTF16 pwszSrc = wszSrc;
        int rc = RTStrToUtf16BigEx(pszSrc, RTSTR_MAX, &pwszSrc, RT_ELEMENTS(wszSrc), &cwcSrc);
        AssertRCStmt(rc, cwcSrc = 0);

        if (cwcSrc > cchDst / sizeof(RTUTF16))
            cwcSrc = cchDst / sizeof(RTUTF16);
        memcpy(pachDst, wszSrc, cwcSrc * sizeof(RTUTF16));
    }

    /* Space padding.  Note! cchDst can be an odd number. */
    size_t cchWritten = cwcSrc * sizeof(RTUTF16);
    if (cchWritten < cchDst)
    {
        while (cchWritten + 2 <= cchDst)
        {
            pachDst[cchWritten++] = '\0';
            pachDst[cchWritten++] = ' ';
        }
        if (cchWritten < cchDst)
            pachDst[cchWritten] = '\0';
    }
}


/**
 * Copies the given string and pad unused space in the destination with spaces.
 *
 * @param   pachDst     The destination field.
 * @param   cchDst      The size of the destination field.
 * @param   pszSrc      The source string. NULL is treated like empty string.
 */
static void rtFsIsoMakerFinalizeCopyAndSpacePad(char *pachDst, size_t cchDst, const char *pszSrc)
{
    size_t cchSrc;
    if (!pszSrc)
        cchSrc = 0;
    else
    {
        cchSrc = strlen(pszSrc);
        if (cchSrc > cchDst)
            cchSrc = cchDst;
        memcpy(pachDst, pszSrc, cchSrc);
    }
    if (cchSrc < cchDst)
        memset(&pachDst[cchSrc], ' ', cchDst - cchSrc);
}


/**
 * Formats a timespec as an ISO-9660 ascii timestamp.
 *
 * @param   pTime       The timespec to format.
 * @param   pIsoTs      The ISO-9660 timestamp destination buffer.
 */
static void rtFsIsoMakerTimespecToIso9660Timestamp(PCRTTIMESPEC pTime, PISO9660TIMESTAMP pIsoTs)
{
    RTTIME Exploded;
    RTTimeExplode(&Exploded, pTime);

    char szTmp[64];
#define FORMAT_FIELD(a_achDst, a_uSrc) \
        do { \
            RTStrFormatU32(szTmp, sizeof(szTmp), a_uSrc, 10, sizeof(a_achDst), sizeof(a_achDst), \
                           RTSTR_F_ZEROPAD | RTSTR_F_WIDTH | RTSTR_F_PRECISION); \
            memcpy(a_achDst, szTmp, sizeof(a_achDst)); \
        } while (0)
    FORMAT_FIELD(pIsoTs->achYear,   Exploded.i32Year);
    FORMAT_FIELD(pIsoTs->achMonth,  Exploded.u8Month);
    FORMAT_FIELD(pIsoTs->achDay,    Exploded.u8MonthDay);
    FORMAT_FIELD(pIsoTs->achHour,   Exploded.u8Hour);
    FORMAT_FIELD(pIsoTs->achMinute, Exploded.u8Minute);
    FORMAT_FIELD(pIsoTs->achSecond, Exploded.u8Second);
    FORMAT_FIELD(pIsoTs->achCentisecond, Exploded.u32Nanosecond / RT_NS_10MS);
#undef FORMAT_FIELD
    pIsoTs->offUtc = 0;
}

/**
 * Formats zero ISO-9660 ascii timestamp (treated as not specified).
 *
 * @param   pIsoTs      The ISO-9660 timestamp destination buffer.
 */
static void rtFsIsoMakerZero9660Timestamp(PISO9660TIMESTAMP pIsoTs)
{
    memset(pIsoTs, '0', RT_UOFFSETOF(ISO9660TIMESTAMP, offUtc));
    pIsoTs->offUtc = 0;
}


/**
 * Formats a timespec as an ISO-9660 record timestamp.
 *
 * @param   pTime       The timespec to format.
 * @param   pIsoTs      The ISO-9660 timestamp destination buffer.
 */
static void rtFsIsoMakerTimespecToIso9660RecTimestamp(PCRTTIMESPEC pTime, PISO9660RECTIMESTAMP pIsoRecTs)
{
    RTTIME Exploded;
    RTTimeExplode(&Exploded, pTime);

    pIsoRecTs->bYear    = Exploded.i32Year >= 1900 ? Exploded.i32Year - 1900 : 0;
    pIsoRecTs->bMonth   = Exploded.u8Month;
    pIsoRecTs->bDay     = Exploded.u8MonthDay;
    pIsoRecTs->bHour    = Exploded.u8Hour;
    pIsoRecTs->bMinute  = Exploded.u8Minute;
    pIsoRecTs->bSecond  = Exploded.u8Second;
    pIsoRecTs->offUtc   = 0;
}


/**
 * Allocate and prepare the volume descriptors.
 *
 * What's not done here gets done later by rtFsIsoMakerFinalizeBootStuffPart2,
 * or at teh very end of the finalization by
 * rtFsIsoMakerFinalizeVolumeDescriptors.
 *
 * @returns IPRT status code
 * @param   pThis               The ISO maker instance.
 */
static int rtFsIsoMakerFinalizePrepVolumeDescriptors(PRTFSISOMAKERINT pThis)
{
    /*
     * Allocate and calc pointers.
     */
    RTMemFree(pThis->pbVolDescs);
    pThis->pbVolDescs = (uint8_t *)RTMemAllocZ(pThis->cVolumeDescriptors * RTFSISOMAKER_SECTOR_SIZE);
    AssertReturn(pThis->pbVolDescs, VERR_NO_MEMORY);

    uint32_t offVolDescs = 0;

    pThis->pPrimaryVolDesc = (PISO9660PRIMARYVOLDESC)&pThis->pbVolDescs[offVolDescs];
    offVolDescs += RTFSISOMAKER_SECTOR_SIZE;

    if (!pThis->pBootCatFile)
        pThis->pElToritoDesc = NULL;
    else
    {
        pThis->pElToritoDesc = (PISO9660BOOTRECORDELTORITO)&pThis->pbVolDescs[offVolDescs];
        offVolDescs += RTFSISOMAKER_SECTOR_SIZE;
    }

    if (!pThis->Joliet.uLevel)
        pThis->pJolietVolDesc = NULL;
    else
    {
        pThis->pJolietVolDesc = (PISO9660SUPVOLDESC)&pThis->pbVolDescs[offVolDescs];
        offVolDescs += RTFSISOMAKER_SECTOR_SIZE;
    }

    pThis->pTerminatorVolDesc = (PISO9660VOLDESCHDR)&pThis->pbVolDescs[offVolDescs];
    offVolDescs += RTFSISOMAKER_SECTOR_SIZE;

    if (pThis->Udf.uLevel > 0)
    {
        /** @todo UDF descriptors. */
    }
    AssertReturn(offVolDescs == pThis->cVolumeDescriptors * RTFSISOMAKER_SECTOR_SIZE, VERR_ISOMK_IPE_DESC_COUNT);

    /*
     * This may be needed later.
     */
    char szImageCreationTime[42];
    RTTimeSpecToString(&pThis->ImageCreationTime, szImageCreationTime, sizeof(szImageCreationTime));

    /*
     * Initialize the primary descriptor.
     */
    PISO9660PRIMARYVOLDESC pPrimary = pThis->pPrimaryVolDesc;

    pPrimary->Hdr.bDescType             = ISO9660VOLDESC_TYPE_PRIMARY;
    pPrimary->Hdr.bDescVersion          = ISO9660PRIMARYVOLDESC_VERSION;
    memcpy(pPrimary->Hdr.achStdId, ISO9660VOLDESC_STD_ID, sizeof(pPrimary->Hdr.achStdId));
    //pPrimary->bPadding8               = 0;
    rtFsIsoMakerFinalizeCopyAndSpacePad(pPrimary->achSystemId, sizeof(pPrimary->achSystemId), pThis->PrimaryIso.pszSystemId);
    rtFsIsoMakerFinalizeCopyAndSpacePad(pPrimary->achVolumeId, sizeof(pPrimary->achVolumeId),
                                        pThis->PrimaryIso.pszVolumeId ? pThis->PrimaryIso.pszVolumeId : szImageCreationTime);
    //pPrimary->Unused73                = {0}
    //pPrimary->VolumeSpaceSize         = later
    //pPrimary->abUnused89              = {0}
    pPrimary->cVolumesInSet.be          = RT_H2BE_U16_C(1);
    pPrimary->cVolumesInSet.le          = RT_H2LE_U16_C(1);
    pPrimary->VolumeSeqNo.be            = RT_H2BE_U16_C(1);
    pPrimary->VolumeSeqNo.le            = RT_H2LE_U16_C(1);
    pPrimary->cbLogicalBlock.be         = RT_H2BE_U16_C(RTFSISOMAKER_SECTOR_SIZE);
    pPrimary->cbLogicalBlock.le         = RT_H2LE_U16_C(RTFSISOMAKER_SECTOR_SIZE);
    //pPrimary->cbPathTable             = later
    //pPrimary->offTypeLPathTable       = later
    //pPrimary->offOptionalTypeLPathTable = {0}
    //pPrimary->offTypeMPathTable       = later
    //pPrimary->offOptionalTypeMPathTable = {0}
    //pPrimary->RootDir                 = later
    rtFsIsoMakerFinalizeCopyAndSpacePad(pPrimary->achVolumeSetId, sizeof(pPrimary->achVolumeSetId),
                                        pThis->PrimaryIso.pszVolumeSetId);
    rtFsIsoMakerFinalizeCopyAndSpacePad(pPrimary->achPublisherId, sizeof(pPrimary->achPublisherId),
                                        pThis->PrimaryIso.pszPublisherId);
    rtFsIsoMakerFinalizeCopyAndSpacePad(pPrimary->achDataPreparerId, sizeof(pPrimary->achDataPreparerId),
                                        pThis->PrimaryIso.pszDataPreparerId);
    rtFsIsoMakerFinalizeCopyAndSpacePad(pPrimary->achApplicationId, sizeof(pPrimary->achApplicationId),
                                        pThis->PrimaryIso.pszApplicationId);
    rtFsIsoMakerFinalizeCopyAndSpacePad(pPrimary->achCopyrightFileId, sizeof(pPrimary->achCopyrightFileId),
                                        pThis->PrimaryIso.pszCopyrightFileId);
    rtFsIsoMakerFinalizeCopyAndSpacePad(pPrimary->achAbstractFileId, sizeof(pPrimary->achAbstractFileId),
                                        pThis->PrimaryIso.pszAbstractFileId);
    rtFsIsoMakerFinalizeCopyAndSpacePad(pPrimary->achBibliographicFileId, sizeof(pPrimary->achBibliographicFileId),
                                        pThis->PrimaryIso.pszBibliographicFileId);
    rtFsIsoMakerTimespecToIso9660Timestamp(&pThis->ImageCreationTime, &pPrimary->BirthTime);
    rtFsIsoMakerTimespecToIso9660Timestamp(&pThis->ImageCreationTime, &pPrimary->ModifyTime);
    rtFsIsoMakerZero9660Timestamp(&pPrimary->ExpireTime);
    rtFsIsoMakerZero9660Timestamp(&pPrimary->EffectiveTime);
    pPrimary->bFileStructureVersion     = ISO9660_FILE_STRUCTURE_VERSION;
    //pPrimary->bReserved883            = 0;
    //RT_ZERO(pPrimary->abAppUse);
    //RT_ZERO(pPrimary->abReserved1396);

    /*
     * Initialize the joliet descriptor if included.
     */
    PISO9660SUPVOLDESC pJoliet = pThis->pJolietVolDesc;
    if (pJoliet)
    {
        pJoliet->Hdr.bDescType              = ISO9660VOLDESC_TYPE_SUPPLEMENTARY;
        pJoliet->Hdr.bDescVersion           = ISO9660SUPVOLDESC_VERSION;
        memcpy(pJoliet->Hdr.achStdId, ISO9660VOLDESC_STD_ID, sizeof(pJoliet->Hdr.achStdId));
        pJoliet->fVolumeFlags               = ISO9660SUPVOLDESC_VOL_F_ESC_ONLY_REG;
        rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(pJoliet->achSystemId, sizeof(pJoliet->achSystemId), pThis->Joliet.pszSystemId);
        rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(pJoliet->achVolumeId, sizeof(pJoliet->achVolumeId),
                                                      pThis->Joliet.pszVolumeId ? pThis->Joliet.pszVolumeId : szImageCreationTime);
        //pJoliet->Unused73                 = {0}
        //pJoliet->VolumeSpaceSize          = later
        memset(pJoliet->abEscapeSequences, ' ', sizeof(pJoliet->abEscapeSequences));
        pJoliet->abEscapeSequences[0]       = ISO9660_JOLIET_ESC_SEQ_0;
        pJoliet->abEscapeSequences[1]       = ISO9660_JOLIET_ESC_SEQ_1;
        pJoliet->abEscapeSequences[2]       = pThis->Joliet.uLevel == 1 ? ISO9660_JOLIET_ESC_SEQ_2_LEVEL_1
                                            : pThis->Joliet.uLevel == 2 ? ISO9660_JOLIET_ESC_SEQ_2_LEVEL_2
                                            :                             ISO9660_JOLIET_ESC_SEQ_2_LEVEL_3;
        pJoliet->cVolumesInSet.be           = RT_H2BE_U16_C(1);
        pJoliet->cVolumesInSet.le           = RT_H2LE_U16_C(1);
        pJoliet->VolumeSeqNo.be             = RT_H2BE_U16_C(1);
        pJoliet->VolumeSeqNo.le             = RT_H2LE_U16_C(1);
        pJoliet->cbLogicalBlock.be          = RT_H2BE_U16_C(RTFSISOMAKER_SECTOR_SIZE);
        pJoliet->cbLogicalBlock.le          = RT_H2LE_U16_C(RTFSISOMAKER_SECTOR_SIZE);
        //pJoliet->cbPathTable              = later
        //pJoliet->offTypeLPathTable        = later
        //pJoliet->offOptionalTypeLPathTable = {0}
        //pJoliet->offTypeMPathTable        = later
        //pJoliet->offOptionalTypeMPathTable = {0}
        //pJoliet->RootDir                  = later
        rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(pJoliet->achVolumeSetId, sizeof(pJoliet->achVolumeSetId),
                                                      pThis->Joliet.pszVolumeSetId);
        rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(pJoliet->achPublisherId, sizeof(pJoliet->achPublisherId),
                                                      pThis->Joliet.pszPublisherId);
        rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(pJoliet->achDataPreparerId, sizeof(pJoliet->achDataPreparerId),
                                                      pThis->Joliet.pszDataPreparerId);
        rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(pJoliet->achApplicationId, sizeof(pJoliet->achApplicationId),
                                                      pThis->Joliet.pszApplicationId);
        rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(pJoliet->achCopyrightFileId, sizeof(pJoliet->achCopyrightFileId),
                                                      pThis->Joliet.pszCopyrightFileId);
        rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(pJoliet->achAbstractFileId, sizeof(pJoliet->achAbstractFileId),
                                                      pThis->Joliet.pszAbstractFileId);
        rtFsIsoMakerFinalizeCopyAsUtf16BigAndSpacePad(pJoliet->achBibliographicFileId, sizeof(pJoliet->achBibliographicFileId),
                                                      pThis->Joliet.pszBibliographicFileId);
        rtFsIsoMakerTimespecToIso9660Timestamp(&pThis->ImageCreationTime, &pJoliet->BirthTime);
        rtFsIsoMakerTimespecToIso9660Timestamp(&pThis->ImageCreationTime, &pJoliet->ModifyTime);
        rtFsIsoMakerZero9660Timestamp(&pJoliet->ExpireTime);
        rtFsIsoMakerZero9660Timestamp(&pJoliet->EffectiveTime);
        pJoliet->bFileStructureVersion      = ISO9660_FILE_STRUCTURE_VERSION;
        //pJoliet->bReserved883             = 0;
        //RT_ZERO(pJoliet->abAppUse);
        //RT_ZERO(pJoliet->abReserved1396);
    }

    /*
     * The ISO-9660 terminator descriptor.
     */
    pThis->pTerminatorVolDesc->bDescType    = ISO9660VOLDESC_TYPE_TERMINATOR;
    pThis->pTerminatorVolDesc->bDescVersion = 1;
    memcpy(pThis->pTerminatorVolDesc->achStdId, ISO9660VOLDESC_STD_ID, sizeof(pThis->pTerminatorVolDesc->achStdId));

    return VINF_SUCCESS;
}


/**
 * Finalizes the volume descriptors.
 *
 * This will set the RTFSISOMAKERFILE::offData members.
 *
 * @returns IPRT status code.
 * @param   pThis               The ISO maker instance.
 */
static int rtFsIsoMakerFinalizeVolumeDescriptors(PRTFSISOMAKERINT pThis)
{
    AssertReturn(pThis->pbVolDescs && pThis->pPrimaryVolDesc && pThis->pTerminatorVolDesc, VERR_ISOMK_IPE_FINALIZE_1);

    /*
     * Primary descriptor.
     */
    PISO9660PRIMARYVOLDESC pPrimary = pThis->pPrimaryVolDesc;

    pPrimary->VolumeSpaceSize.be        = RT_H2BE_U32(pThis->cbFinalizedImage / RTFSISOMAKER_SECTOR_SIZE);
    pPrimary->VolumeSpaceSize.le        = RT_H2LE_U32(pThis->cbFinalizedImage / RTFSISOMAKER_SECTOR_SIZE);
    pPrimary->cbPathTable.be            = RT_H2BE_U32(pThis->PrimaryIsoDirs.cbPathTable);
    pPrimary->cbPathTable.le            = RT_H2LE_U32(pThis->PrimaryIsoDirs.cbPathTable);
    pPrimary->offTypeLPathTable         = RT_H2LE_U32(pThis->PrimaryIsoDirs.offPathTableL / RTFSISOMAKER_SECTOR_SIZE);
    pPrimary->offTypeMPathTable         = RT_H2BE_U32(pThis->PrimaryIsoDirs.offPathTableM / RTFSISOMAKER_SECTOR_SIZE);
    pPrimary->RootDir.DirRec.cbDirRec           = sizeof(pPrimary->RootDir);
    pPrimary->RootDir.DirRec.cExtAttrBlocks     = 0;
    pPrimary->RootDir.DirRec.offExtent.be       = RT_H2BE_U32(pThis->PrimaryIso.pRoot->pDir->offDir / RTFSISOMAKER_SECTOR_SIZE);
    pPrimary->RootDir.DirRec.offExtent.le       = RT_H2LE_U32(pThis->PrimaryIso.pRoot->pDir->offDir / RTFSISOMAKER_SECTOR_SIZE);
    pPrimary->RootDir.DirRec.cbData.be          = RT_H2BE_U32(pThis->PrimaryIso.pRoot->pDir->cbDir);
    pPrimary->RootDir.DirRec.cbData.le          = RT_H2LE_U32(pThis->PrimaryIso.pRoot->pDir->cbDir);
    rtFsIsoMakerTimespecToIso9660RecTimestamp(&pThis->PrimaryIso.pRoot->pObj->BirthTime, &pPrimary->RootDir.DirRec.RecTime);
    pPrimary->RootDir.DirRec.fFileFlags         = ISO9660_FILE_FLAGS_DIRECTORY;
    pPrimary->RootDir.DirRec.bFileUnitSize      = 0;
    pPrimary->RootDir.DirRec.bInterleaveGapSize = 0;
    pPrimary->RootDir.DirRec.VolumeSeqNo.be     = RT_H2BE_U16_C(1);
    pPrimary->RootDir.DirRec.VolumeSeqNo.le     = RT_H2LE_U16_C(1);
    pPrimary->RootDir.DirRec.bFileIdLength      = 1;
    pPrimary->RootDir.DirRec.achFileId[0]       = 0x00;

    /*
     * Initialize the joliet descriptor if included.
     */
    PISO9660SUPVOLDESC pJoliet = pThis->pJolietVolDesc;
    if (pJoliet)
    {
        pJoliet->VolumeSpaceSize            = pPrimary->VolumeSpaceSize;
        pJoliet->cbPathTable.be             = RT_H2BE_U32(pThis->JolietDirs.cbPathTable);
        pJoliet->cbPathTable.le             = RT_H2LE_U32(pThis->JolietDirs.cbPathTable);
        pJoliet->offTypeLPathTable          = RT_H2LE_U32(pThis->JolietDirs.offPathTableL / RTFSISOMAKER_SECTOR_SIZE);
        pJoliet->offTypeMPathTable          = RT_H2BE_U32(pThis->JolietDirs.offPathTableM / RTFSISOMAKER_SECTOR_SIZE);
        pJoliet->RootDir.DirRec.cbDirRec           = sizeof(pJoliet->RootDir);
        pJoliet->RootDir.DirRec.cExtAttrBlocks     = 0;
        pJoliet->RootDir.DirRec.offExtent.be       = RT_H2BE_U32(pThis->Joliet.pRoot->pDir->offDir / RTFSISOMAKER_SECTOR_SIZE);
        pJoliet->RootDir.DirRec.offExtent.le       = RT_H2LE_U32(pThis->Joliet.pRoot->pDir->offDir / RTFSISOMAKER_SECTOR_SIZE);
        pJoliet->RootDir.DirRec.cbData.be          = RT_H2BE_U32(pThis->Joliet.pRoot->pDir->cbDir);
        pJoliet->RootDir.DirRec.cbData.le          = RT_H2LE_U32(pThis->Joliet.pRoot->pDir->cbDir);
        rtFsIsoMakerTimespecToIso9660RecTimestamp(&pThis->Joliet.pRoot->pObj->BirthTime, &pJoliet->RootDir.DirRec.RecTime);
        pJoliet->RootDir.DirRec.fFileFlags         = ISO9660_FILE_FLAGS_DIRECTORY;
        pJoliet->RootDir.DirRec.bFileUnitSize      = 0;
        pJoliet->RootDir.DirRec.bInterleaveGapSize = 0;
        pJoliet->RootDir.DirRec.VolumeSeqNo.be     = RT_H2BE_U16_C(1);
        pJoliet->RootDir.DirRec.VolumeSeqNo.le     = RT_H2LE_U16_C(1);
        pJoliet->RootDir.DirRec.bFileIdLength      = 1;
        pJoliet->RootDir.DirRec.achFileId[0]       = 0x00;
    }

#if 0 /* this doesn't quite fool it. */
    /*
     * isomd5sum fake.
     */
    if (1)
    {
        uint8_t      abDigest[RTMD5_HASH_SIZE];
        if (pThis->cbSysArea == 0)
            RTMd5(g_abRTZero4K, ISO9660_SECTOR_SIZE, abDigest);
        else
        {
            RTMD5CONTEXT Ctx;
            RTMd5Init(&Ctx);
            RTMd5Update(&Ctx, pThis->pbSysArea, RT_MIN(pThis->cbSysArea, ISO9660_SECTOR_SIZE));
            if (pThis->cbSysArea < ISO9660_SECTOR_SIZE)
                RTMd5Update(&Ctx, g_abRTZero4K, ISO9660_SECTOR_SIZE - pThis->cbSysArea);
            RTMd5Final(abDigest, &Ctx);
        }
        char szFakeHash[RTMD5_DIGEST_LEN + 1];
        RTMd5ToString(abDigest, szFakeHash, sizeof(szFakeHash));

        size_t cch = RTStrPrintf((char *)&pPrimary->abAppUse[0], sizeof(pPrimary->abAppUse),
                                 "ISO MD5SUM = %s;SKIPSECTORS = %u;RHLISOSTATUS=1;THIS IS JUST A FAKE!",
                                 szFakeHash, pThis->cbFinalizedImage / RTFSISOMAKER_SECTOR_SIZE - 1);
        memset(&pPrimary->abAppUse[cch], ' ', sizeof(pPrimary->abAppUse) - cch);
    }
#endif

    return VINF_SUCCESS;
}


/**
 * Finalizes the image.
 *
 * @returns IPRT status code.
 * @param   hIsoMaker       The ISO maker handle.
 */
RTDECL(int) RTFsIsoMakerFinalize(RTFSISOMAKER hIsoMaker)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(!pThis->fFinalized, VERR_WRONG_ORDER);

    /*
     * Remove orphaned objects and allocate volume descriptors.
     */
    int rc = rtFsIsoMakerFinalizeRemoveOrphans(pThis);
    if (RT_FAILURE(rc))
        return rc;
    AssertReturn(pThis->cObjects > 0, VERR_NO_DATA);

    /* The primary ISO-9660 namespace must be explicitly disabled (for now),
       so we return VERR_NO_DATA if no root dir. */
    AssertReturn(pThis->PrimaryIso.pRoot || pThis->PrimaryIso.uLevel == 0, VERR_NO_DATA);

    /* Automatically disable the joliet namespace if it is empty (no root dir). */
    if (!pThis->Joliet.pRoot && pThis->Joliet.uLevel > 0)
    {
        pThis->Joliet.uLevel = 0;
        pThis->cVolumeDescriptors--;
    }

    rc = rtFsIsoMakerFinalizePrepVolumeDescriptors(pThis);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * If there is any boot related stuff to be included, it ends up right after
     * the descriptors.
     */
    uint64_t offData = _32K + pThis->cVolumeDescriptors * RTFSISOMAKER_SECTOR_SIZE;
    rc = rtFsIsoMakerFinalizeBootStuffPart1(pThis);
    if (RT_SUCCESS(rc))
    {
        /*
         * Directories and path tables comes next.
         */
        rc = rtFsIsoMakerFinalizeDirectories(pThis, &offData);
        if (RT_SUCCESS(rc))
        {
            /*
             * Then we store the file data.
             */
            rc = rtFsIsoMakerFinalizeData(pThis, &offData);
            if (RT_SUCCESS(rc))
            {
                pThis->cbFinalizedImage = offData + pThis->cbImagePadding;

                /*
                 * Do a 2nd pass over the boot stuff to finalize locations.
                 */
                rc = rtFsIsoMakerFinalizeBootStuffPart2(pThis);
                if (RT_SUCCESS(rc))
                {
                    /*
                     * Finally, finalize the volume descriptors as they depend on some of the
                     * block allocations done in the previous steps.
                     */
                    rc = rtFsIsoMakerFinalizeVolumeDescriptors(pThis);
                    if (RT_SUCCESS(rc))
                    {
                        pThis->fFinalized = true;
                        return VINF_SUCCESS;
                    }
                }
            }
        }
    }
    return rc;
}





/*
 *
 * Image I/O.
 * Image I/O.
 * Image I/O.
 *
 */

/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtFsIsoMakerOutFile_Close(void *pvThis)
{
    PRTFSISOMAKEROUTPUTFILE pThis = (PRTFSISOMAKEROUTPUTFILE)pvThis;

    RTFsIsoMakerRelease(pThis->pIsoMaker);
    pThis->pIsoMaker = NULL;

    if (pThis->hVfsSrcFile != NIL_RTVFSFILE)
    {
        RTVfsFileRelease(pThis->hVfsSrcFile);
        pThis->hVfsSrcFile = NIL_RTVFSFILE;
    }

    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtFsIsoMakerOutFile_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTFSISOMAKEROUTPUTFILE pThis     = (PRTFSISOMAKEROUTPUTFILE)pvThis;
    PRTFSISOMAKERINT        pIsoMaker = pThis->pIsoMaker;


    pObjInfo->cbObject         = pIsoMaker->cbFinalizedImage;
    pObjInfo->cbAllocated      = pIsoMaker->cbFinalizedImage;
    pObjInfo->AccessTime       = pIsoMaker->ImageCreationTime;
    pObjInfo->ModificationTime = pIsoMaker->ImageCreationTime;
    pObjInfo->ChangeTime       = pIsoMaker->ImageCreationTime;
    pObjInfo->BirthTime        = pIsoMaker->ImageCreationTime;
    pObjInfo->Attr.fMode       = 0444 | RTFS_TYPE_FILE | RTFS_DOS_READONLY;

    switch (enmAddAttr)
    {
        case RTFSOBJATTRADD_NOTHING:
            enmAddAttr = RTFSOBJATTRADD_UNIX;
            RT_FALL_THRU();
        case RTFSOBJATTRADD_UNIX:
            pObjInfo->Attr.u.Unix.uid           = NIL_RTUID;
            pObjInfo->Attr.u.Unix.gid           = NIL_RTGID;
            pObjInfo->Attr.u.Unix.cHardlinks    = 1;
            pObjInfo->Attr.u.Unix.INodeIdDevice = 0;
            pObjInfo->Attr.u.Unix.INodeId       = 0;
            pObjInfo->Attr.u.Unix.fFlags        = 0;
            pObjInfo->Attr.u.Unix.GenerationId  = 0;
            pObjInfo->Attr.u.Unix.Device        = 0;
            break;

        case RTFSOBJATTRADD_UNIX_OWNER:
            pObjInfo->Attr.u.UnixOwner.uid = NIL_RTUID;
            pObjInfo->Attr.u.UnixOwner.szName[0] = '\0';
            break;

        case RTFSOBJATTRADD_UNIX_GROUP:
            pObjInfo->Attr.u.UnixGroup.gid = NIL_RTGID;
            pObjInfo->Attr.u.UnixGroup.szName[0] = '\0';
            break;

        case RTFSOBJATTRADD_EASIZE:
            pObjInfo->Attr.u.EASize.cb = 0;
            break;

        default:
            AssertFailedReturn(VERR_INVALID_PARAMETER);
    }
    pObjInfo->Attr.enmAdditional = enmAddAttr;

    return VINF_SUCCESS;
}


/**
 * Generates the 'SL' records for a symbolic link.
 *
 * This is used both when generating directories records, spill file data and
 * when creating the symbolic link.
 *
 * @returns Number of bytes produced.  Negative IPRT status if buffer overflow.
 * @param   pszTarget   The symbolic link target to encode.
 * @param   pbBuf       The output buffer.
 * @param   cbBuf       The size of the output buffer.
 */
static ssize_t rtFsIsoMakerOutFile_RockRidgeGenSL(const char *pszTarget, uint8_t *pbBuf, size_t cbBuf)
{
    Assert(*pszTarget != '\0');

    PISO9660RRIPSL pEntry = (PISO9660RRIPSL)pbBuf;
    pEntry->Hdr.bSig1    = ISO9660RRIPSL_SIG1;
    pEntry->Hdr.bSig2    = ISO9660RRIPSL_SIG2;
    pEntry->Hdr.cbEntry  = 0; /* set later. */
    pEntry->Hdr.bVersion = ISO9660RRIPSL_VER;
    pEntry->fFlags       = 0;
    size_t  offEntry = 0;
    size_t  off      = RT_UOFFSETOF(ISO9660RRIPSL, abComponents);

    /* Does it start with a root slash? */
    if (RTPATH_IS_SLASH(*pszTarget))
    {
        pbBuf[off++] = ISO9660RRIP_SL_C_ROOT;
        pbBuf[off++] = 0;
        pszTarget++;
    }

    for (;;)
    {
        /* Find the end of the component. */
        size_t cchComponent = 0;
        char   ch;
        while ((ch = pszTarget[cchComponent]) != '\0' && !RTPATH_IS_SLASH(ch))
            cchComponent++;

        /* Check for dots and figure out how much space we need. */
        uint8_t fFlags;
        size_t  cbNeeded;
        if (cchComponent == 1 && *pszTarget == '.')
        {
            fFlags   = ISO9660RRIP_SL_C_CURRENT;
            cbNeeded = 2;
        }
        else if (cchComponent == 2 && pszTarget[0] == '.' && pszTarget[1] == '.')
        {
            fFlags   = ISO9660RRIP_SL_C_PARENT;
            cbNeeded = 2;
        }
        else
        {
            fFlags   = 0;
            cbNeeded = 2 + cchComponent;
        }

        /* Split the SL record if we're out of space. */
        if (   off - offEntry + cbNeeded < UINT8_MAX
            && off + cbNeeded <= cbBuf)
        { /* likely */ }
        else if (cbNeeded + RT_UOFFSETOF(ISO9660RRIPSL, abComponents) < UINT8_MAX)
        {
            AssertReturn(off + cbNeeded + RT_UOFFSETOF(ISO9660RRIPSL, abComponents) <= cbBuf, VERR_BUFFER_OVERFLOW);
            Assert(off - offEntry < UINT8_MAX);
            pEntry->Hdr.cbEntry = (uint8_t)(off - offEntry);
            pEntry->fFlags |= ISO9660RRIP_SL_F_CONTINUE;

            offEntry = off;
            pEntry = (PISO9660RRIPSL)&pbBuf[off];
            pEntry->Hdr.bSig1    = ISO9660RRIPSL_SIG1;
            pEntry->Hdr.bSig2    = ISO9660RRIPSL_SIG2;
            pEntry->Hdr.cbEntry  = 0; /* set later. */
            pEntry->Hdr.bVersion = ISO9660RRIPSL_VER;
            pEntry->fFlags       = 0;
        }
        else
        {
            /* Special case: component doesn't fit in a single SL entry. */
            do
            {
                if (off - offEntry + 3 < UINT8_MAX)
                {
                    size_t cchLeft   = UINT8_MAX - 1 - (off - offEntry) - 2;
                    size_t cchToCopy = RT_MIN(cchLeft, cchComponent);
                    AssertReturn(off + 2 + cchToCopy <= cbBuf, VERR_BUFFER_OVERFLOW);
                    pbBuf[off++] = cchToCopy < cchComponent ? ISO9660RRIP_SL_C_CONTINUE : 0;
                    pbBuf[off++] = (uint8_t)cchToCopy;
                    memcpy(&pbBuf[off], pszTarget, cchToCopy);
                    off          += cchToCopy;
                    pszTarget    += cchToCopy;
                    cchComponent -= cchToCopy;
                    if (!cchComponent)
                        break;
                }

                Assert(off - offEntry < UINT8_MAX);
                pEntry->Hdr.cbEntry = (uint8_t)(off - offEntry);
                pEntry->fFlags |= ISO9660RRIP_SL_F_CONTINUE;

                AssertReturn(off + 2 + cchComponent + RT_UOFFSETOF(ISO9660RRIPSL, abComponents) <= cbBuf, VERR_BUFFER_OVERFLOW);
                offEntry = off;
                pEntry = (PISO9660RRIPSL)&pbBuf[off];
                pEntry->Hdr.bSig1    = ISO9660RRIPSL_SIG1;
                pEntry->Hdr.bSig2    = ISO9660RRIPSL_SIG2;
                pEntry->Hdr.cbEntry  = 0; /* set later. */
                pEntry->Hdr.bVersion = ISO9660RRIPSL_VER;
                pEntry->fFlags       = 0;
            } while (cchComponent > 0);
            if (ch == '\0')
                break;
            pszTarget++;
            continue;
        }

        /* Produce the record. */
        pbBuf[off++] = fFlags;
        pbBuf[off++] = (uint8_t)(cbNeeded - 2);
        if (cchComponent > 0)
        {
            memcpy(&pbBuf[off], pszTarget, cbNeeded - 2);
            off += cbNeeded - 2;
        }

        if (ch == '\0')
            break;
        pszTarget += cchComponent + 1;
    }

    Assert(off - offEntry < UINT8_MAX);
    pEntry->Hdr.cbEntry = (uint8_t)(off - offEntry);
    return off;
}


/**
 * Generates rock ridge data.
 *
 * This is used both for the directory record and for the spill file ('CE').
 *
 * @param   pName           The name to generate rock ridge info for.
 * @param   pbSys           The output buffer.
 * @param   cbSys           The size of the output buffer.
 * @param   fInSpill        Indicates whether we're in a spill file (true) or
 *                          directory record (false).
 * @param   enmDirType      The kind of directory entry this is.
 */
static void rtFsIosMakerOutFile_GenerateRockRidge(PRTFSISOMAKERNAME pName, uint8_t *pbSys, size_t cbSys,
                                                  bool fInSpill, RTFSISOMAKERDIRTYPE enmDirType)
{
    /*
     * Deal with records specific to the root directory '.' entry.
     */
    if (pName->pParent != NULL)
    { /* likely */ }
    else
    {
        if (!fInSpill)
        {
            PISO9660SUSPSP  pSP = (PISO9660SUSPSP)pbSys;
            Assert(cbSys >= sizeof(*pSP));
            pSP->Hdr.bSig1      = ISO9660SUSPSP_SIG1;
            pSP->Hdr.bSig2      = ISO9660SUSPSP_SIG2;
            pSP->Hdr.cbEntry    = ISO9660SUSPSP_LEN;
            pSP->Hdr.bVersion   = ISO9660SUSPSP_VER;
            pSP->bCheck1        = ISO9660SUSPSP_CHECK1;
            pSP->bCheck2        = ISO9660SUSPSP_CHECK2;
            pSP->cbSkip         = 0;
            pbSys += sizeof(*pSP);
            cbSys -= sizeof(*pSP);
        }
        if (pName->fRockNeedER)
        {
            PISO9660SUSPER  pER = (PISO9660SUSPER)pbSys;
            Assert(cbSys >= ISO9660_RRIP_ER_LEN);
            AssertCompile(ISO9660_RRIP_ER_LEN < UINT8_MAX);
            pER->Hdr.bSig1      = ISO9660SUSPER_SIG1;
            pER->Hdr.bSig2      = ISO9660SUSPER_SIG2;
            pER->Hdr.cbEntry    = ISO9660_RRIP_ER_LEN;
            pER->Hdr.bVersion   = ISO9660SUSPER_VER;
            pER->cchIdentifier  = sizeof(ISO9660_RRIP_ID)   - 1;
            pER->cchDescription = sizeof(ISO9660_RRIP_DESC) - 1;
            pER->cchSource      = sizeof(ISO9660_RRIP_SRC)  - 1;
            pER->bVersion       = ISO9660_RRIP_VER;
            char *pchDst = &pER->achPayload[0]; /* we do this to shut up annoying clang. */
            memcpy(pchDst, RT_STR_TUPLE(ISO9660_RRIP_ID));
            pchDst += sizeof(ISO9660_RRIP_ID) - 1;
            memcpy(pchDst, RT_STR_TUPLE(ISO9660_RRIP_DESC));
            pchDst += sizeof(ISO9660_RRIP_DESC) - 1;
            memcpy(pchDst, RT_STR_TUPLE(ISO9660_RRIP_SRC));
            pbSys += ISO9660_RRIP_ER_LEN;
            cbSys -= ISO9660_RRIP_ER_LEN;
        }
    }

    /*
     * Deal with common stuff.
     */
    if (!fInSpill ? pName->fRockNeedRRInDirRec : pName->fRockNeedRRInSpill)
    {
        PISO9660RRIPRR  pRR = (PISO9660RRIPRR)pbSys;
        Assert(cbSys >= sizeof(*pRR));
        pRR->Hdr.bSig1      = ISO9660RRIPRR_SIG1;
        pRR->Hdr.bSig2      = ISO9660RRIPRR_SIG2;
        pRR->Hdr.cbEntry    = ISO9660RRIPRR_LEN;
        pRR->Hdr.bVersion   = ISO9660RRIPRR_VER;
        pRR->fFlags         = pName->fRockEntries;
        pbSys += sizeof(*pRR);
        cbSys -= sizeof(*pRR);
    }

    /*
     * The following entries all end up in the spill or fully in
     * the directory record.
     */
    if (fInSpill || pName->cbRockSpill == 0)
    {
        if (pName->fRockEntries & ISO9660RRIP_RR_F_PX)
        {
            PISO9660RRIPPX pPX = (PISO9660RRIPPX)pbSys;
            Assert(cbSys >= sizeof(*pPX));
            pPX->Hdr.bSig1      = ISO9660RRIPPX_SIG1;
            pPX->Hdr.bSig2      = ISO9660RRIPPX_SIG2;
            pPX->Hdr.cbEntry    = ISO9660RRIPPX_LEN;
            pPX->Hdr.bVersion   = ISO9660RRIPPX_VER;
            pPX->fMode.be       = RT_H2BE_U32((uint32_t)(pName->fMode & RTFS_UNIX_MASK));
            pPX->fMode.le       = RT_H2LE_U32((uint32_t)(pName->fMode & RTFS_UNIX_MASK));
            pPX->cHardlinks.be  = RT_H2BE_U32((uint32_t)pName->cHardlinks);
            pPX->cHardlinks.le  = RT_H2LE_U32((uint32_t)pName->cHardlinks);
            pPX->uid.be         = RT_H2BE_U32((uint32_t)pName->uid);
            pPX->uid.le         = RT_H2LE_U32((uint32_t)pName->uid);
            pPX->gid.be         = RT_H2BE_U32((uint32_t)pName->gid);
            pPX->gid.le         = RT_H2LE_U32((uint32_t)pName->gid);
#if 0 /* This is confusing solaris.  Looks like it has code assuming inode numbers are block numbers and ends up mistaking files for the root dir.  Sigh. */
            pPX->INode.be       = RT_H2BE_U32((uint32_t)pName->pObj->idxObj + 1); /* Don't use zero - isoinfo doesn't like it. */
            pPX->INode.le       = RT_H2LE_U32((uint32_t)pName->pObj->idxObj + 1);
#else
            pPX->INode.be       = 0;
            pPX->INode.le       = 0;
#endif
            pbSys += sizeof(*pPX);
            cbSys -= sizeof(*pPX);
        }

        if (pName->fRockEntries & ISO9660RRIP_RR_F_TF)
        {
            PISO9660RRIPTF pTF = (PISO9660RRIPTF)pbSys;
            pTF->Hdr.bSig1      = ISO9660RRIPTF_SIG1;
            pTF->Hdr.bSig2      = ISO9660RRIPTF_SIG2;
            pTF->Hdr.cbEntry    = Iso9660RripTfCalcLength(ISO9660RRIPTF_F_BIRTH | ISO9660RRIPTF_F_MODIFY | ISO9660RRIPTF_F_ACCESS | ISO9660RRIPTF_F_CHANGE);
            Assert(cbSys >= pTF->Hdr.cbEntry);
            pTF->Hdr.bVersion   = ISO9660RRIPTF_VER;
            pTF->fFlags         = ISO9660RRIPTF_F_BIRTH | ISO9660RRIPTF_F_MODIFY | ISO9660RRIPTF_F_ACCESS | ISO9660RRIPTF_F_CHANGE;
            PISO9660RECTIMESTAMP paTimestamps = (PISO9660RECTIMESTAMP)&pTF->abPayload[0];
            rtFsIsoMakerTimespecToIso9660RecTimestamp(&pName->pObj->BirthTime,        &paTimestamps[0]);
            rtFsIsoMakerTimespecToIso9660RecTimestamp(&pName->pObj->ModificationTime, &paTimestamps[1]);
            rtFsIsoMakerTimespecToIso9660RecTimestamp(&pName->pObj->AccessedTime,     &paTimestamps[2]);
            rtFsIsoMakerTimespecToIso9660RecTimestamp(&pName->pObj->ChangeTime,       &paTimestamps[3]);
            cbSys -= pTF->Hdr.cbEntry;
            pbSys += pTF->Hdr.cbEntry;
        }

        if (pName->fRockEntries & ISO9660RRIP_RR_F_PN)
        {
            PISO9660RRIPPN pPN = (PISO9660RRIPPN)pbSys;
            Assert(cbSys >= sizeof(*pPN));
            pPN->Hdr.bSig1      = ISO9660RRIPPN_SIG1;
            pPN->Hdr.bSig2      = ISO9660RRIPPN_SIG2;
            pPN->Hdr.cbEntry    = ISO9660RRIPPN_LEN;
            pPN->Hdr.bVersion   = ISO9660RRIPPN_VER;
            pPN->Major.be       = RT_H2BE_U32((uint32_t)RTDEV_MAJOR(pName->Device));
            pPN->Major.le       = RT_H2LE_U32((uint32_t)RTDEV_MAJOR(pName->Device));
            pPN->Minor.be       = RT_H2BE_U32((uint32_t)RTDEV_MINOR(pName->Device));
            pPN->Minor.le       = RT_H2LE_U32((uint32_t)RTDEV_MINOR(pName->Device));
            cbSys -= sizeof(*pPN);
            pbSys += sizeof(*pPN);
        }

        if (pName->fRockEntries & ISO9660RRIP_RR_F_NM)
        {
            size_t      cchSrc = pName->cchRockRidgeNm;
            const char *pszSrc = pName->pszRockRidgeNm;
            for (;;)
            {
                size_t         cchThis = RT_MIN(cchSrc, ISO9660RRIPNM_MAX_NAME_LEN);
                PISO9660RRIPNM pNM     = (PISO9660RRIPNM)pbSys;
                Assert(cbSys >= RT_UOFFSETOF_DYN(ISO9660RRIPNM, achName[cchThis]));
                pNM->Hdr.bSig1      = ISO9660RRIPNM_SIG1;
                pNM->Hdr.bSig2      = ISO9660RRIPNM_SIG2;
                pNM->Hdr.cbEntry    = (uint8_t)(RT_UOFFSETOF(ISO9660RRIPNM, achName) + cchThis);
                pNM->Hdr.bVersion   = ISO9660RRIPNM_VER;
                pNM->fFlags         = cchThis == cchSrc ? 0 : ISO9660RRIP_NM_F_CONTINUE;
                /** @todo r=bird: This only works when not using the spill file. The spill
                 *        file entry will be shared between the original and all the '.' and
                 *        '..' entries.  FreeBSD gets confused by this w/o the
                 *        ISO9660RRIP_NM_F_CURRENT and ISO9660RRIP_NM_F_PARENT flags. */
                if (enmDirType == RTFSISOMAKERDIRTYPE_CURRENT)
                    pNM->fFlags    |= ISO9660RRIP_NM_F_CURRENT;
                else if (enmDirType == RTFSISOMAKERDIRTYPE_PARENT)
                    pNM->fFlags    |= ISO9660RRIP_NM_F_PARENT;
                memcpy(&pNM->achName[0], pszSrc, cchThis);
                pbSys  += RT_UOFFSETOF(ISO9660RRIPNM, achName) + cchThis;
                cbSys  -= RT_UOFFSETOF(ISO9660RRIPNM, achName) + cchThis;
                cchSrc -= cchThis;
                if (!cchSrc)
                    break;
            }
        }

        if (pName->fRockEntries & ISO9660RRIP_RR_F_SL)
        {
            AssertReturnVoid(pName->pObj->enmType == RTFSISOMAKEROBJTYPE_SYMLINK);
            PCRTFSISOMAKERSYMLINK pSymlink = (PCRTFSISOMAKERSYMLINK)pName->pObj;

            ssize_t cbSlRockRidge = rtFsIsoMakerOutFile_RockRidgeGenSL(pSymlink->szTarget, pbSys, cbSys);
            AssertReturnVoid(cbSlRockRidge > 0);
            Assert(cbSys >= (size_t)cbSlRockRidge);
            pbSys += (size_t)cbSlRockRidge;
            cbSys -= (size_t)cbSlRockRidge;
        }
    }

    /* finally, zero padding. */
    if (cbSys & 1)
    {
        *pbSys++ = '\0';
        cbSys--;
    }

    Assert(!fInSpill ? cbSys == 0 : cbSys < _2G);
}




/**
 * Reads one or more sectors from a rock ridge spill file.
 *
 * @returns IPRT status code.
 * @param   pThis       The ISO maker output file instance.  We use the
 *                      directory pointer hints and child index hints
 * @param   pIsoMaker   The ISO maker.
 * @param   pFile       The rock ridge spill file.
 * @param   offInFile   The offset into the spill file.  This is sector aligned.
 * @param   pbBuf       The output buffer.
 * @param   cbToRead    The number of bytes to tread.  This is sector aligned.
 */
static int rtFsIsoMakerOutFile_RockRidgeSpillReadSectors(PRTFSISOMAKEROUTPUTFILE pThis, PRTFSISOMAKERINT pIsoMaker,
                                                         PRTFSISOMAKERFILE pFile, uint32_t offInFile, uint8_t *pbBuf,
                                                         size_t cbToRead)
{
    /*
     * We're only working multiple of ISO 9660 sectors.
     *
     * The spill of one directory record will always fit entirely within a
     * sector, we make sure about that during finalization.  There may be
     * zero padding between spill data sequences, especially on the sector
     * boundrary.
     */
    Assert((offInFile & ISO9660_SECTOR_OFFSET_MASK) == 0);
    Assert((cbToRead  & ISO9660_SECTOR_OFFSET_MASK) == 0);
    Assert(cbToRead  >= ISO9660_SECTOR_SIZE);

    /*
     * We generate a sector at a time.
     *
     * So, we start by locating the first directory/child in the block offInFile
     * is pointing to.
     */
    PRTFSISOMAKERFINALIZEDDIRS  pFinalizedDirs;
    PRTFSISOMAKERNAMEDIR       *ppDirHint;
    uint32_t                   *pidxChildHint;
    if (pFile->u.pRockSpillNamespace->fNamespace & RTFSISOMAKER_NAMESPACE_ISO_9660)
    {
        pFinalizedDirs = &pIsoMaker->PrimaryIsoDirs;
        ppDirHint      = &pThis->pDirHintPrimaryIso;
        pidxChildHint  = &pThis->iChildPrimaryIso;
    }
    else
    {
        pFinalizedDirs = &pIsoMaker->JolietDirs;
        ppDirHint      = &pThis->pDirHintJoliet;
        pidxChildHint  = &pThis->iChildJoliet;
    }

    /* Special case: '.' record in root dir */
    uint32_t             idxChild  = *pidxChildHint;
    PRTFSISOMAKERNAMEDIR pDir      = *ppDirHint;
    if (   offInFile == 0
        && (pDir = RTListGetFirst(&pFinalizedDirs->FinalizedDirs, RTFSISOMAKERNAMEDIR, FinalizedEntry)) != NULL
        && pDir->pName->cbRockSpill > 0)
    {
        AssertReturn(pDir, VERR_ISOMK_IPE_RR_READ);
        AssertReturn(pDir->pName->offRockSpill == 0, VERR_ISOMK_IPE_RR_READ);
        idxChild = 0;
    }
    else
    {
        /* Establish where to start searching from. */
        if (  !pDir
            || idxChild >= pDir->cChildren
            || pDir->papChildren[idxChild]->cbRockSpill == 0)
        {
            idxChild = 0;
            pDir = RTListGetFirst(&pFinalizedDirs->FinalizedDirs, RTFSISOMAKERNAMEDIR, FinalizedEntry);
            AssertReturn(pDir, VERR_ISOMK_IPE_RR_READ);
        }

        if (pDir->papChildren[idxChild]->offRockSpill == offInFile)
        { /* hit, no need to search */ }
        else if (pDir->papChildren[idxChild]->offRockSpill < offInFile)
        {
            /* search forwards */
            for (;;)
            {
                idxChild++;
                while (   idxChild < pDir->cChildren
                       && (   pDir->papChildren[idxChild]->offRockSpill < offInFile
                           || pDir->papChildren[idxChild]->cbRockSpill  == 0) )
                    idxChild++;
                if (idxChild < pDir->cChildren)
                    break;
                pDir = RTListGetNext(&pFinalizedDirs->FinalizedDirs, pDir, RTFSISOMAKERNAMEDIR, FinalizedEntry);
                AssertReturn(pDir, VERR_ISOMK_IPE_RR_READ);
            }
            Assert(pDir->papChildren[idxChild]->offRockSpill == offInFile);
        }
        else
        {
            /* search backwards (no root dir concerns here) */
            for (;;)
            {
                while (   idxChild > 0
                       && (   pDir->papChildren[idxChild - 1]->offRockSpill >= offInFile
                           || pDir->papChildren[idxChild - 1]->cbRockSpill  == 0) )
                    idxChild--;
                if (pDir->papChildren[idxChild]->offRockSpill == offInFile)
                    break;
                pDir = RTListGetPrev(&pFinalizedDirs->FinalizedDirs, pDir, RTFSISOMAKERNAMEDIR, FinalizedEntry);
                AssertReturn(pDir, VERR_ISOMK_IPE_RR_READ);
            }
            Assert(pDir->papChildren[idxChild]->offRockSpill == offInFile);
        }
    }

    /*
     * Produce data.
     */
    while (cbToRead > 0)
    {
        PRTFSISOMAKERNAME pChild;
        if (   offInFile > 0
            || pDir->pName->cbRockSpill == 0
            || pDir->pName->pParent     != NULL)
        {
            pChild = pDir->papChildren[idxChild];
            AssertReturn(pChild->offRockSpill == offInFile, VERR_ISOMK_IPE_RR_READ);
            AssertReturn(pChild->cbRockSpill > 0, VERR_ISOMK_IPE_RR_READ);
            idxChild++;
        }
        else
        {   /* root dir special case. */
            pChild = pDir->pName;
            Assert(idxChild == 0);
            Assert(pChild->pParent == NULL);
        }

        AssertReturn(cbToRead >= pChild->cbRockSpill, VERR_ISOMK_IPE_RR_READ);
        /** @todo r=bird: using RTFSISOMAKERDIRTYPE_OTHER is correct as we don't seem to
         *        have separate name entries for '.' and '..'.  However it means that if
         *        any directory ends up in the spill file we'll end up with the wrong
         *        data for the '.' and '..' entries. [RR NM ./..] */
        rtFsIosMakerOutFile_GenerateRockRidge(pDir->pName, pbBuf, cbToRead, true /*fInSpill*/, RTFSISOMAKERDIRTYPE_OTHER);
        cbToRead  -= pChild->cbRockSpill;
        pbBuf     += pChild->cbRockSpill;
        offInFile += pChild->cbRockSpill;

        /* Advance to the next name, if any. */
        uint32_t offNext = UINT32_MAX;
        do
        {
            while (idxChild < pDir->cChildren)
            {
                pChild = pDir->papChildren[idxChild];
                if (pChild->cbRockSpill == 0)
                    Assert(pChild->offRockSpill == UINT32_MAX);
                else
                {
                    offNext = pChild->offRockSpill;
                    AssertReturn(offNext >= offInFile, VERR_ISOMK_IPE_RR_READ);
                    AssertReturn(offNext < pFile->cbData, VERR_ISOMK_IPE_RR_READ);
                    break;
                }
                idxChild++;
            }
            if (offNext != UINT32_MAX)
                break;
            pDir     = RTListGetNext(&pFinalizedDirs->FinalizedDirs, pDir, RTFSISOMAKERNAMEDIR, FinalizedEntry);
            idxChild = 0;
        } while (pDir != NULL);

        if (offNext != UINT32_MAX)
        {
            uint32_t cbToZero = offNext - offInFile;
            if (cbToRead > cbToZero)
                RT_BZERO(pbBuf, cbToZero);
            else
            {
                RT_BZERO(pbBuf, cbToRead);
                *ppDirHint     = pDir;
                *pidxChildHint = idxChild;
                break;
            }
            cbToRead  -= cbToZero;
            pbBuf     += cbToZero;
            offInFile += cbToZero;
        }
        else
        {
            RT_BZERO(pbBuf, cbToRead);
            *ppDirHint     = NULL;
            *pidxChildHint = UINT32_MAX;
            break;
        }
    }

    return VINF_SUCCESS;
}


/**
 * Deals with reads that aren't an exact multiple of sectors.
 *
 * @returns IPRT status code.
 * @param   pThis       The ISO maker output file instance.  We use the
 *                      directory pointer hints and child index hints
 * @param   pIsoMaker   The ISO maker.
 * @param   pFile       The rock ridge spill file.
 * @param   offInFile   The offset into the spill file.
 * @param   pbBuf       The output buffer.
 * @param   cbToRead    The number of bytes to tread.
 */
static int rtFsIsoMakerOutFile_RockRidgeSpillReadUnaligned(PRTFSISOMAKEROUTPUTFILE pThis, PRTFSISOMAKERINT pIsoMaker,
                                                           PRTFSISOMAKERFILE pFile, uint32_t offInFile, uint8_t *pbBuf,
                                                           uint32_t cbToRead)
{
    for (;;)
    {
        /*
         * Deal with unnaligned file offsets and sub-sector sized reads.
         */
        if (   (offInFile & ISO9660_SECTOR_OFFSET_MASK)
            || cbToRead < ISO9660_SECTOR_SIZE)
        {
            uint8_t abSectorBuf[ISO9660_SECTOR_SIZE];
            int rc = rtFsIsoMakerOutFile_RockRidgeSpillReadSectors(pThis, pIsoMaker, pFile,
                                                                   offInFile & ~(uint32_t)ISO9660_SECTOR_OFFSET_MASK,
                                                                   abSectorBuf, sizeof(abSectorBuf));
            if (RT_FAILURE(rc))
                return rc;
            uint32_t offSrcBuf = (size_t)offInFile & (size_t)ISO9660_SECTOR_OFFSET_MASK;
            uint32_t cbToCopy  = RT_MIN(ISO9660_SECTOR_SIZE - offSrcBuf, cbToRead);
            memcpy(pbBuf, &abSectorBuf[offSrcBuf], cbToCopy);
            if (cbToCopy >= cbToRead)
                return VINF_SUCCESS;
            cbToRead  -= cbToCopy;
            offInFile += cbToCopy;
            pbBuf     += cbToCopy;
        }

        /*
         * The offset is aligned now, so try read some sectors directly into the buffer.
         */
        AssertContinue((offInFile & ISO9660_SECTOR_OFFSET_MASK) == 0);
        if (cbToRead >= ISO9660_SECTOR_SIZE)
        {
            uint32_t cbFullSectors = cbToRead & ~(uint32_t)ISO9660_SECTOR_OFFSET_MASK;
            int rc = rtFsIsoMakerOutFile_RockRidgeSpillReadSectors(pThis, pIsoMaker, pFile, offInFile, pbBuf, cbFullSectors);
            if (RT_FAILURE(rc))
                return rc;
            if (cbFullSectors >= cbToRead)
                return VINF_SUCCESS;
            cbToRead  -= cbFullSectors;
            offInFile += cbFullSectors;
            pbBuf     += cbFullSectors;
        }
    }
}



/**
 * Produces the content of a TRANS.TBL file as a memory file.
 *
 * @returns IPRT status code.
 * @param   pThis       The ISO maker output file instance.  The file is
 *                      returned as pThis->hVfsSrcFile.
 * @param   pFile       The TRANS.TBL file.
 */
static int rtFsIsoMakerOutFile_ProduceTransTbl(PRTFSISOMAKEROUTPUTFILE pThis, PRTFSISOMAKERFILE pFile)
{
    /*
     * Create memory file instance.
     */
    RTVFSFILE hVfsFile;
    int rc = RTVfsMemFileCreate(NIL_RTVFSIOSTREAM, pFile->cbData, &hVfsFile);
    AssertRCReturn(rc, rc);

    /*
     * Produce the file content.
     */
    PRTFSISOMAKERNAME *ppChild = pFile->u.pTransTblDir->pDir->papChildren;
    uint32_t           cLeft   = pFile->u.pTransTblDir->pDir->cChildren;
    while (cLeft-- > 0)
    {
        PRTFSISOMAKERNAME pChild = *ppChild++;
        if (pChild->cchTransNm)
        {
            /** @todo TRANS.TBL codeset, currently using UTF-8 which is probably not it.
             *        However, nobody uses this stuff any more, so who cares. */
            char   szEntry[RTFSISOMAKER_MAX_NAME_BUF * 2 + 128];
            size_t cchEntry = RTStrPrintf(szEntry, sizeof(szEntry), "%c %-*s\t%s\n", pChild->pDir ? 'D' : 'F',
                                          RTFSISOMAKER_TRANS_TBL_LEFT_PAD, pChild->szName, pChild->pszTransNm);
            rc = RTVfsFileWrite(hVfsFile, szEntry, cchEntry, NULL);
            if (RT_FAILURE(rc))
            {
                RTVfsFileRelease(hVfsFile);
                return rc;
            }
        }
    }

    /*
     * Check that the size matches our estimate.
     */
    uint64_t cbResult = 0;
    rc = RTVfsFileQuerySize(hVfsFile, &cbResult);
    if (RT_SUCCESS(rc) && cbResult == pFile->cbData)
    {
        pThis->hVfsSrcFile = hVfsFile;
        return VINF_SUCCESS;
    }

    AssertMsgFailed(("rc=%Rrc, cbResult=%#RX64 cbData=%#RX64\n", rc, cbResult, pFile->cbData));
    RTVfsFileRelease(hVfsFile);
    return VERR_ISOMK_IPE_PRODUCE_TRANS_TBL;
}



/**
 * Reads file data.
 *
 * @returns IPRT status code
 * @param   pThis           The instance data for the VFS file.  We use this to
 *                          keep hints about where we are and we which source
 *                          file we've opened/created.
 * @param   pIsoMaker       The ISO maker instance.
 * @param   offUnsigned     The ISO image byte offset of the requested data.
 * @param   pbBuf           The output buffer.
 * @param   cbBuf           How much to read.
 * @param   pcbDone         Where to return how much was read.
 */
static int rtFsIsoMakerOutFile_ReadFileData(PRTFSISOMAKEROUTPUTFILE pThis, PRTFSISOMAKERINT pIsoMaker, uint64_t offUnsigned,
                                            uint8_t *pbBuf, size_t cbBuf, size_t *pcbDone)
{
    *pcbDone = 0;

    /*
     * Figure out which file.  We keep a hint in the instance.
     */
    uint64_t          offInFile;
    PRTFSISOMAKERFILE pFile = pThis->pFileHint;
    if (!pFile)
    {
        pFile = RTListGetFirst(&pIsoMaker->FinalizedFiles, RTFSISOMAKERFILE, FinalizedEntry);
        AssertReturn(pFile, VERR_ISOMK_IPE_READ_FILE_DATA_1);
    }
    if ((offInFile = offUnsigned - pFile->offData) < RT_ALIGN_64(pFile->cbData, RTFSISOMAKER_SECTOR_SIZE))
    { /* hit */ }
    else if (offUnsigned >= pFile->offData)
    {
        /* Seek forwards. */
        do
        {
            pFile = RTListGetNext(&pIsoMaker->FinalizedFiles, pFile, RTFSISOMAKERFILE, FinalizedEntry);
            AssertReturn(pFile, VERR_ISOMK_IPE_READ_FILE_DATA_2);
        } while ((offInFile = offUnsigned - pFile->offData) >= RT_ALIGN_64(pFile->cbData, RTFSISOMAKER_SECTOR_SIZE));
    }
    else
    {
        /* Seek backwards. */
        do
        {
            pFile = RTListGetPrev(&pIsoMaker->FinalizedFiles, pFile, RTFSISOMAKERFILE, FinalizedEntry);
            AssertReturn(pFile, VERR_ISOMK_IPE_READ_FILE_DATA_3);
        } while ((offInFile = offUnsigned - pFile->offData) >= RT_ALIGN_64(pFile->cbData, RTFSISOMAKER_SECTOR_SIZE));
    }

    /*
     * Update the hint/current file.
     */
    if (pThis->pFileHint != pFile)
    {
        pThis->pFileHint = pFile;
        if (pThis->hVfsSrcFile != NIL_RTVFSFILE)
        {
            RTVfsFileRelease(pThis->hVfsSrcFile);
            pThis->hVfsSrcFile = NIL_RTVFSFILE;
        }
    }

    /*
     * Produce data bits according to the source type.
     */
    if (offInFile < pFile->cbData)
    {
        int    rc;
        size_t cbToRead = RT_MIN(cbBuf, pFile->cbData - offInFile);

        switch (pFile->enmSrcType)
        {
            case RTFSISOMAKERSRCTYPE_PATH:
                if (pThis->hVfsSrcFile == NIL_RTVFSFILE)
                {
                    rc = RTVfsChainOpenFile(pFile->u.pszSrcPath, RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
                                            &pThis->hVfsSrcFile, NULL, NULL);
                    AssertMsgRCReturn(rc, ("%s -> %Rrc\n", pFile->u.pszSrcPath, rc), rc);
                }
                rc = RTVfsFileReadAt(pThis->hVfsSrcFile, offInFile, pbBuf, cbToRead, NULL);
                AssertRC(rc);
                break;

            case RTFSISOMAKERSRCTYPE_VFS_FILE:
                rc = RTVfsFileReadAt(pFile->u.hVfsFile, offInFile, pbBuf, cbToRead, NULL);
                AssertRC(rc);
                break;

            case RTFSISOMAKERSRCTYPE_COMMON:
                rc = RTVfsFileReadAt(pIsoMaker->paCommonSources[pFile->u.Common.idxSrc],
                                     pFile->u.Common.offData + offInFile, pbBuf, cbToRead, NULL);
                AssertRC(rc);
                break;

            case RTFSISOMAKERSRCTYPE_TRANS_TBL:
                if (pThis->hVfsSrcFile == NIL_RTVFSFILE)
                {
                    rc = rtFsIsoMakerOutFile_ProduceTransTbl(pThis, pFile);
                    AssertRCReturn(rc, rc);
                }
                rc = RTVfsFileReadAt(pThis->hVfsSrcFile, offInFile, pbBuf, cbToRead, NULL);
                AssertRC(rc);
                break;

            case RTFSISOMAKERSRCTYPE_RR_SPILL:
                Assert(pFile->cbData < UINT32_MAX);
                if (   !(offInFile & ISO9660_SECTOR_OFFSET_MASK)
                    && !(cbToRead & ISO9660_SECTOR_OFFSET_MASK)
                    && cbToRead > 0)
                    rc = rtFsIsoMakerOutFile_RockRidgeSpillReadSectors(pThis, pIsoMaker, pFile, (uint32_t)offInFile,
                                                                       pbBuf, (uint32_t)cbToRead);
                else
                    rc = rtFsIsoMakerOutFile_RockRidgeSpillReadUnaligned(pThis, pIsoMaker, pFile, (uint32_t)offInFile,
                                                                         pbBuf, (uint32_t)cbToRead);
                break;

            default:
                AssertFailedReturn(VERR_IPE_NOT_REACHED_DEFAULT_CASE);
        }
        if (RT_FAILURE(rc))
            return rc;
        *pcbDone = cbToRead;

        /*
         * Do boot info table patching.
         */
        if (   pFile->pBootInfoTable
            && offInFile            < 64
            && offInFile + cbToRead > 8)
        {
            size_t offInBuf = offInFile <  8 ? 8 - (size_t)offInFile : 0;
            size_t offInTab = offInFile <= 8 ? 0 : (size_t)offInFile - 8;
            size_t cbToCopy = RT_MIN(sizeof(*pFile->pBootInfoTable) - offInTab, cbToRead - offInBuf);
            memcpy(&pbBuf[offInBuf], (uint8_t *)pFile->pBootInfoTable + offInTab, cbToCopy);
        }

        /*
         * Check if we're into the zero padding at the end of the file now.
         */
        if (   cbToRead < cbBuf
            && (pFile->cbData & RTFSISOMAKER_SECTOR_OFFSET_MASK)
            && offInFile + cbToRead == pFile->cbData)
        {
            cbBuf -= cbToRead;
            pbBuf += cbToRead;
            size_t cbZeros = RT_MIN(cbBuf, RTFSISOMAKER_SECTOR_SIZE - (pFile->cbData & RTFSISOMAKER_SECTOR_OFFSET_MASK));
            memset(pbBuf, 0, cbZeros);
            *pcbDone += cbZeros;
        }
    }
    else
    {
        size_t cbZeros = RT_MIN(cbBuf, RT_ALIGN_64(pFile->cbData, RTFSISOMAKER_SECTOR_SIZE) - offInFile);
        memset(pbBuf, 0, cbZeros);
        *pcbDone = cbZeros;
    }
    return VINF_SUCCESS;
}


/**
 * Generates ISO-9660 path table record into the specified buffer.
 *
 * @returns Number of bytes copied into the buffer.
 * @param   pName       The directory namespace node.
 * @param   fUnicode    Set if the name should be translated to big endian
 *                      UTF-16 / UCS-2, i.e. we're in the joliet namespace.
 * @param   pbBuf       The buffer.  This is large enough to hold the path
 *                      record (use RTFSISOMAKER_CALC_PATHREC_SIZE) and a zero
 *                      RTUTF16 terminator if @a fUnicode is true.
 */
static uint32_t rtFsIsoMakerOutFile_GeneratePathRec(PRTFSISOMAKERNAME pName, bool fUnicode, bool fLittleEndian, uint8_t *pbBuf)
{
    PISO9660PATHREC pPathRec = (PISO9660PATHREC)pbBuf;
    pPathRec->cbDirId   = pName->cbNameInDirRec;
    pPathRec->cbExtAttr = 0;
    if (fLittleEndian)
    {
        pPathRec->offExtent   = RT_H2LE_U32(pName->pDir->offDir / RTFSISOMAKER_SECTOR_SIZE);
        pPathRec->idParentRec = RT_H2LE_U16(pName->pParent ? pName->pParent->pDir->idPathTable : 1);
    }
    else
    {
        pPathRec->offExtent   = RT_H2BE_U32(pName->pDir->offDir / RTFSISOMAKER_SECTOR_SIZE);
        pPathRec->idParentRec = RT_H2BE_U16(pName->pParent ? pName->pParent->pDir->idPathTable : 1);
    }
    if (!fUnicode)
    {
        memcpy(&pPathRec->achDirId[0], pName->szName, pName->cbNameInDirRec);
        if (pName->cbNameInDirRec & 1)
            pPathRec->achDirId[pName->cbNameInDirRec] = '\0';
    }
    else
    {
        /* Caller made sure there is space for a zero terminator character. */
        PRTUTF16 pwszTmp   = (PRTUTF16)&pPathRec->achDirId[0];
        size_t   cwcResult = 0;
        int rc = RTStrToUtf16BigEx(pName->szName, RTSTR_MAX, &pwszTmp, pName->cbNameInDirRec / sizeof(RTUTF16) + 1, &cwcResult);
        AssertRC(rc);
        Assert(   cwcResult * sizeof(RTUTF16) == pName->cbNameInDirRec
               || (!pName->pParent && cwcResult == 0 && pName->cbNameInDirRec == 1) );

    }
    return RTFSISOMAKER_CALC_PATHREC_SIZE(pName->cbNameInDirRec);
}


/**
 * Deals with situations where the destination buffer doesn't cover the whole
 * path table record.
 *
 * @returns Number of bytes copied into the buffer.
 * @param   pName       The directory namespace node.
 * @param   fUnicode    Set if the name should be translated to big endian
 *                      UTF-16 / UCS-2, i.e. we're in the joliet namespace.
 * @param   offInRec    The offset into the path table record.
 * @param   pbBuf       The buffer.
 * @param   cbBuf       The buffer size.
 */
static uint32_t rtFsIsoMakerOutFile_GeneratePathRecPartial(PRTFSISOMAKERNAME pName, bool fUnicode, bool fLittleEndian,
                                                           uint32_t offInRec, uint8_t *pbBuf, size_t cbBuf)
{
    uint8_t abTmpRec[256];
    size_t cbToCopy = rtFsIsoMakerOutFile_GeneratePathRec(pName, fUnicode, fLittleEndian, abTmpRec);
    cbToCopy = RT_MIN(cbBuf, cbToCopy - offInRec);
    memcpy(pbBuf, &abTmpRec[offInRec], cbToCopy);
    return (uint32_t)cbToCopy;
}


/**
 * Generate path table records.
 *
 * This will generate record up to the end of the table.  However, it will not
 * supply the zero padding in the last sector, the caller is expected to take
 * care of that.
 *
 * @returns Number of bytes written to the buffer.
 * @param   ppDirHint       Pointer to the directory hint for the namespace.
 * @param   pFinalizedDirs  The finalized directory data for the namespace.
 * @param   fUnicode        Set if the name should be translated to big endian
 *                          UTF-16 / UCS-2, i.e. we're in the joliet namespace.
 * @param   fLittleEndian   Set if we're generating little endian records, clear
 *                          if big endian records.
 * @param   offInTable      Offset into the path table.
 * @param   pbBuf           The output buffer.
 * @param   cbBuf           The buffer size.
 */
static size_t rtFsIsoMakerOutFile_ReadPathTable(PRTFSISOMAKERNAMEDIR *ppDirHint, PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs,
                                                bool fUnicode, bool fLittleEndian, uint32_t offInTable,
                                                uint8_t *pbBuf, size_t cbBuf)
{
    /*
     * Figure out which directory to start with.  We keep a hint in the instance.
     */
    PRTFSISOMAKERNAMEDIR pDir = *ppDirHint;
    if (!pDir)
    {
        pDir = RTListGetFirst(&pFinalizedDirs->FinalizedDirs, RTFSISOMAKERNAMEDIR, FinalizedEntry);
        AssertReturnStmt(pDir, *pbBuf = 0xff, 1);
    }
    if (offInTable - pDir->offPathTable < RTFSISOMAKER_CALC_PATHREC_SIZE(pDir->pName->cbNameInDirRec))
    { /* hit */ }
    /* Seek forwards: */
    else if (offInTable > pDir->offPathTable)
        do
        {
            pDir = RTListGetNext(&pFinalizedDirs->FinalizedDirs, pDir, RTFSISOMAKERNAMEDIR, FinalizedEntry);
            AssertReturnStmt(pDir, *pbBuf = 0xff, 1);
        } while (offInTable - pDir->offPathTable >= RTFSISOMAKER_CALC_PATHREC_SIZE(pDir->pName->cbNameInDirRec));
    /* Back to the start: */
    else if (offInTable == 0)
    {
        pDir = RTListGetFirst(&pFinalizedDirs->FinalizedDirs, RTFSISOMAKERNAMEDIR, FinalizedEntry);
        AssertReturnStmt(pDir, *pbBuf = 0xff, 1);
    }
    /* Seek backwards: */
    else
        do
        {
            pDir = RTListGetPrev(&pFinalizedDirs->FinalizedDirs, pDir, RTFSISOMAKERNAMEDIR, FinalizedEntry);
            AssertReturnStmt(pDir, *pbBuf = 0xff, 1);
        } while (offInTable - pDir->offPathTable >= RTFSISOMAKER_CALC_PATHREC_SIZE(pDir->pName->cbNameInDirRec));

    /*
     * Generate content.
     */
    size_t cbDone = 0;
    while (   cbBuf > 0
           && pDir)
    {
        PRTFSISOMAKERNAME pName = pDir->pName;
        uint8_t           cbRec = RTFSISOMAKER_CALC_PATHREC_SIZE(pName->cbNameInDirRec);
        uint32_t          cbCopied;
        if (   offInTable == pDir->offPathTable
            && cbBuf      >= cbRec + fUnicode * 2U)
            cbCopied = rtFsIsoMakerOutFile_GeneratePathRec(pName, fUnicode, fLittleEndian, pbBuf);
        else
            cbCopied = rtFsIsoMakerOutFile_GeneratePathRecPartial(pName, fUnicode, fLittleEndian,
                                                                  offInTable - pDir->offPathTable, pbBuf, cbBuf);
        cbDone     += cbCopied;
        offInTable += cbCopied;
        pbBuf      += cbCopied;
        cbBuf      -= cbCopied;
        pDir = RTListGetNext(&pFinalizedDirs->FinalizedDirs, pDir, RTFSISOMAKERNAMEDIR, FinalizedEntry);
    }

    /*
     * Update the hint.
     */
    *ppDirHint = pDir;

    return cbDone;
}


/**
 * Generates ISO-9660 directory record into the specified buffer.
 *
 * The caller must deal with multi-extent copying and end of sector zero
 * padding.
 *
 * @returns Number of bytes copied into the buffer (pName->cbDirRec).
 * @param   pName           The namespace node.
 * @param   fUnicode        Set if the name should be translated to big endian
 *                          UTF-16BE / UCS-2BE, i.e. we're in the joliet namespace.
 * @param   pbBuf           The buffer.  This is at least pName->cbDirRec bytes
 *                          big (i.e. at most 256 bytes).
 * @param   pFinalizedDirs  The finalized directory data for the namespace.
 * @param   enmDirType      The kind of directory entry this is.
 */
static uint32_t rtFsIsoMakerOutFile_GenerateDirRec(PRTFSISOMAKERNAME pName, bool fUnicode, uint8_t *pbBuf,
                                                   PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs, RTFSISOMAKERDIRTYPE enmDirType)
{
    /*
     * Emit a standard ISO-9660 directory record.
     */
    PISO9660DIRREC          pDirRec = (PISO9660DIRREC)pbBuf;
    PCRTFSISOMAKEROBJ       pObj    = pName->pObj;
    PCRTFSISOMAKERNAMEDIR   pDir    = pName->pDir;
    if (pDir)
    {
        pDirRec->offExtent.be       = RT_H2BE_U32(pDir->offDir / RTFSISOMAKER_SECTOR_SIZE);
        pDirRec->offExtent.le       = RT_H2LE_U32(pDir->offDir / RTFSISOMAKER_SECTOR_SIZE);
        pDirRec->cbData.be          = RT_H2BE_U32(pDir->cbDir);
        pDirRec->cbData.le          = RT_H2LE_U32(pDir->cbDir);
        pDirRec->fFileFlags         = ISO9660_FILE_FLAGS_DIRECTORY;
    }
    else if (pObj->enmType == RTFSISOMAKEROBJTYPE_FILE)
    {
        PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pObj;
        pDirRec->offExtent.be       = RT_H2BE_U32(pFile->offData / RTFSISOMAKER_SECTOR_SIZE);
        pDirRec->offExtent.le       = RT_H2LE_U32(pFile->offData / RTFSISOMAKER_SECTOR_SIZE);
        pDirRec->cbData.be          = RT_H2BE_U32(pFile->cbData);
        pDirRec->cbData.le          = RT_H2LE_U32(pFile->cbData);
        pDirRec->fFileFlags         = 0;
    }
    else
    {
        pDirRec->offExtent.be       = 0;
        pDirRec->offExtent.le       = 0;
        pDirRec->cbData.be          = 0;
        pDirRec->cbData.le          = 0;
        pDirRec->fFileFlags         = 0;
    }
    rtFsIsoMakerTimespecToIso9660RecTimestamp(&pObj->BirthTime, &pDirRec->RecTime);

    pDirRec->cbDirRec               = pName->cbDirRec;
    pDirRec->cExtAttrBlocks         = 0;
    pDirRec->bFileUnitSize          = 0;
    pDirRec->bInterleaveGapSize     = 0;
    pDirRec->VolumeSeqNo.be         = RT_H2BE_U16_C(1);
    pDirRec->VolumeSeqNo.le         = RT_H2LE_U16_C(1);
    pDirRec->bFileIdLength          = pName->cbNameInDirRec;

    if (!fUnicode)
    {
        memcpy(&pDirRec->achFileId[0], pName->szName, pName->cbNameInDirRec);
        if (!(pName->cbNameInDirRec & 1))
            pDirRec->achFileId[pName->cbNameInDirRec] = '\0';
    }
    else
    {
        /* Convert to big endian UTF-16.  We're using a separate buffer here
           because of zero terminator (none in pDirRec) and misalignment. */
        RTUTF16  wszTmp[128];
        PRTUTF16 pwszTmp = &wszTmp[0];
        size_t   cwcResult = 0;
        int rc = RTStrToUtf16BigEx(pName->szName, RTSTR_MAX, &pwszTmp, RT_ELEMENTS(wszTmp), &cwcResult);
        AssertRC(rc);
        Assert(   cwcResult * sizeof(RTUTF16) == pName->cbNameInDirRec
               || (!pName->pParent && cwcResult == 0 && pName->cbNameInDirRec == 1) );
        memcpy(&pDirRec->achFileId[0], pwszTmp, pName->cbNameInDirRec);
        pDirRec->achFileId[pName->cbNameInDirRec] = '\0';
    }

    /*
     * Rock ridge fields if enabled.
     */
    if (pName->cbRockInDirRec > 0)
    {
        uint8_t *pbSys = (uint8_t *)&pDirRec->achFileId[pName->cbNameInDirRec + !(pName->cbNameInDirRec & 1)];
        size_t   cbSys = &pbBuf[pName->cbDirRec] - pbSys;
        Assert(cbSys >= pName->cbRockInDirRec);
        if (cbSys > pName->cbRockInDirRec)
            RT_BZERO(&pbSys[pName->cbRockInDirRec], cbSys - pName->cbRockInDirRec);
        if (pName->cbRockSpill == 0)
            rtFsIosMakerOutFile_GenerateRockRidge(pName, pbSys, cbSys, false /*fInSpill*/, enmDirType);
        else
        {
            /* Maybe emit SP and RR entry, before emitting the CE entry. */
            if (pName->pParent == NULL)
            {
                PISO9660SUSPSP pSP = (PISO9660SUSPSP)pbSys;
                pSP->Hdr.bSig1     = ISO9660SUSPSP_SIG1;
                pSP->Hdr.bSig2     = ISO9660SUSPSP_SIG2;
                pSP->Hdr.cbEntry   = ISO9660SUSPSP_LEN;
                pSP->Hdr.bVersion  = ISO9660SUSPSP_VER;
                pSP->bCheck1       = ISO9660SUSPSP_CHECK1;
                pSP->bCheck2       = ISO9660SUSPSP_CHECK2;
                pSP->cbSkip        = 0;
                pbSys += sizeof(*pSP);
                cbSys -= sizeof(*pSP);
            }
            if (pName->fRockNeedRRInDirRec)
            {
                PISO9660RRIPRR pRR = (PISO9660RRIPRR)pbSys;
                pRR->Hdr.bSig1     = ISO9660RRIPRR_SIG1;
                pRR->Hdr.bSig2     = ISO9660RRIPRR_SIG2;
                pRR->Hdr.cbEntry   = ISO9660RRIPRR_LEN;
                pRR->Hdr.bVersion  = ISO9660RRIPRR_VER;
                pRR->fFlags        = pName->fRockEntries;
                pbSys += sizeof(*pRR);
                cbSys -= sizeof(*pRR);
            }
            PISO9660SUSPCE pCE = (PISO9660SUSPCE)pbSys;
            pCE->Hdr.bSig1     = ISO9660SUSPCE_SIG1;
            pCE->Hdr.bSig2     = ISO9660SUSPCE_SIG2;
            pCE->Hdr.cbEntry   = ISO9660SUSPCE_LEN;
            pCE->Hdr.bVersion  = ISO9660SUSPCE_VER;
            uint64_t offData = pFinalizedDirs->pRRSpillFile->offData + pName->offRockSpill;
            pCE->offBlock.be   = RT_H2BE_U32((uint32_t)(offData / ISO9660_SECTOR_SIZE));
            pCE->offBlock.le   = RT_H2LE_U32((uint32_t)(offData / ISO9660_SECTOR_SIZE));
            pCE->offData.be    = RT_H2BE_U32((uint32_t)(offData & ISO9660_SECTOR_OFFSET_MASK));
            pCE->offData.le    = RT_H2LE_U32((uint32_t)(offData & ISO9660_SECTOR_OFFSET_MASK));
            pCE->cbData.be     = RT_H2BE_U32((uint32_t)pName->cbRockSpill);
            pCE->cbData.le     = RT_H2LE_U32((uint32_t)pName->cbRockSpill);
            Assert(cbSys >= sizeof(*pCE));
        }
    }

    return pName->cbDirRec;
}


/**
 * Generates ISO-9660 directory records into the specified buffer.
 *
 * @returns Number of bytes copied into the buffer.
 * @param   pName           The namespace node.
 * @param   fUnicode        Set if the name should be translated to big endian
 *                          UTF-16BE / UCS-2BE, i.e. we're in the joliet namespace.
 * @param   pbBuf           The buffer.  This is at least pName->cbDirRecTotal
 *                          bytes big.
 * @param   pFinalizedDirs  The finalized directory data for the namespace.
 */
static uint32_t rtFsIsoMakerOutFile_GenerateDirRecDirect(PRTFSISOMAKERNAME pName, bool fUnicode, uint8_t *pbBuf,
                                                         PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs)
{
    /*
     * Normally there is just a single record without any zero padding.
     */
    uint32_t cbReturn = rtFsIsoMakerOutFile_GenerateDirRec(pName, fUnicode, pbBuf, pFinalizedDirs, RTFSISOMAKERDIRTYPE_OTHER);
    if (RT_LIKELY(pName->cbDirRecTotal == cbReturn))
        return cbReturn;
    Assert(cbReturn < pName->cbDirRecTotal);

    /*
     * Deal with multiple records.
     */
    if (pName->cDirRecs > 1)
    {
        Assert(pName->pObj->enmType == RTFSISOMAKEROBJTYPE_FILE);
        PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pName->pObj;

        /* Set max size and duplicate the first directory record cDirRecs - 1 times. */
        uint32_t const cbOne   = cbReturn;
        PISO9660DIRREC pDirRec = (PISO9660DIRREC)pbBuf;
        pDirRec->cbData.be   = RT_H2BE_U32_C(RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE);
        pDirRec->cbData.le   = RT_H2LE_U32_C(RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE);
        pDirRec->fFileFlags |= ISO9660_FILE_FLAGS_MULTI_EXTENT;

        PISO9660DIRREC pCurDirRec = pDirRec;
        uint32_t       offExtent  = (uint32_t)(pFile->offData / RTFSISOMAKER_SECTOR_SIZE);
        Assert(offExtent == ISO9660_GET_ENDIAN(&pDirRec->offExtent));
        for (uint32_t iDirRec = 1; iDirRec < pName->cDirRecs; iDirRec++)
        {
            pCurDirRec = (PISO9660DIRREC)memcpy(&pbBuf[cbReturn], pDirRec, cbOne);

            offExtent += RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE / RTFSISOMAKER_SECTOR_SIZE;
            pCurDirRec->offExtent.le = RT_H2LE_U32(offExtent);

            cbReturn += cbOne;
        }
        Assert(cbReturn <= pName->cbDirRecTotal);

        /* Adjust the size in the final record. */
        uint32_t cbDataLast = (uint32_t)(pFile->cbData % RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE);
        pCurDirRec->cbData.be   = RT_H2BE_U32(cbDataLast);
        pCurDirRec->cbData.le   = RT_H2LE_U32(cbDataLast);
        pCurDirRec->fFileFlags &= ~ISO9660_FILE_FLAGS_MULTI_EXTENT;
    }

    /*
     * Do end of sector zero padding.
     */
    if (cbReturn < pName->cbDirRecTotal)
        memset(&pbBuf[cbReturn], 0, (uint32_t)pName->cbDirRecTotal - cbReturn);

    return pName->cbDirRecTotal;
}


/**
 * Deals with situations where the destination buffer doesn't cover the whole
 * directory record.
 *
 * @returns Number of bytes copied into the buffer.
 * @param   pName           The namespace node.
 * @param   fUnicode        Set if the name should be translated to big endian
 *                          UTF-16 / UCS-2, i.e. we're in the joliet namespace.
 * @param   off             The offset into the directory record.
 * @param   pbBuf           The buffer.
 * @param   cbBuf           The buffer size.
 * @param   pFinalizedDirs  The finalized directory data for the namespace.
 */
static uint32_t rtFsIsoMakerOutFile_GenerateDirRecPartial(PRTFSISOMAKERNAME pName, bool fUnicode,
                                                          uint32_t off, uint8_t *pbBuf, size_t cbBuf,
                                                          PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs)
{
    Assert(off < pName->cbDirRecTotal);

    /*
     * This is reasonably simple when there is only one directory record and
     * without any padding.
     */
    uint8_t abTmpBuf[256];
    Assert(pName->cbDirRec <= sizeof(abTmpBuf));
    uint32_t const cbOne = rtFsIsoMakerOutFile_GenerateDirRec(pName, fUnicode, abTmpBuf,
                                                              pFinalizedDirs, RTFSISOMAKERDIRTYPE_OTHER);
    Assert(cbOne == pName->cbDirRec);
    if (cbOne == pName->cbDirRecTotal)
    {
        uint32_t cbToCopy = RT_MIN((uint32_t)cbBuf, cbOne - off);
        memcpy(pbBuf, &abTmpBuf[off], cbToCopy);
        return cbToCopy;
    }
    Assert(cbOne < pName->cbDirRecTotal);

    /*
     * Single record and zero padding?
     */
    uint32_t cbCopied = 0;
    if (pName->cDirRecs == 1)
    {
        /* Anything from the record to copy? */
        if (off < cbOne)
        {
            cbCopied = RT_MIN((uint32_t)cbBuf, cbOne - off);
            memcpy(pbBuf, &abTmpBuf[off], cbCopied);
            pbBuf += cbCopied;
            cbBuf -= cbCopied;
            off   += cbCopied;
        }

        /* Anything from the zero padding? */
        if (off >= cbOne && cbBuf > 0)
        {
            uint32_t cbToZero = RT_MIN((uint32_t)cbBuf, (uint32_t)pName->cbDirRecTotal - off);
            memset(pbBuf, 0, cbToZero);
            cbCopied += cbToZero;
        }
    }
    /*
     * Multi-extent stuff.  Need to modify the cbData member as we copy.
     */
    else
    {
        Assert(pName->pObj->enmType == RTFSISOMAKEROBJTYPE_FILE);
        PRTFSISOMAKERFILE pFile = (PRTFSISOMAKERFILE)pName->pObj;

        /* Max out the size. */
        PISO9660DIRREC pDirRec = (PISO9660DIRREC)abTmpBuf;
        pDirRec->cbData.be   = RT_H2BE_U32_C(RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE);
        pDirRec->cbData.le   = RT_H2LE_U32_C(RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE);
        pDirRec->fFileFlags |= ISO9660_FILE_FLAGS_MULTI_EXTENT;

        /* Copy directory records. */
        uint32_t offDirRec = pName->offDirRec;
        uint32_t offExtent = pFile->offData / RTFSISOMAKER_SECTOR_SIZE;
        for (uint32_t i = 0; i < pName->cDirRecs && cbBuf > 0; i++)
        {
            uint32_t const offInRec = off - offDirRec;
            if (offInRec < cbOne)
            {
                /* Update the record. */
                pDirRec->offExtent.be = RT_H2BE_U32(offExtent);
                pDirRec->offExtent.le = RT_H2LE_U32(offExtent);
                if (i + 1 == pName->cDirRecs)
                {
                    uint32_t cbDataLast = pFile->cbData % RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE;
                    pDirRec->cbData.be   = RT_H2BE_U32(cbDataLast);
                    pDirRec->cbData.le   = RT_H2LE_U32(cbDataLast);
                    pDirRec->fFileFlags &= ~ISO9660_FILE_FLAGS_MULTI_EXTENT;
                }

                /* Copy chunk. */
                uint32_t cbToCopy = RT_MIN((uint32_t)cbBuf, cbOne - offInRec);
                memcpy(pbBuf, &abTmpBuf[offInRec], cbToCopy);
                cbCopied += cbToCopy;
                pbBuf    += cbToCopy;
                cbBuf    -= cbToCopy;
                off      += cbToCopy;
            }

            offDirRec += cbOne;
            offExtent += RTFSISOMAKER_MAX_ISO9660_EXTENT_SIZE / RTFSISOMAKER_SECTOR_SIZE;
        }

        /* Anything from the zero padding? */
        if (off >= offDirRec && cbBuf > 0)
        {
            uint32_t cbToZero = RT_MIN((uint32_t)cbBuf, (uint32_t)pName->cbDirRecTotal - offDirRec);
            memset(pbBuf, 0, cbToZero);
            cbCopied += cbToZero;
        }
    }

    return cbCopied;
}


/**
 * Generate a '.' or '..' directory record.
 *
 * This is the same as rtFsIsoMakerOutFile_GenerateDirRec, but with the filename
 * reduced to 1 byte.
 *
 * @returns Number of bytes copied into the buffer.
 * @param   pName           The directory namespace node.
 * @param   fUnicode        Set if the name should be translated to big endian
 *                          UTF-16 / UCS-2, i.e. we're in the joliet namespace.
 * @param   bDirId          The directory ID (0x00 or 0x01).
 * @param   off             The offset into the directory record.
 * @param   pbBuf           The buffer.
 * @param   cbBuf           The buffer size.
 * @param   pFinalizedDirs  The finalized directory data for the namespace.
 */
static uint32_t rtFsIsoMakerOutFile_GenerateSpecialDirRec(PRTFSISOMAKERNAME pName, bool fUnicode, uint8_t bDirId,
                                                          uint32_t off, uint8_t *pbBuf, size_t cbBuf,
                                                          PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs)
{
    Assert(off < pName->cbDirRec);
    Assert(pName->pDir);

    /* Generate a regular directory record. */
    uint8_t abTmpBuf[256];
    Assert(off < pName->cbDirRec);
    size_t cbToCopy = rtFsIsoMakerOutFile_GenerateDirRec(pName, fUnicode, abTmpBuf, pFinalizedDirs,
                                                         bDirId == 0 ? RTFSISOMAKERDIRTYPE_CURRENT : RTFSISOMAKERDIRTYPE_PARENT);
    Assert(cbToCopy == pName->cbDirRec);

    /** @todo r=bird: This isn't working quite right as the NM record includes the
     *        full directory name. Spill file stuff is shared with the (grand)parent
     *        directory entry. [RR NM ./..] */

    /* Replace the filename part. */
    PISO9660DIRREC pDirRec = (PISO9660DIRREC)abTmpBuf;
    if (pDirRec->bFileIdLength != 1)
    {
        uint8_t offSysUse = pDirRec->bFileIdLength + !(pDirRec->bFileIdLength & 1) + RT_UOFFSETOF(ISO9660DIRREC, achFileId);
        uint8_t cbSysUse  = pDirRec->cbDirRec - offSysUse;
        if (cbSysUse > 0)
            memmove(&pDirRec->achFileId[1], &abTmpBuf[offSysUse], cbSysUse);
        pDirRec->bFileIdLength = 1;
        cbToCopy = RT_UOFFSETOF(ISO9660DIRREC, achFileId) + 1 + cbSysUse;
        pDirRec->cbDirRec = (uint8_t)cbToCopy;
    }
    pDirRec->achFileId[0] = bDirId;

    /* Do the copying. */
    cbToCopy = RT_MIN(cbBuf, cbToCopy - off);
    memcpy(pbBuf, &abTmpBuf[off], cbToCopy);
    return (uint32_t)cbToCopy;
}


/**
 * Read directory records.
 *
 * This locates the directory at @a offUnsigned and generates directory records
 * for it.  Caller must repeat the call to get directory entries for the next
 * directory should there be desire for that.
 *
 * @returns Number of bytes copied into @a pbBuf.
 * @param   ppDirHint       Pointer to the directory hint for the namespace.
 * @param   pIsoMaker       The ISO maker instance.
 * @param   pFinalizedDirs  The finalized directory data for the namespace.
 * @param   fUnicode        Set if the name should be translated to big endian
 *                          UTF-16 / UCS-2, i.e. we're in the joliet namespace.
 * @param   offUnsigned     The ISO image byte offset of the requested data.
 * @param   pbBuf           The output buffer.
 * @param   cbBuf           How much to read.
 */
static size_t rtFsIsoMakerOutFile_ReadDirRecords(PRTFSISOMAKERNAMEDIR *ppDirHint, PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs,
                                                 bool fUnicode, uint64_t offUnsigned, uint8_t *pbBuf, size_t cbBuf)
{
    /*
     * Figure out which directory.  We keep a hint in the instance.
     */
    uint64_t             offInDir64;
    PRTFSISOMAKERNAMEDIR pDir = *ppDirHint;
    if (!pDir)
    {
        pDir = RTListGetFirst(&pFinalizedDirs->FinalizedDirs, RTFSISOMAKERNAMEDIR, FinalizedEntry);
        AssertReturnStmt(pDir, *pbBuf = 0xff, 1);
    }
    if ((offInDir64 = offUnsigned - pDir->offDir) < RT_ALIGN_32(pDir->cbDir, RTFSISOMAKER_SECTOR_SIZE))
    { /* hit */ }
    /* Seek forwards: */
    else if (offUnsigned > pDir->offDir)
        do
        {
            pDir = RTListGetNext(&pFinalizedDirs->FinalizedDirs, pDir, RTFSISOMAKERNAMEDIR, FinalizedEntry);
            AssertReturnStmt(pDir, *pbBuf = 0xff, 1);
        } while ((offInDir64 = offUnsigned - pDir->offDir) >= RT_ALIGN_32(pDir->cbDir, RTFSISOMAKER_SECTOR_SIZE));
    /* Back to the start: */
    else if (pFinalizedDirs->offDirs / RTFSISOMAKER_SECTOR_SIZE == offUnsigned / RTFSISOMAKER_SECTOR_SIZE)
    {
        pDir = RTListGetFirst(&pFinalizedDirs->FinalizedDirs, RTFSISOMAKERNAMEDIR, FinalizedEntry);
        AssertReturnStmt(pDir, *pbBuf = 0xff, 1);
        offInDir64 = offUnsigned - pDir->offDir;
    }
    /* Seek backwards: */
    else
        do
        {
            pDir = RTListGetPrev(&pFinalizedDirs->FinalizedDirs, pDir, RTFSISOMAKERNAMEDIR, FinalizedEntry);
            AssertReturnStmt(pDir, *pbBuf = 0xff, 1);
        } while ((offInDir64 = offUnsigned - pDir->offDir) >= RT_ALIGN_32(pDir->cbDir, RTFSISOMAKER_SECTOR_SIZE));

    /*
     * Update the hint.
     */
    *ppDirHint = pDir;

    /*
     * Generate content.
     */
    size_t cbDone = 0;
    uint32_t offInDir = (uint32_t)offInDir64;
    if (offInDir < pDir->cbDir)
    {
        PRTFSISOMAKERNAME   pDirName      = pDir->pName;
        PRTFSISOMAKERNAME   pParentName   = pDirName->pParent ? pDirName->pParent : pDirName;
        uint32_t            cbSpecialRecs = (uint32_t)pDir->cbDirRec00 + pDir->cbDirRec01;

        /*
         * Special '.' and/or '..' entries requested.
         */
        uint32_t iChild;
        if (offInDir < cbSpecialRecs)
        {
            /* do '.' */
            if (offInDir < pDir->cbDirRec00)
            {
                uint32_t cbCopied = rtFsIsoMakerOutFile_GenerateSpecialDirRec(pDirName, fUnicode, 0, offInDir,
                                                                              pbBuf, cbBuf, pFinalizedDirs);
                cbDone   += cbCopied;
                offInDir += cbCopied;
                pbBuf    += cbCopied;
                cbBuf    -= cbCopied;
            }

            /* do '..' */
            if (cbBuf > 0)
            {
                uint32_t cbCopied = rtFsIsoMakerOutFile_GenerateSpecialDirRec(pParentName, fUnicode, 1,
                                                                              offInDir - pDir->cbDirRec00,
                                                                              pbBuf, cbBuf, pFinalizedDirs);
                cbDone   += cbCopied;
                offInDir += cbCopied;
                pbBuf    += cbCopied;
                cbBuf    -= cbCopied;
            }

            iChild = 0;
        }
        /*
         * Locate the directory entry we should start with.  We can do this
         * using binary searching on offInDir.
         */
        else
        {
            /** @todo binary search   */
            iChild = 0;
            while (iChild < pDir->cChildren)
            {
                PRTFSISOMAKERNAME pChild = pDir->papChildren[iChild];
                if ((offInDir - pChild->offDirRec) < pChild->cbDirRecTotal)
                    break;
                iChild++;
            }
            AssertReturnStmt(iChild < pDir->cChildren, *pbBuf = 0xff, 1);
        }

        /*
         * Normal directory entries.
         */
        while (   cbBuf > 0
               && iChild < pDir->cChildren)
        {
            PRTFSISOMAKERNAME pChild = pDir->papChildren[iChild];
            uint32_t cbCopied;
            if (   offInDir == pChild->offDirRec
                && cbBuf    >= pChild->cbDirRecTotal)
                cbCopied = rtFsIsoMakerOutFile_GenerateDirRecDirect(pChild, fUnicode, pbBuf, pFinalizedDirs);
            else
                cbCopied = rtFsIsoMakerOutFile_GenerateDirRecPartial(pChild, fUnicode, offInDir - pChild->offDirRec,
                                                                     pbBuf, cbBuf, pFinalizedDirs);

            cbDone   += cbCopied;
            offInDir += cbCopied;
            pbBuf    += cbCopied;
            cbBuf    -= cbCopied;
            iChild++;
        }

        /*
         * Check if we're into the zero padding at the end of the directory now.
         */
        if (   cbBuf > 0
            && iChild >= pDir->cChildren)
        {
            size_t cbZeros = RT_MIN(cbBuf, RTFSISOMAKER_SECTOR_SIZE - (pDir->cbDir & RTFSISOMAKER_SECTOR_OFFSET_MASK));
            memset(pbBuf, 0, cbZeros);
            cbDone += cbZeros;
        }
    }
    else
    {
        cbDone = RT_MIN(cbBuf, RT_ALIGN_32(pDir->cbDir, RTFSISOMAKER_SECTOR_SIZE) - offInDir);
        memset(pbBuf, 0, cbDone);
    }

    return cbDone;
}


/**
 * Read directory records or path table records.
 *
 * Will not necessarily fill the entire buffer.  Caller must call again to get
 * more.
 *
 * @returns Number of bytes copied into @a pbBuf.
 * @param   ppDirHint       Pointer to the directory hint for the namespace.
 * @param   pIsoMaker       The ISO maker instance.
 * @param   pNamespace      The namespace.
 * @param   pFinalizedDirs  The finalized directory data for the namespace.
 * @param   offUnsigned     The ISO image byte offset of the requested data.
 * @param   pbBuf           The output buffer.
 * @param   cbBuf           How much to read.
 */
static size_t rtFsIsoMakerOutFile_ReadDirStructures(PRTFSISOMAKERNAMEDIR *ppDirHint, PRTFSISOMAKERNAMESPACE pNamespace,
                                                    PRTFSISOMAKERFINALIZEDDIRS pFinalizedDirs,
                                                    uint64_t offUnsigned, uint8_t *pbBuf, size_t cbBuf)
{
    if (offUnsigned < pFinalizedDirs->offPathTableL)
        return rtFsIsoMakerOutFile_ReadDirRecords(ppDirHint, pFinalizedDirs,
                                                  pNamespace->fNamespace == RTFSISOMAKER_NAMESPACE_JOLIET,
                                                  offUnsigned, pbBuf, cbBuf);

    uint64_t offInTable;
    if ((offInTable = offUnsigned - pFinalizedDirs->offPathTableL) < pFinalizedDirs->cbPathTable)
        return rtFsIsoMakerOutFile_ReadPathTable(ppDirHint, pFinalizedDirs,
                                                 pNamespace->fNamespace == RTFSISOMAKER_NAMESPACE_JOLIET,
                                                 true /*fLittleEndian*/, (uint32_t)offInTable, pbBuf, cbBuf);

    if ((offInTable = offUnsigned - pFinalizedDirs->offPathTableM) < pFinalizedDirs->cbPathTable)
        return rtFsIsoMakerOutFile_ReadPathTable(ppDirHint, pFinalizedDirs,
                                                 pNamespace->fNamespace == RTFSISOMAKER_NAMESPACE_JOLIET,
                                                 false /*fLittleEndian*/, (uint32_t)offInTable, pbBuf, cbBuf);

    /* ASSUME we're in the zero padding at the end of a path table. */
    Assert(   offUnsigned - pFinalizedDirs->offPathTableL <  RT_ALIGN_32(pFinalizedDirs->cbPathTable, RTFSISOMAKER_SECTOR_SIZE)
           || offUnsigned - pFinalizedDirs->offPathTableM <  RT_ALIGN_32(pFinalizedDirs->cbPathTable, RTFSISOMAKER_SECTOR_SIZE));
    size_t cbZeros = RT_MIN(cbBuf, RTFSISOMAKER_SECTOR_SIZE - ((size_t)offUnsigned & RTFSISOMAKER_SECTOR_OFFSET_MASK));
    memset(pbBuf, 0, cbZeros);
    return cbZeros;
}



/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnRead}
 */
static DECLCALLBACK(int) rtFsIsoMakerOutFile_Read(void *pvThis, RTFOFF off, PCRTSGBUF pSgBuf, bool fBlocking, size_t *pcbRead)
{
    PRTFSISOMAKEROUTPUTFILE pThis     = (PRTFSISOMAKEROUTPUTFILE)pvThis;
    PRTFSISOMAKERINT        pIsoMaker = pThis->pIsoMaker;
    size_t                  cbBuf     = pSgBuf->paSegs[0].cbSeg;
    uint8_t                *pbBuf     = (uint8_t *)pSgBuf->paSegs[0].pvSeg;

    Assert(pSgBuf->cSegs == 1);
    RT_NOREF(fBlocking);

    /*
     * Process the offset, checking for end-of-file.
     */
    uint64_t offUnsigned;
    if (off < 0)
        offUnsigned = pThis->offCurPos;
    else
        offUnsigned = (uint64_t)off;
    if (offUnsigned >= pIsoMaker->cbFinalizedImage)
    {
        if (*pcbRead)
        {
            *pcbRead = 0;
            return VINF_EOF;
        }
        return VERR_EOF;
    }
    if (   !pcbRead
        && pIsoMaker->cbFinalizedImage - offUnsigned < cbBuf)
        return VERR_EOF;

    /*
     * Produce the bytes.
     */
    int    rc     = VINF_SUCCESS;
    size_t cbRead = 0;
    while (cbBuf > 0)
    {
        size_t cbDone;

        /* Betting on there being more file data than metadata, thus doing the
           offset switch in decending order. */
        if (offUnsigned >= pIsoMaker->offFirstFile)
        {
            if (offUnsigned < pIsoMaker->cbFinalizedImage)
            {
                if (offUnsigned < pIsoMaker->cbFinalizedImage - pIsoMaker->cbImagePadding)
                {
                    rc = rtFsIsoMakerOutFile_ReadFileData(pThis, pIsoMaker, offUnsigned, pbBuf, cbBuf, &cbDone);
                    if (RT_FAILURE(rc))
                        break;
                }
                else
                {
                    cbDone = pIsoMaker->cbFinalizedImage - offUnsigned;
                    if (cbDone > cbBuf)
                        cbDone = cbBuf;
                    memset(pbBuf, 0, cbDone);
                }
            }
            else
            {
                rc = pcbRead ? VINF_EOF : VERR_EOF;
                break;
            }
        }
        /*
         * Joliet directory structures.
         */
        else if (   offUnsigned >= pIsoMaker->JolietDirs.offDirs
                 && pIsoMaker->JolietDirs.offDirs < pIsoMaker->JolietDirs.offPathTableL)
            cbDone = rtFsIsoMakerOutFile_ReadDirStructures(&pThis->pDirHintJoliet, &pIsoMaker->Joliet, &pIsoMaker->JolietDirs,
                                                           offUnsigned, pbBuf, cbBuf);
        /*
         * Primary ISO directory structures.
         */
        else if (offUnsigned >= pIsoMaker->PrimaryIsoDirs.offDirs)
            cbDone = rtFsIsoMakerOutFile_ReadDirStructures(&pThis->pDirHintPrimaryIso, &pIsoMaker->PrimaryIso,
                                                           &pIsoMaker->PrimaryIsoDirs, offUnsigned, pbBuf, cbBuf);
        /*
         * Volume descriptors.
         */
        else if (offUnsigned >= _32K)
        {
            size_t offVolDescs = (size_t)offUnsigned - _32K;
            cbDone = RT_MIN(cbBuf, (pIsoMaker->cVolumeDescriptors * RTFSISOMAKER_SECTOR_SIZE) - offVolDescs);
            memcpy(pbBuf, &pIsoMaker->pbVolDescs[offVolDescs], cbDone);
        }
        /*
         * Zeros in the system area.
         */
        else if (offUnsigned >= pIsoMaker->cbSysArea)
        {
            cbDone = RT_MIN(cbBuf, _32K - (size_t)offUnsigned);
            memset(pbBuf, 0, cbDone);
        }
        /*
         * Actual data in the system area.
         */
        else
        {
            cbDone = RT_MIN(cbBuf, pIsoMaker->cbSysArea - (size_t)offUnsigned);
            memcpy(pbBuf, &pIsoMaker->pbSysArea[(size_t)offUnsigned], cbDone);
        }

        /*
         * Common advance.
         */
        cbRead      += cbDone;
        offUnsigned += cbDone;
        pbBuf       += cbDone;
        cbBuf       -= cbDone;
    }

    if (pcbRead)
        *pcbRead = cbRead;
    return rc;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnFlush}
 */
static DECLCALLBACK(int) rtFsIsoMakerOutFile_Flush(void *pvThis)
{
    RT_NOREF(pvThis);
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnTell}
 */
static DECLCALLBACK(int) rtFsIsoMakerOutFile_Tell(void *pvThis, PRTFOFF poffActual)
{
    PRTFSISOMAKEROUTPUTFILE pThis = (PRTFSISOMAKEROUTPUTFILE)pvThis;
    *poffActual = pThis->offCurPos;
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnSkip}
 */
static DECLCALLBACK(int) rtFsIsoMakerOutFile_Skip(void *pvThis, RTFOFF cb)
{
    RTFOFF offIgnored;
    return rtFsIsoMakerOutFile_Seek(pvThis, cb, RTFILE_SEEK_CURRENT, &offIgnored);
}


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnSeek}
 */
static DECLCALLBACK(int) rtFsIsoMakerOutFile_Seek(void *pvThis, RTFOFF offSeek, unsigned uMethod, PRTFOFF poffActual)
{
    PRTFSISOMAKEROUTPUTFILE pThis = (PRTFSISOMAKEROUTPUTFILE)pvThis;

    /*
     * Seek relative to which position.
     */
    uint64_t offWrt;
    switch (uMethod)
    {
        case RTFILE_SEEK_BEGIN:
            offWrt = 0;
            break;

        case RTFILE_SEEK_CURRENT:
            offWrt = pThis->offCurPos;
            break;

        case RTFILE_SEEK_END:
            offWrt = pThis->pIsoMaker->cbFinalizedImage;
            break;

        default:
            return VERR_INVALID_PARAMETER;
    }

    /*
     * Calc new position, take care to stay within RTFOFF type bounds.
     */
    uint64_t offNew;
    if (offSeek == 0)
        offNew = offWrt;
    else if (offSeek > 0)
    {
        offNew = offWrt + offSeek;
        if (   offNew < offWrt
            || offNew > RTFOFF_MAX)
            offNew = RTFOFF_MAX;
    }
    else if ((uint64_t)-offSeek < offWrt)
        offNew = offWrt + offSeek;
    else
        offNew = 0;
    pThis->offCurPos = offNew;

    *poffActual = offNew;
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnQuerySize}
 */
static DECLCALLBACK(int) rtFsIsoMakerOutFile_QuerySize(void *pvThis, uint64_t *pcbFile)
{
    PRTFSISOMAKEROUTPUTFILE pThis = (PRTFSISOMAKEROUTPUTFILE)pvThis;
    *pcbFile = pThis->pIsoMaker->cbFinalizedImage;
    return VINF_SUCCESS;
}


/**
 * Standard file operations.
 */
DECL_HIDDEN_CONST(const RTVFSFILEOPS) g_rtFsIsoMakerOutputFileOps =
{
    { /* Stream */
        { /* Obj */
            RTVFSOBJOPS_VERSION,
            RTVFSOBJTYPE_FILE,
            "ISO Maker Output File",
            rtFsIsoMakerOutFile_Close,
            rtFsIsoMakerOutFile_QueryInfo,
            NULL,
            RTVFSOBJOPS_VERSION
        },
        RTVFSIOSTREAMOPS_VERSION,
        RTVFSIOSTREAMOPS_FEAT_NO_SG,
        rtFsIsoMakerOutFile_Read,
        NULL /*Write*/,
        rtFsIsoMakerOutFile_Flush,
        NULL /*PollOne*/,
        rtFsIsoMakerOutFile_Tell,
        rtFsIsoMakerOutFile_Skip,
        NULL /*ZeroFill*/,
        RTVFSIOSTREAMOPS_VERSION,
    },
    RTVFSFILEOPS_VERSION,
    0,
    { /* ObjSet */
        RTVFSOBJSETOPS_VERSION,
        RT_UOFFSETOF(RTVFSFILEOPS, ObjSet) - RT_UOFFSETOF(RTVFSFILEOPS, Stream.Obj),
        NULL /*SetMode*/,
        NULL /*SetTimes*/,
        NULL /*SetOwner*/,
        RTVFSOBJSETOPS_VERSION
    },
    rtFsIsoMakerOutFile_Seek,
    rtFsIsoMakerOutFile_QuerySize,
    NULL /*SetSize*/,
    NULL /*QueryMaxSize*/,
    RTVFSFILEOPS_VERSION
};



/**
 * Creates a VFS file for a finalized ISO maker instanced.
 *
 * The file can be used to access the image.  Both sequential and random access
 * are supported, so that this could in theory be hooked up to a CD/DVD-ROM
 * drive emulation and used as a virtual ISO image.
 *
 * @returns IRPT status code.
 * @param   hIsoMaker           The ISO maker handle.
 * @param   phVfsFile           Where to return the handle.
 */
RTDECL(int) RTFsIsoMakerCreateVfsOutputFile(RTFSISOMAKER hIsoMaker, PRTVFSFILE phVfsFile)
{
    PRTFSISOMAKERINT pThis = hIsoMaker;
    RTFSISOMAKER_ASSERT_VALID_HANDLE_RET(pThis);
    AssertReturn(pThis->fFinalized, VERR_WRONG_ORDER);
    AssertPtrReturn(phVfsFile, VERR_INVALID_POINTER);

    uint32_t cRefs = RTFsIsoMakerRetain(pThis);
    AssertReturn(cRefs != UINT32_MAX, VERR_INVALID_HANDLE);

    PRTFSISOMAKEROUTPUTFILE pFileData;
    RTVFSFILE               hVfsFile;
    int rc = RTVfsNewFile(&g_rtFsIsoMakerOutputFileOps, sizeof(*pFileData), RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_CREATE,
                          NIL_RTVFS, NIL_RTVFSLOCK, &hVfsFile, (void **)&pFileData);
    if (RT_SUCCESS(rc))
    {
        pFileData->pIsoMaker          = pThis;
        pFileData->offCurPos          = 0;
        pFileData->pFileHint          = NULL;
        pFileData->hVfsSrcFile        = NIL_RTVFSFILE;
        pFileData->pDirHintPrimaryIso = NULL;
        pFileData->pDirHintJoliet     = NULL;
        pFileData->iChildPrimaryIso   = UINT32_MAX;
        pFileData->iChildJoliet       = UINT32_MAX;
        *phVfsFile = hVfsFile;
        return VINF_SUCCESS;
    }

    RTFsIsoMakerRelease(pThis);
    *phVfsFile = NIL_RTVFSFILE;
    return rc;
}