summaryrefslogtreecommitdiffstats
path: root/src/VBox/Runtime/common/efi/efivarstorevfs.cpp
blob: 7703577ee83a768d2c7321420449c08b025e640a (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
/* $Id: efivarstorevfs.cpp $ */
/** @file
 * IPRT - Expose a EFI variable store as a Virtual Filesystem.
 */

/*
 * Copyright (C) 2021-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 <iprt/efi.h>

#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/crc.h>
#include <iprt/file.h>
#include <iprt/err.h>
#include <iprt/log.h>
#include <iprt/mem.h>
#include <iprt/string.h>
#include <iprt/uuid.h>
#include <iprt/utf16.h>
#include <iprt/vfs.h>
#include <iprt/vfslowlevel.h>
#include <iprt/formats/efi-fv.h>
#include <iprt/formats/efi-varstore.h>


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/** Pointer to the varstore filesystem data. */
typedef struct RTEFIVARSTORE *PRTEFIVARSTORE;


/**
 * EFI variable entry.
 */
typedef struct RTEFIVAR
{
    /** Pointer to the owning variable store. */
    PRTEFIVARSTORE      pVarStore;
    /** Offset of the variable data located in the backing image - 0 if not written yet. */
    uint64_t            offVarData;
    /** Pointer to the in memory data, NULL if not yet read. */
    void                *pvData;
    /** Monotonic counter value. */
    uint64_t            cMonotonic;
    /** Size of the variable data in bytes. */
    uint32_t            cbData;
    /** Index of the assoicated public key. */
    uint32_t            idPubKey;
    /** Attributes for the variable. */
    uint32_t            fAttr;
    /** Flag whether the variable was deleted. */
    bool                fDeleted;
    /** Name of the variable. */
    char                *pszName;
    /** The raw EFI timestamp as read from the header. */
    EFI_TIME            EfiTimestamp;
    /** The creation/update time. */
    RTTIMESPEC          Time;
    /** The vendor UUID of the variable. */
    RTUUID              Uuid;
} RTEFIVAR;
/** Pointer to an EFI variable. */
typedef RTEFIVAR *PRTEFIVAR;


/**
 * EFI GUID entry.
 */
typedef struct RTEFIGUID
{
    /** The UUID representation of the GUID. */
    RTUUID              Uuid;
    /** Pointer to the array of indices into RTEFIVARSTORE::paVars. */
    uint32_t            *paidxVars;
    /** Number of valid indices in the array. */
    uint32_t            cVars;
    /** Maximum number of indices the array can hold. */
    uint32_t            cVarsMax;
} RTEFIGUID;
/** Pointer to an EFI variable. */
typedef RTEFIGUID *PRTEFIGUID;


/**
 * EFI variable store filesystem volume.
 */
typedef struct RTEFIVARSTORE
{
    /** Handle to itself. */
    RTVFS               hVfsSelf;
    /** The file, partition, or whatever backing the volume has. */
    RTVFSFILE           hVfsBacking;
    /** The size of the backing thingy. */
    uint64_t            cbBacking;

    /** RTVFSMNT_F_XXX. */
    uint32_t            fMntFlags;
    /** RTEFIVARSTOREVFS_F_XXX (currently none defined). */
    uint32_t            fVarStoreFlags;

    /** Size of the variable store (minus the header). */
    uint64_t            cbVarStore;
    /** Start offset into the backing image where the variable data starts. */
    uint64_t            offStoreData;
    /** Flag whether the variable store uses authenticated variables. */
    bool                fAuth;
    /** Number of bytes occupied by existing variables. */
    uint64_t            cbVarData;

    /** Pointer to the array of variables sorted by start offset. */
    PRTEFIVAR           paVars;
    /** Number of valid variables in the array. */
    uint32_t            cVars;
    /** Maximum number of variables the array can hold. */
    uint32_t            cVarsMax;

    /** Pointer to the array of vendor GUIDS. */
    PRTEFIGUID          paGuids;
    /** Number of valid GUIDS in the array. */
    uint32_t            cGuids;
    /** Maximum number of GUIDS the array can hold. */
    uint32_t            cGuidsMax;

} RTEFIVARSTORE;


/**
 * Variable store directory type.
 */
typedef enum RTEFIVARSTOREDIRTYPE
{
    /** Invalid directory type. */
    RTEFIVARSTOREDIRTYPE_INVALID = 0,
    /** Root directory type. */
    RTEFIVARSTOREDIRTYPE_ROOT,
    /** 'by-name' directory. */
    RTEFIVARSTOREDIRTYPE_BY_NAME,
    /** 'by-uuid' directory. */
    RTEFIVARSTOREDIRTYPE_BY_GUID,
    /** 'raw' directory. */
    RTEFIVARSTOREDIRTYPE_RAW,
    /** Specific 'by-uuid/{...}' directory. */
    RTEFIVARSTOREDIRTYPE_GUID,
    /** Specific 'raw/{...}' directory. */
    RTEFIVARSTOREDIRTYPE_RAW_ENTRY,
    /** 32bit blowup hack. */
    RTEFIVARSTOREDIRTYPE_32BIT_HACK = 0x7fffffff
} RTEFIVARSTOREDIRTYPE;


/**
 * EFI variable store directory entry.
 */
typedef struct RTEFIVARSTOREDIRENTRY
{
    /** Name of the directory if constant. */
    const char              *pszName;
    /** Size of the name. */
    size_t                  cbName;
    /** Entry type. */
    RTEFIVARSTOREDIRTYPE    enmType;
    /** Parent entry type. */
    RTEFIVARSTOREDIRTYPE    enmParentType;
} RTEFIVARSTOREDIRENTRY;
/** Pointer to a EFI variable store directory entry. */
typedef RTEFIVARSTOREDIRENTRY *PRTEFIVARSTOREDIRENTRY;
/** Pointer to a const EFI variable store directory entry. */
typedef const RTEFIVARSTOREDIRENTRY *PCRTEFIVARSTOREDIRENTRY;


/**
 * Variable store directory.
 */
typedef struct RTEFIVARSTOREDIR
{
    /* Flag whether we reached the end of directory entries. */
    bool                    fNoMoreFiles;
    /** The index of the next item to read. */
    uint32_t                idxNext;
    /** Directory entry. */
    PCRTEFIVARSTOREDIRENTRY pEntry;
    /** The variable store associated with this directory. */
    PRTEFIVARSTORE          pVarStore;
    /** Time when the directory was created. */
    RTTIMESPEC              Time;
    /** Pointer to the GUID entry, only valid for RTEFIVARSTOREDIRTYPE_GUID. */
    PRTEFIGUID              pGuid;
    /** The variable ID, only valid for RTEFIVARSTOREDIRTYPE_RAW_ENTRY. */
    uint32_t                idVar;
} RTEFIVARSTOREDIR;
/** Pointer to an Variable store directory. */
typedef RTEFIVARSTOREDIR *PRTEFIVARSTOREDIR;


/**
 * File type.
 */
typedef enum RTEFIVARSTOREFILETYPE
{
    /** Invalid type, do not use. */
    RTEFIVARSTOREFILETYPE_INVALID = 0,
    /** File accesses the data portion of the variable. */
    RTEFIVARSTOREFILETYPE_DATA,
    /** File accesses the attributes of the variable. */
    RTEFIVARSTOREFILETYPE_ATTR,
    /** File accesses the UUID of the variable. */
    RTEFIVARSTOREFILETYPE_UUID,
    /** File accesses the public key index of the variable. */
    RTEFIVARSTOREFILETYPE_PUBKEY,
    /** File accesses the raw EFI Time of the variable. */
    RTEFIVARSTOREFILETYPE_TIME,
    /** The monotonic counter (deprecated). */
    RTEFIVARSTOREFILETYPE_MONOTONIC,
    /** 32bit hack. */
    RTEFIVARSTOREFILETYPE_32BIT_HACK = 0x7fffffff
} RTEFIVARSTOREFILETYPE;


/**
 * Raw file type entry.
 */
typedef struct RTEFIVARSTOREFILERAWENTRY
{
    /** Name of the entry. */
    const char              *pszName;
    /** The associated file type. */
    RTEFIVARSTOREFILETYPE   enmType;
    /** File size of the object, 0 if dynamic. */
    size_t                  cbObject;
    /** Offset of the item in the variable header. */
    uint32_t                offObject;
} RTEFIVARSTOREFILERAWENTRY;
/** Pointer to a raw file type entry. */
typedef RTEFIVARSTOREFILERAWENTRY *PRTEFIVARSTOREFILERAWENTRY;
/** Pointer to a const file type entry. */
typedef const RTEFIVARSTOREFILERAWENTRY *PCRTEFIVARSTOREFILERAWENTRY;


/**
 * Open file instance.
 */
typedef struct RTEFIVARFILE
{
    /** The file type. */
    PCRTEFIVARSTOREFILERAWENTRY pEntry;
    /** Variable store this file belongs to. */
    PRTEFIVARSTORE              pVarStore;
    /** The underlying variable structure. */
    PRTEFIVAR                   pVar;
    /** Current offset into the file for I/O. */
    RTFOFF                      offFile;
} RTEFIVARFILE;
/** Pointer to an open file instance. */
typedef RTEFIVARFILE *PRTEFIVARFILE;


/**
 * Directories.
 */
static const RTEFIVARSTOREDIRENTRY g_aDirs[] =
{
    { NULL,      0,            RTEFIVARSTOREDIRTYPE_ROOT,      RTEFIVARSTOREDIRTYPE_ROOT    },
    { RT_STR_TUPLE("by-name"), RTEFIVARSTOREDIRTYPE_BY_NAME,   RTEFIVARSTOREDIRTYPE_ROOT    },
    { RT_STR_TUPLE("by-uuid"), RTEFIVARSTOREDIRTYPE_BY_GUID,   RTEFIVARSTOREDIRTYPE_ROOT    },
    { RT_STR_TUPLE("raw"),     RTEFIVARSTOREDIRTYPE_RAW,       RTEFIVARSTOREDIRTYPE_ROOT    },
    { NULL,      0,            RTEFIVARSTOREDIRTYPE_GUID,      RTEFIVARSTOREDIRTYPE_BY_GUID },
    { NULL,      0,            RTEFIVARSTOREDIRTYPE_RAW_ENTRY, RTEFIVARSTOREDIRTYPE_RAW     },
};


/**
 * Raw files for accessing specific items in the variable header.
 */
static const RTEFIVARSTOREFILERAWENTRY g_aRawFiles[] =
{
    { "attr",      RTEFIVARSTOREFILETYPE_ATTR,      sizeof(uint32_t), RT_UOFFSETOF(RTEFIVAR, fAttr)        },
    { "data",      RTEFIVARSTOREFILETYPE_DATA,                     0,                                    0 },
    { "uuid",      RTEFIVARSTOREFILETYPE_UUID,      sizeof(RTUUID),   RT_UOFFSETOF(RTEFIVAR, Uuid)         },
    { "pubkey",    RTEFIVARSTOREFILETYPE_PUBKEY,    sizeof(uint32_t), RT_UOFFSETOF(RTEFIVAR, idPubKey)     },
    { "time",      RTEFIVARSTOREFILETYPE_TIME,      sizeof(EFI_TIME), RT_UOFFSETOF(RTEFIVAR, EfiTimestamp) },
    { "monotonic", RTEFIVARSTOREFILETYPE_MONOTONIC, sizeof(uint64_t), RT_UOFFSETOF(RTEFIVAR, cMonotonic)   }
};

#define RTEFIVARSTORE_FILE_ENTRY_DATA 1


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static int rtEfiVarStore_NewDirByType(PRTEFIVARSTORE pThis, RTEFIVARSTOREDIRTYPE enmDirType,
                                      PRTEFIGUID pGuid, uint32_t idVar, PRTVFSOBJ phVfsObj);


#ifdef LOG_ENABLED

/**
 * Logs a firmware volume header.
 *
 * @param   pFvHdr              The firmware volume header.
 */
static void rtEfiVarStoreFvHdr_Log(PCEFI_FIRMWARE_VOLUME_HEADER pFvHdr)
{
    if (LogIs2Enabled())
    {
        Log2(("EfiVarStore: Volume Header:\n"));
        Log2(("EfiVarStore:   abZeroVec                   %#.*Rhxs\n", sizeof(pFvHdr->abZeroVec), &pFvHdr->abZeroVec[0]));
        Log2(("EfiVarStore:   GuidFilesystem              %#.*Rhxs\n", sizeof(pFvHdr->GuidFilesystem), &pFvHdr->GuidFilesystem));
        Log2(("EfiVarStore:   cbFv                        %#RX64\n", RT_LE2H_U64(pFvHdr->cbFv)));
        Log2(("EfiVarStore:   u32Signature                %#RX32\n", RT_LE2H_U32(pFvHdr->u32Signature)));
        Log2(("EfiVarStore:   fAttr                       %#RX32\n", RT_LE2H_U32(pFvHdr->fAttr)));
        Log2(("EfiVarStore:   cbFvHdr                     %#RX16\n", RT_LE2H_U16(pFvHdr->cbFvHdr)));
        Log2(("EfiVarStore:   u16Chksum                   %#RX16\n", RT_LE2H_U16(pFvHdr->u16Chksum)));
        Log2(("EfiVarStore:   offExtHdr                   %#RX16\n", RT_LE2H_U16(pFvHdr->offExtHdr)));
        Log2(("EfiVarStore:   bRsvd                       %#RX8\n", pFvHdr->bRsvd));
        Log2(("EfiVarStore:   bRevision                   %#RX8\n", pFvHdr->bRevision));
    }
}


/**
 * Logs a variable store header.
 *
 * @param   pStoreHdr           The variable store header.
 */
static void rtEfiVarStoreHdr_Log(PCEFI_VARSTORE_HEADER pStoreHdr)
{
    if (LogIs2Enabled())
    {
        Log2(("EfiVarStore: Variable Store Header:\n"));
        Log2(("EfiVarStore:   GuidVarStore                %#.*Rhxs\n", sizeof(pStoreHdr->GuidVarStore), &pStoreHdr->GuidVarStore));
        Log2(("EfiVarStore:   cbVarStore                  %#RX32\n", RT_LE2H_U32(pStoreHdr->cbVarStore)));
        Log2(("EfiVarStore:   bFmt                        %#RX8\n", pStoreHdr->bFmt));
        Log2(("EfiVarStore:   bState                      %#RX8\n", pStoreHdr->bState));
    }
}


/**
 * Logs a authenticated variable header.
 *
 * @param   pVarHdr             The authenticated variable header.
 * @param   offVar              Offset of the authenticated variable header.
 */
static void rtEfiVarStoreAuthVarHdr_Log(PCEFI_AUTH_VAR_HEADER pVarHdr, uint64_t offVar)
{
    if (LogIs2Enabled())
    {
        Log2(("EfiVarStore: Authenticated Variable Header at offset %#RU64:\n", offVar));
        Log2(("EfiVarStore:   u16StartId                  %#RX16\n", RT_LE2H_U16(pVarHdr->u16StartId)));
        Log2(("EfiVarStore:   bState                      %#RX8\n", pVarHdr->bState));
        Log2(("EfiVarStore:   bRsvd                       %#RX8\n", pVarHdr->bRsvd));
        Log2(("EfiVarStore:   fAttr                       %#RX32\n", RT_LE2H_U32(pVarHdr->fAttr)));
        Log2(("EfiVarStore:   cMonotonic                  %#RX64\n", RT_LE2H_U64(pVarHdr->cMonotonic)));
        Log2(("EfiVarStore:   Timestamp.u16Year           %#RX16\n", RT_LE2H_U16(pVarHdr->Timestamp.u16Year)));
        Log2(("EfiVarStore:   Timestamp.u8Month           %#RX8\n", pVarHdr->Timestamp.u8Month));
        Log2(("EfiVarStore:   Timestamp.u8Day             %#RX8\n", pVarHdr->Timestamp.u8Day));
        Log2(("EfiVarStore:   Timestamp.u8Hour            %#RX8\n", pVarHdr->Timestamp.u8Hour));
        Log2(("EfiVarStore:   Timestamp.u8Minute          %#RX8\n", pVarHdr->Timestamp.u8Minute));
        Log2(("EfiVarStore:   Timestamp.u8Second          %#RX8\n", pVarHdr->Timestamp.u8Second));
        Log2(("EfiVarStore:   Timestamp.bPad0             %#RX8\n", pVarHdr->Timestamp.bPad0));
        Log2(("EfiVarStore:   Timestamp.u32Nanosecond     %#RX32\n", RT_LE2H_U32(pVarHdr->Timestamp.u32Nanosecond)));
        Log2(("EfiVarStore:   Timestamp.iTimezone         %#RI16\n", RT_LE2H_S16(pVarHdr->Timestamp.iTimezone)));
        Log2(("EfiVarStore:   Timestamp.u8Daylight        %#RX8\n", pVarHdr->Timestamp.u8Daylight));
        Log2(("EfiVarStore:   Timestamp.bPad1             %#RX8\n", pVarHdr->Timestamp.bPad1));
        Log2(("EfiVarStore:   idPubKey                    %#RX32\n", RT_LE2H_U32(pVarHdr->idPubKey)));
        Log2(("EfiVarStore:   cbName                      %#RX32\n", RT_LE2H_U32(pVarHdr->cbName)));
        Log2(("EfiVarStore:   cbData                      %#RX32\n", RT_LE2H_U32(pVarHdr->cbData)));
        Log2(("EfiVarStore:   GuidVendor                  %#.*Rhxs\n", sizeof(pVarHdr->GuidVendor), &pVarHdr->GuidVendor));
    }
}

#endif /* LOG_ENABLED */

/**
 * Worker for rtEfiVarStoreFile_QueryInfo() and rtEfiVarStoreDir_QueryInfo().
 *
 * @returns IPRT status code.
 * @param   cbObject            Size of the object in bytes.
 * @param   fIsDir              Flag whether the object is a directory or file.
 * @param   pTime               The time to use.
 * @param   pObjInfo            The FS object information structure to fill in.
 * @param   enmAddAttr          What to fill in.
 */
static int rtEfiVarStore_QueryInfo(uint64_t cbObject, bool fIsDir, PCRTTIMESPEC pTime, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    pObjInfo->cbObject              = cbObject;
    pObjInfo->cbAllocated           = cbObject;
    pObjInfo->AccessTime            = *pTime;
    pObjInfo->ModificationTime      = *pTime;
    pObjInfo->ChangeTime            = *pTime;
    pObjInfo->BirthTime             = *pTime;
    pObjInfo->Attr.fMode            =   fIsDir
                                      ? RTFS_TYPE_DIRECTORY | RTFS_UNIX_ALL_ACCESS_PERMS
                                      : RTFS_TYPE_FILE | RTFS_UNIX_IWOTH | RTFS_UNIX_IROTH
                                                       | RTFS_UNIX_IWGRP | RTFS_UNIX_IRGRP
                                                       | RTFS_UNIX_IWUSR | RTFS_UNIX_IRUSR;
    pObjInfo->Attr.enmAdditional    = enmAddAttr;

    switch (enmAddAttr)
    {
        case RTFSOBJATTRADD_NOTHING: 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       = 0;
            pObjInfo->Attr.u.UnixOwner.szName[0] = '\0';
            break;
        case RTFSOBJATTRADD_UNIX_GROUP:
            pObjInfo->Attr.u.UnixGroup.gid       = 0;
            pObjInfo->Attr.u.UnixGroup.szName[0] = '\0';
            break;
        case RTFSOBJATTRADD_EASIZE:
            pObjInfo->Attr.u.EASize.cb = 0;
            break;
        default:
            return VERR_INVALID_PARAMETER;
    }
    return VINF_SUCCESS;
}


/**
 * Tries to find and return the GUID entry for the given UUID.
 *
 * @returns Pointer to the GUID entry or NULL if not found.
 * @param   pThis               The EFI variable store instance.
 * @param   pUuid               The UUID to look for.
 */
static PRTEFIGUID rtEfiVarStore_GetGuid(PRTEFIVARSTORE pThis, PCRTUUID pUuid)
{
    for (uint32_t i = 0; i < pThis->cGuids; i++)
        if (!RTUuidCompare(&pThis->paGuids[i].Uuid, pUuid))
            return &pThis->paGuids[i];

    return NULL;
}


/**
 * Adds the given UUID to the array of known GUIDs.
 *
 * @returns Pointer to the GUID entry or NULL if out of memory.
 * @param   pThis               The EFI variable store instance.
 * @param   pUuid               The UUID to add.
 */
static PRTEFIGUID rtEfiVarStore_AddGuid(PRTEFIVARSTORE pThis, PCRTUUID pUuid)
{
    if (pThis->cGuids == pThis->cGuidsMax)
    {
        /* Grow the array. */
        uint32_t cGuidsMaxNew = pThis->cGuidsMax + 10;
        PRTEFIGUID paGuidsNew = (PRTEFIGUID)RTMemRealloc(pThis->paGuids, cGuidsMaxNew * sizeof(RTEFIGUID));
        if (!paGuidsNew)
            return NULL;

        pThis->paGuids   = paGuidsNew;
        pThis->cGuidsMax = cGuidsMaxNew;
    }

    PRTEFIGUID pGuid = &pThis->paGuids[pThis->cGuids++];
    pGuid->Uuid      = *pUuid;
    pGuid->paidxVars = NULL;
    pGuid->cVars     = 0;
    pGuid->cVarsMax  = 0;
    return pGuid;
}


/**
 * Adds the given variable to the GUID array.
 *
 * @returns IPRT status code.
 * @param   pThis               The EFI variable store instance.
 * @param   pUuid               The UUID of the variable.
 * @param   idVar               The variable index into the array.
 */
static int rtEfiVarStore_AddVarByGuid(PRTEFIVARSTORE pThis, PCRTUUID pUuid, uint32_t idVar)
{
    PRTEFIGUID pGuid = rtEfiVarStore_GetGuid(pThis, pUuid);
    if (!pGuid)
        pGuid = rtEfiVarStore_AddGuid(pThis, pUuid);

    if (   pGuid
        && pGuid->cVars == pGuid->cVarsMax)
    {
        /* Grow the array. */
        uint32_t cVarsMaxNew = pGuid->cVarsMax + 10;
        uint32_t *paidxVarsNew = (uint32_t *)RTMemRealloc(pGuid->paidxVars, cVarsMaxNew * sizeof(uint32_t));
        if (!paidxVarsNew)
            return VERR_NO_MEMORY;

        pGuid->paidxVars = paidxVarsNew;
        pGuid->cVarsMax  = cVarsMaxNew;
    }

    int rc = VINF_SUCCESS;
    if (pGuid)
        pGuid->paidxVars[pGuid->cVars++] = idVar;
    else
        rc = VERR_NO_MEMORY;

    return rc;
}


/**
 * Reads variable data from the given memory area.
 *
 * @returns IPRT status code.
 * @param   pThis               The EFI variable file instance.
 * @param   pvData              Pointer to the start of the data.
 * @param   cbData              Size of the variable data in bytes.
 * @param   off                 Where to start reading relative from the data start offset.
 * @param   pSgBuf              Where to store the read data.
 * @param   pcbRead             Where to return the number of bytes read, optional.
 */
static int rtEfiVarStoreFile_ReadMem(PRTEFIVARFILE pThis, const void *pvData, size_t cbData,
                                     RTFOFF off, PCRTSGBUF pSgBuf, size_t *pcbRead)
{
    int rc = VINF_SUCCESS;
    size_t cbRead = pSgBuf->paSegs[0].cbSeg;
    size_t cbThisRead = RT_MIN(cbData - off, cbRead);
    const uint8_t *pbData = (const uint8_t *)pvData;
    if (!pcbRead)
    {
        if (cbThisRead == cbRead)
            memcpy(pSgBuf->paSegs[0].pvSeg, &pbData[off], cbThisRead);
        else
            rc = VERR_EOF;

        if (RT_SUCCESS(rc))
            pThis->offFile = off + cbThisRead;
        Log6(("rtEfiVarStoreFile_ReadMem: off=%#RX64 cbSeg=%#x -> %Rrc\n", off, pSgBuf->paSegs[0].cbSeg, rc));
    }
    else
    {
        if ((uint64_t)off >= cbData)
        {
            *pcbRead = 0;
            rc = VINF_EOF;
        }
        else
        {
            memcpy(pSgBuf->paSegs[0].pvSeg, &pbData[off], cbThisRead);
            /* Return VINF_EOF if beyond end-of-file. */
            if (cbThisRead < cbRead)
                rc = VINF_EOF;
            pThis->offFile = off + cbThisRead;
            *pcbRead = cbThisRead;
        }
        Log6(("rtEfiVarStoreFile_ReadMem: off=%#RX64 cbSeg=%#x -> %Rrc *pcbRead=%#x\n", off, pSgBuf->paSegs[0].cbSeg, rc, *pcbRead));
    }

    return rc;
}


/**
 * Writes variable data from the given memory area.
 *
 * @returns IPRT status code.
 * @param   pThis               The EFI variable file instance.
 * @param   pvData              Pointer to the start of the data.
 * @param   cbData              Size of the variable data in bytes.
 * @param   off                 Where to start writing relative from the data start offset.
 * @param   pSgBuf              The data to write.
 * @param   pcbWritten          Where to return the number of bytes written, optional.
 */
static int rtEfiVarStoreFile_WriteMem(PRTEFIVARFILE pThis, void *pvData, size_t cbData,
                                      RTFOFF off, PCRTSGBUF pSgBuf, size_t *pcbWritten)
{
    int rc = VINF_SUCCESS;
    size_t cbWrite = pSgBuf->paSegs[0].cbSeg;
    size_t cbThisWrite = RT_MIN(cbData - off, cbWrite);
    uint8_t *pbData = (uint8_t *)pvData;
    if (!pcbWritten)
    {
        if (cbThisWrite == cbWrite)
            memcpy(&pbData[off], pSgBuf->paSegs[0].pvSeg, cbThisWrite);
        else
            rc = VERR_EOF;

        if (RT_SUCCESS(rc))
            pThis->offFile = off + cbThisWrite;
        Log6(("rtEfiVarStoreFile_WriteMem: off=%#RX64 cbSeg=%#x -> %Rrc\n", off, pSgBuf->paSegs[0].cbSeg, rc));
    }
    else
    {
        if ((uint64_t)off >= cbData)
        {
            *pcbWritten = 0;
            rc = VINF_EOF;
        }
        else
        {
            memcpy(&pbData[off], pSgBuf->paSegs[0].pvSeg, cbThisWrite);
            /* Return VINF_EOF if beyond end-of-file. */
            if (cbThisWrite < cbWrite)
                rc = VINF_EOF;
            pThis->offFile = off + cbThisWrite;
            *pcbWritten = cbThisWrite;
        }
        Log6(("rtEfiVarStoreFile_WriteMem: off=%#RX64 cbSeg=%#x -> %Rrc *pcbWritten=%#x\n", off, pSgBuf->paSegs[0].cbSeg, rc, *pcbWritten));
    }

    return rc;
}


/**
 * Reads variable data from the given range.
 *
 * @returns IPRT status code.
 * @param   pThis               The EFI variable file instance.
 * @param   offData             Where the data starts in the backing storage.
 * @param   cbData              Size of the variable data in bytes.
 * @param   off                 Where to start reading relative from the data start offset.
 * @param   pSgBuf              Where to store the read data.
 * @param   pcbRead             Where to return the number of bytes read, optional.
 */
static int rtEfiVarStoreFile_ReadFile(PRTEFIVARFILE pThis, uint64_t offData, size_t cbData,
                                      RTFOFF off, PCRTSGBUF pSgBuf, size_t *pcbRead)
{
    int rc;
    PRTEFIVARSTORE pVarStore = pThis->pVarStore;
    size_t cbRead = pSgBuf->paSegs[0].cbSeg;
    size_t cbThisRead = RT_MIN(cbData - off, cbRead);
    uint64_t offStart = offData + off;
    if (!pcbRead)
    {
        if (cbThisRead == cbRead)
            rc = RTVfsFileReadAt(pVarStore->hVfsBacking, offStart, pSgBuf->paSegs[0].pvSeg, cbThisRead, NULL);
        else
            rc = VERR_EOF;

        if (RT_SUCCESS(rc))
            pThis->offFile = off + cbThisRead;
        Log6(("rtFsEfiVarStore_Read: off=%#RX64 cbSeg=%#x -> %Rrc\n", off, pSgBuf->paSegs[0].cbSeg, rc));
    }
    else
    {
        if ((uint64_t)off >= cbData)
        {
            *pcbRead = 0;
            rc = VINF_EOF;
        }
        else
        {
            rc = RTVfsFileReadAt(pVarStore->hVfsBacking, offStart, pSgBuf->paSegs[0].pvSeg, cbThisRead, NULL);
            if (RT_SUCCESS(rc))
            {
                /* Return VINF_EOF if beyond end-of-file. */
                if (cbThisRead < cbRead)
                    rc = VINF_EOF;
                pThis->offFile = off + cbThisRead;
                *pcbRead = cbThisRead;
            }
            else
                *pcbRead = 0;
        }
        Log6(("rtFsEfiVarStore_Read: off=%#RX64 cbSeg=%#x -> %Rrc *pcbRead=%#x\n", off, pSgBuf->paSegs[0].cbSeg, rc, *pcbRead));
    }

    return rc;
}


/**
 * Ensures that the variable data is available before any modification.
 *
 * @returns IPRT status code.
 * @param   pVar                The variable instance.
 */
static int rtEfiVarStore_VarReadData(PRTEFIVAR pVar)
{
    if (RT_LIKELY(   !pVar->offVarData
                  || !pVar->cbData))
        return VINF_SUCCESS;

    Assert(!pVar->pvData);
    pVar->pvData = RTMemAlloc(pVar->cbData);
    if (RT_UNLIKELY(!pVar->pvData))
        return VERR_NO_MEMORY;

    PRTEFIVARSTORE pVarStore = pVar->pVarStore;
    int rc = RTVfsFileReadAt(pVarStore->hVfsBacking, pVar->offVarData, pVar->pvData, pVar->cbData, NULL);
    if (RT_SUCCESS(rc))
        pVar->offVarData = 0; /* Marks the variable data as in memory. */
    else
    {
        RTMemFree(pVar->pvData);
        pVar->pvData = NULL;
    }

    return rc;
}


/**
 * Ensures that the given variable has the given data size.
 *
 * @returns IPRT status code.
 * @retval  VERR_DISK_FULL if the new size would exceed the variable storage size.
 * @param   pVar                The variable instance.
 * @param   cbData              New number of bytes of data for the variable.
 */
static int rtEfiVarStore_VarEnsureDataSz(PRTEFIVAR pVar, size_t cbData)
{
    PRTEFIVARSTORE pVarStore = pVar->pVarStore;

    if (pVar->cbData == cbData)
        return VINF_SUCCESS;

    if ((uint32_t)cbData != cbData)
        return VERR_FILE_TOO_BIG;

    int rc = VINF_SUCCESS;
    if (cbData < pVar->cbData)
    {
        /* Shrink. */
        void *pvNew = RTMemRealloc(pVar->pvData, cbData);
        if (pvNew)
        {
            pVar->pvData = pvNew;
            pVarStore->cbVarData -= pVar->cbData - cbData;
            pVar->cbData = (uint32_t)cbData;
        }
        else
            rc = VERR_NO_MEMORY;
    }
    else if (cbData > pVar->cbData)
    {
        /* Grow. */
        if (pVarStore->cbVarStore - pVarStore->cbVarData >= cbData - pVar->cbData)
        {
            void *pvNew = RTMemRealloc(pVar->pvData, cbData);
            if (pvNew)
            {
                pVar->pvData = pvNew;
                pVarStore->cbVarData += cbData - pVar->cbData;
                pVar->cbData          = (uint32_t)cbData;
            }
            else
                rc = VERR_NO_MEMORY;
        }
        else
            rc = VERR_DISK_FULL;
    }

    return rc;
}


/**
 * Flush the variable store to the backing storage. This will remove any
 * deleted variables in the backing storage.
 *
 * @returns IPRT status code.
 * @param   pThis               The EFI variable store instance.
 */
static int rtEfiVarStore_Flush(PRTEFIVARSTORE pThis)
{
    int rc = VINF_SUCCESS;
    uint64_t offCur = pThis->offStoreData;

    for (uint32_t i = 0; i < pThis->cVars && RT_SUCCESS(rc); i++)
    {
        PRTUTF16 pwszName = NULL;
        size_t cwcLen = 0;
        PRTEFIVAR pVar = &pThis->paVars[i];

        if (!pVar->fDeleted)
        {
            rc = RTStrToUtf16Ex(pVar->pszName, RTSTR_MAX, &pwszName, 0, &cwcLen);
            if (RT_SUCCESS(rc))
            {
                cwcLen++; /* Include the terminator. */

                /* Read in the data of the variable if it exists. */
                rc = rtEfiVarStore_VarReadData(pVar);
                if (RT_SUCCESS(rc))
                {
                    /* Write out the variable. */
                    EFI_AUTH_VAR_HEADER VarHdr;
                    size_t cbName = cwcLen * sizeof(RTUTF16);

                    VarHdr.u16StartId = RT_H2LE_U16(EFI_AUTH_VAR_HEADER_START);
                    VarHdr.bState     = EFI_AUTH_VAR_HEADER_STATE_ADDED;
                    VarHdr.bRsvd      = 0;
                    VarHdr.fAttr      = RT_H2LE_U32(pVar->fAttr);
                    VarHdr.cMonotonic = RT_H2LE_U64(pVar->cMonotonic);
                    VarHdr.idPubKey   = RT_H2LE_U32(pVar->idPubKey);
                    VarHdr.cbName     = RT_H2LE_U32((uint32_t)cbName);
                    VarHdr.cbData     = RT_H2LE_U32(pVar->cbData);
                    RTEfiGuidFromUuid(&VarHdr.GuidVendor, &pVar->Uuid);
                    memcpy(&VarHdr.Timestamp, &pVar->EfiTimestamp, sizeof(pVar->EfiTimestamp));

                    rc = RTVfsFileWriteAt(pThis->hVfsBacking, offCur, &VarHdr, sizeof(VarHdr), NULL);
                    if (RT_SUCCESS(rc))
                        rc = RTVfsFileWriteAt(pThis->hVfsBacking, offCur + sizeof(VarHdr), pwszName, cbName, NULL);
                    if (RT_SUCCESS(rc))
                        rc = RTVfsFileWriteAt(pThis->hVfsBacking, offCur + sizeof(VarHdr) + cbName, pVar->pvData, pVar->cbData, NULL);
                    if (RT_SUCCESS(rc))
                    {
                        offCur += sizeof(VarHdr) + cbName + pVar->cbData;
                        uint64_t offCurAligned = RT_ALIGN_64(offCur, sizeof(uint32_t));
                        if (offCurAligned > offCur)
                        {
                            /* Should be at most 3 bytes to align the next variable to a 32bit boundary. */
                            Assert(offCurAligned - offCur <= 3);
                            uint8_t abFill[3] = { 0xff };
                            rc = RTVfsFileWriteAt(pThis->hVfsBacking, offCur, &abFill[0], offCurAligned - offCur, NULL);
                        }

                        offCur = offCurAligned;
                    }
                }

                RTUtf16Free(pwszName);
            }
        }
    }

    if (RT_SUCCESS(rc))
    {
        /* Fill the remainder with 0xff as it would be the case for a real NAND flash device. */
        uint8_t abFF[512];
        memset(&abFF[0], 0xff, sizeof(abFF));

        uint64_t offStart = offCur;
        uint64_t offEnd   = pThis->offStoreData + pThis->cbVarStore;
        while (   offStart < offEnd
               && RT_SUCCESS(rc))
        {
            size_t cbThisWrite = RT_MIN(sizeof(abFF), offEnd - offStart);
            rc = RTVfsFileWriteAt(pThis->hVfsBacking, offStart, &abFF[0], cbThisWrite, NULL);
            offStart += cbThisWrite;
        }
    }

    return rc;
}


/**
 * Tries to find a variable with the given name.
 *
 * @returns Pointer to the variable if found or NULL otherwise.
 * @param   pThis               The variable store instance.
 * @param   pszName             Name of the variable to look for.
 * @param   pidVar              Where to store the index of the variable, optional.
 */
static PRTEFIVAR rtEfiVarStore_VarGet(PRTEFIVARSTORE pThis, const char *pszName, uint32_t *pidVar)
{
    for (uint32_t i = 0; i < pThis->cVars; i++)
        if (   !pThis->paVars[i].fDeleted
            && !strcmp(pszName, pThis->paVars[i].pszName))
        {
            if (pidVar)
                *pidVar = i;
            return &pThis->paVars[i];
        }

    return NULL;
}


/**
 * Maybe grows the array of variables to hold more entries.
 *
 * @returns IPRT status code.
 * @param   pThis               The variable store instance.
 */
static int rtEfiVarStore_VarMaybeGrowEntries(PRTEFIVARSTORE pThis)
{
    if (pThis->cVars == pThis->cVarsMax)
    {
        /* Grow the variable array. */
        uint32_t cVarsMaxNew = pThis->cVarsMax + 10;
        PRTEFIVAR paVarsNew = (PRTEFIVAR)RTMemRealloc(pThis->paVars, cVarsMaxNew * sizeof(RTEFIVAR));
        if (!paVarsNew)
            return VERR_NO_MEMORY;

        pThis->paVars   = paVarsNew;
        pThis->cVarsMax = cVarsMaxNew;
    }

    return VINF_SUCCESS;
}


/**
 * Add a variable with the given name.
 *
 * @returns Pointer to the entry or NULL if out of memory.
 * @param   pThis               The variable store instance.
 * @param   pszName             Name of the variable to add.
 * @param   pUuid               The UUID of the variable owner.
 * @param   pidVar              Where to store the variable index on success, optional
 */
static PRTEFIVAR rtEfiVarStore_VarAdd(PRTEFIVARSTORE pThis, const char *pszName, PCRTUUID pUuid, uint32_t *pidVar)
{
    Assert(!rtEfiVarStore_VarGet(pThis, pszName, NULL));

    int rc = rtEfiVarStore_VarMaybeGrowEntries(pThis);
    if (RT_SUCCESS(rc))
    {
        PRTEFIVAR pVar = &pThis->paVars[pThis->cVars];
        RT_ZERO(*pVar);

        pVar->pszName = RTStrDup(pszName);
        if (pVar->pszName)
        {
            pVar->pVarStore  = pThis;
            pVar->offVarData = 0;
            pVar->fDeleted   = false;
            pVar->Uuid       = *pUuid;
            RTTimeNow(&pVar->Time);

            rc = rtEfiVarStore_AddVarByGuid(pThis, pUuid, pThis->cVars);
            AssertRC(rc); /** @todo */

            if (pidVar)
                *pidVar = pThis->cVars;
            pThis->cVars++;
            return pVar;
        }
    }

    return NULL;
}


/**
 * Delete the given variable.
 *
 * @returns IPRT status code.
 * @param   pThis               The variable store instance.
 * @param   pVar                The variable.
 */
static int rtEfiVarStore_VarDel(PRTEFIVARSTORE pThis, PRTEFIVAR pVar)
{
    pVar->fDeleted = true;
    if (pVar->pvData)
        RTMemFree(pVar->pvData);
    pVar->pvData = NULL;
    pThis->cbVarData -= sizeof(EFI_AUTH_VAR_HEADER) + pVar->cbData;
    /** @todo Delete from GUID entry. */
    return VINF_SUCCESS;
}


/**
 * Delete the variable with the given index.
 *
 * @returns IPRT status code.
 * @param   pThis               The variable store instance.
 * @param   idVar               The variable index.
 */
static int rtEfiVarStore_VarDelById(PRTEFIVARSTORE pThis, uint32_t idVar)
{
    return rtEfiVarStore_VarDel(pThis, &pThis->paVars[idVar]);
}


/**
 * Delete the variable with the given name.
 *
 * @returns IPRT status code.
 * @param   pThis               The variable store instance.
 * @param   pszName             Name of the variable to delete.
 */
static int rtEfiVarStore_VarDelByName(PRTEFIVARSTORE pThis, const char *pszName)
{
    PRTEFIVAR pVar = rtEfiVarStore_VarGet(pThis, pszName, NULL);
    if (pVar)
        return rtEfiVarStore_VarDel(pThis, pVar);

    return VERR_FILE_NOT_FOUND;
}


/*
 *
 * File operations.
 * File operations.
 * File operations.
 *
 */

/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_Close(void *pvThis)
{
    PRTEFIVARFILE pThis = (PRTEFIVARFILE)pvThis;
    LogFlow(("rtEfiVarStoreFile_Close(%p/%p)\n", pThis, pThis->pVar));
    RT_NOREF(pThis);
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTEFIVARFILE pThis = (PRTEFIVARFILE)pvThis;
    uint64_t cbObject =   pThis->pEntry->cbObject > 0
                        ? pThis->pEntry->cbObject
                        : pThis->pVar->cbData;
    return rtEfiVarStore_QueryInfo(cbObject, false /*fIsDir*/, &pThis->pVar->Time, pObjInfo, enmAddAttr);
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnRead}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_Read(void *pvThis, RTFOFF off, PCRTSGBUF pSgBuf, bool fBlocking, size_t *pcbRead)
{
    PRTEFIVARFILE pThis = (PRTEFIVARFILE)pvThis;
    PRTEFIVAR pVar = pThis->pVar;
    AssertReturn(pSgBuf->cSegs == 1, VERR_INTERNAL_ERROR_3);
    RT_NOREF(fBlocking);

    if (off == -1)
        off = pThis->offFile;
    else
        AssertReturn(off >= 0, VERR_INTERNAL_ERROR_3);

    int rc;
    if (pThis->pEntry->cbObject)
        rc = rtEfiVarStoreFile_ReadMem(pThis, (const uint8_t *)pVar + pThis->pEntry->offObject, pThis->pEntry->cbObject, off, pSgBuf, pcbRead);
    else
    {
        /* Data section. */
        if (!pVar->offVarData)
            rc = rtEfiVarStoreFile_ReadMem(pThis, pVar->pvData, pVar->cbData, off, pSgBuf, pcbRead);
        else
            rc = rtEfiVarStoreFile_ReadFile(pThis, pVar->offVarData, pVar->cbData, off, pSgBuf, pcbRead);
    }

    return rc;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnWrite}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_Write(void *pvThis, RTFOFF off, PCRTSGBUF pSgBuf, bool fBlocking, size_t *pcbWritten)
{
    PRTEFIVARFILE pThis = (PRTEFIVARFILE)pvThis;
    PRTEFIVARSTORE pVarStore = pThis->pVarStore;
    PRTEFIVAR pVar = pThis->pVar;
    AssertReturn(pSgBuf->cSegs == 1, VERR_INTERNAL_ERROR_3);
    RT_NOREF(fBlocking);

    if (pVarStore->fMntFlags & RTVFSMNT_F_READ_ONLY)
        return VERR_WRITE_PROTECT;

    if (off == -1)
        off = pThis->offFile;
    else
        AssertReturn(off >= 0, VERR_INTERNAL_ERROR_3);

    int rc;
    if (pThis->pEntry->cbObject) /* These can't grow. */
        rc = rtEfiVarStoreFile_WriteMem(pThis, (uint8_t *)pVar + pThis->pEntry->offObject, pThis->pEntry->cbObject,
                                        off, pSgBuf, pcbWritten);
    else
    {
        /* Writing data section. */
        rc = rtEfiVarStore_VarReadData(pVar);
        if (RT_SUCCESS(rc))
        {
            if (off + pSgBuf->paSegs[0].cbSeg > pVar->cbData)
                rc = rtEfiVarStore_VarEnsureDataSz(pVar, off + pSgBuf->paSegs[0].cbSeg);
            if (RT_SUCCESS(rc))
                rc = rtEfiVarStoreFile_WriteMem(pThis, pVar->pvData, pVar->cbData, off, pSgBuf, pcbWritten);
        }
    }

    return rc;
}


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


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


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnMode}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_SetMode(void *pvThis, RTFMODE fMode, RTFMODE fMask)
{
    RT_NOREF(pvThis, fMode, fMask);
    return VERR_WRITE_PROTECT;
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnSetTimes}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_SetTimes(void *pvThis, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
                                                    PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
{
    RT_NOREF(pvThis, pAccessTime, pModificationTime, pChangeTime, pBirthTime);
    return VERR_WRITE_PROTECT;
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnSetOwner}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_SetOwner(void *pvThis, RTUID uid, RTGID gid)
{
    RT_NOREF(pvThis, uid, gid);
    return VERR_WRITE_PROTECT;
}


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnSeek}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_Seek(void *pvThis, RTFOFF offSeek, unsigned uMethod, PRTFOFF poffActual)
{
    PRTEFIVARFILE pThis = (PRTEFIVARFILE)pvThis;
    RTFOFF offNew;
    switch (uMethod)
    {
        case RTFILE_SEEK_BEGIN:
            offNew = offSeek;
            break;
        case RTFILE_SEEK_END:
            offNew = pThis->pVar->cbData + offSeek;
            break;
        case RTFILE_SEEK_CURRENT:
            offNew = (RTFOFF)pThis->offFile + offSeek;
            break;
        default:
            return VERR_INVALID_PARAMETER;
    }
    if (offNew >= 0)
    {
        pThis->offFile = offNew;
        *poffActual    = offNew;
        return VINF_SUCCESS;
    }
    return VERR_NEGATIVE_SEEK;
}


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnQuerySize}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_QuerySize(void *pvThis, uint64_t *pcbFile)
{
    PRTEFIVARFILE pThis = (PRTEFIVARFILE)pvThis;
    if (pThis->pEntry->cbObject)
        *pcbFile = pThis->pEntry->cbObject;
    else
        *pcbFile = (uint64_t)pThis->pVar->cbData;
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnSetSize}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_SetSize(void *pvThis, uint64_t cbFile, uint32_t fFlags)
{
    PRTEFIVARFILE pThis = (PRTEFIVARFILE)pvThis;
    PRTEFIVAR pVar = pThis->pVar;
    PRTEFIVARSTORE pVarStore = pThis->pVarStore;

    RT_NOREF(fFlags);

    if (pVarStore->fMntFlags & RTVFSMNT_F_READ_ONLY)
        return VERR_WRITE_PROTECT;

    int rc = rtEfiVarStore_VarReadData(pVar);
    if (RT_SUCCESS(rc))
        rc = rtEfiVarStore_VarEnsureDataSz(pVar, cbFile);

    return rc;
}


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnQueryMaxSize}
 */
static DECLCALLBACK(int) rtEfiVarStoreFile_QueryMaxSize(void *pvThis, uint64_t *pcbMax)
{
    RT_NOREF(pvThis);
    *pcbMax = UINT32_MAX;
    return VINF_SUCCESS;
}


/**
 * EFI variable store file operations.
 */
static const RTVFSFILEOPS g_rtEfiVarStoreFileOps =
{
    { /* Stream */
        { /* Obj */
            RTVFSOBJOPS_VERSION,
            RTVFSOBJTYPE_FILE,
            "EfiVarStore File",
            rtEfiVarStoreFile_Close,
            rtEfiVarStoreFile_QueryInfo,
            NULL,
            RTVFSOBJOPS_VERSION
        },
        RTVFSIOSTREAMOPS_VERSION,
        RTVFSIOSTREAMOPS_FEAT_NO_SG,
        rtEfiVarStoreFile_Read,
        rtEfiVarStoreFile_Write,
        rtEfiVarStoreFile_Flush,
        NULL /*PollOne*/,
        rtEfiVarStoreFile_Tell,
        NULL /*pfnSkip*/,
        NULL /*pfnZeroFill*/,
        RTVFSIOSTREAMOPS_VERSION,
    },
    RTVFSFILEOPS_VERSION,
    0,
    { /* ObjSet */
        RTVFSOBJSETOPS_VERSION,
        RT_UOFFSETOF(RTVFSFILEOPS, ObjSet) - RT_UOFFSETOF(RTVFSFILEOPS, Stream.Obj),
        rtEfiVarStoreFile_SetMode,
        rtEfiVarStoreFile_SetTimes,
        rtEfiVarStoreFile_SetOwner,
        RTVFSOBJSETOPS_VERSION
    },
    rtEfiVarStoreFile_Seek,
    rtEfiVarStoreFile_QuerySize,
    rtEfiVarStoreFile_SetSize,
    rtEfiVarStoreFile_QueryMaxSize,
    RTVFSFILEOPS_VERSION
};


/**
 * Creates a new VFS file from the given regular file inode.
 *
 * @returns IPRT status code.
 * @param   pThis               The ext volume instance.
 * @param   fOpen               Open flags passed.
 * @param   pVar                The variable this file accesses.
 * @param   pEntry              File type entry.
 * @param   phVfsFile           Where to store the VFS file handle on success.
 * @param   pErrInfo            Where to record additional error information on error, optional.
 */
static int rtEfiVarStore_NewFile(PRTEFIVARSTORE pThis, uint64_t fOpen, PRTEFIVAR pVar,
                                 PCRTEFIVARSTOREFILERAWENTRY pEntry, PRTVFSOBJ phVfsObj)
{
    RTVFSFILE hVfsFile;
    PRTEFIVARFILE pNewFile;
    int rc = RTVfsNewFile(&g_rtEfiVarStoreFileOps, sizeof(*pNewFile), fOpen, pThis->hVfsSelf, NIL_RTVFSLOCK,
                          &hVfsFile, (void **)&pNewFile);
    if (RT_SUCCESS(rc))
    {
        pNewFile->pEntry    = pEntry;
        pNewFile->pVarStore = pThis;
        pNewFile->pVar      = pVar;
        pNewFile->offFile   = 0;

        *phVfsObj = RTVfsObjFromFile(hVfsFile);
        RTVfsFileRelease(hVfsFile);
        AssertStmt(*phVfsObj != NIL_RTVFSOBJ, rc = VERR_INTERNAL_ERROR_3);
    }

    return rc;
}



/*
 *
 * Directory instance methods
 * Directory instance methods
 * Directory instance methods
 *
 */

/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_Close(void *pvThis)
{
    PRTEFIVARSTOREDIR pThis = (PRTEFIVARSTOREDIR)pvThis;
    LogFlowFunc(("pThis=%p\n", pThis));
    pThis->pVarStore = NULL;
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTEFIVARSTOREDIR pThis = (PRTEFIVARSTOREDIR)pvThis;
    LogFlowFunc(("\n"));
    return rtEfiVarStore_QueryInfo(1, true /*fIsDir*/, &pThis->Time, pObjInfo, enmAddAttr);
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnMode}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_SetMode(void *pvThis, RTFMODE fMode, RTFMODE fMask)
{
    LogFlowFunc(("\n"));
    RT_NOREF(pvThis, fMode, fMask);
    return VERR_WRITE_PROTECT;
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnSetTimes}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_SetTimes(void *pvThis, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
                                                   PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
{
    LogFlowFunc(("\n"));
    RT_NOREF(pvThis, pAccessTime, pModificationTime, pChangeTime, pBirthTime);
    return VERR_WRITE_PROTECT;
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnSetOwner}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_SetOwner(void *pvThis, RTUID uid, RTGID gid)
{
    LogFlowFunc(("\n"));
    RT_NOREF(pvThis, uid, gid);
    return VERR_WRITE_PROTECT;
}


/**
 * @interface_method_impl{RTVFSDIROPS,pfnOpen}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_Open(void *pvThis, const char *pszEntry, uint64_t fOpen,
                                               uint32_t fFlags, PRTVFSOBJ phVfsObj)
{
    LogFlowFunc(("pszEntry='%s' fOpen=%#RX64 fFlags=%#x\n", pszEntry, fOpen, fFlags));
    PRTEFIVARSTOREDIR pThis     = (PRTEFIVARSTOREDIR)pvThis;
    PRTEFIVARSTORE    pVarStore = pThis->pVarStore;
    int               rc        = VINF_SUCCESS;

    /*
     * Special cases '.' and '.'
     */
    if (pszEntry[0] == '.')
    {
        RTEFIVARSTOREDIRTYPE enmDirTypeNew = RTEFIVARSTOREDIRTYPE_INVALID;
        if (pszEntry[1] == '\0')
            enmDirTypeNew = pThis->pEntry->enmType;
        else if (pszEntry[1] == '.' && pszEntry[2] == '\0')
            enmDirTypeNew = pThis->pEntry->enmParentType;

        if (enmDirTypeNew != RTEFIVARSTOREDIRTYPE_INVALID)
        {
            if (fFlags & RTVFSOBJ_F_OPEN_DIRECTORY)
            {
                if (   (fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_OPEN
                    || (fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_OPEN_CREATE)
                    rc = rtEfiVarStore_NewDirByType(pVarStore, enmDirTypeNew, NULL /*pGuid*/, 0 /*idVar*/, phVfsObj);
                else
                    rc = VERR_ACCESS_DENIED;
            }
            else
                rc = VERR_IS_A_DIRECTORY;
            return rc;
        }
    }

    /*
     * We can create or replace in certain directories.
     */
    if (   (fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_OPEN
        || (fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_OPEN_CREATE
        || (fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_CREATE
        || (fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_CREATE_REPLACE)
    { /* likely */ }
    else
        return VERR_WRITE_PROTECT;

    switch (pThis->pEntry->enmType)
    {
        case RTEFIVARSTOREDIRTYPE_ROOT:
        {
            if (!strcmp(pszEntry, "by-name"))
                return rtEfiVarStore_NewDirByType(pVarStore, RTEFIVARSTOREDIRTYPE_BY_NAME,
                                                  NULL /*pGuid*/, 0 /*idVar*/, phVfsObj);
            else if (!strcmp(pszEntry, "by-uuid"))
                return rtEfiVarStore_NewDirByType(pVarStore, RTEFIVARSTOREDIRTYPE_BY_GUID,
                                                  NULL /*pGuid*/, 0 /*idVar*/, phVfsObj);
            else if (!strcmp(pszEntry, "raw"))
                return rtEfiVarStore_NewDirByType(pVarStore, RTEFIVARSTOREDIRTYPE_RAW,
                                                  NULL /*pGuid*/, 0 /*idVar*/, phVfsObj);
            else
                rc = VERR_FILE_NOT_FOUND;
            break;
        }
        case RTEFIVARSTOREDIRTYPE_GUID: /** @todo This looks through all variables, not only the ones with the GUID. */
        case RTEFIVARSTOREDIRTYPE_BY_NAME:
        case RTEFIVARSTOREDIRTYPE_RAW:
        {
            /* Look for the name. */
            uint32_t idVar = 0;
            PRTEFIVAR pVar = rtEfiVarStore_VarGet(pVarStore, pszEntry, &idVar);
            if (   !pVar
                && (   (fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_OPEN_CREATE
                    || (fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_CREATE
                    || (fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_CREATE_REPLACE))
            {
                if (pThis->pEntry->enmType == RTEFIVARSTOREDIRTYPE_GUID)
                    pVar = rtEfiVarStore_VarAdd(pVarStore, pszEntry, &pThis->pGuid->Uuid, &idVar);
                else
                {
                    RTUUID UuidNull;
                    RTUuidClear(&UuidNull);
                    pVar = rtEfiVarStore_VarAdd(pVarStore, pszEntry, &UuidNull, &idVar);
                }

                if (!pVar)
                {
                    rc = VERR_NO_MEMORY;
                    break;
                }
            }

            if (pVar)
            {
                if (pThis->pEntry->enmType == RTEFIVARSTOREDIRTYPE_RAW)
                    return rtEfiVarStore_NewDirByType(pVarStore, RTEFIVARSTOREDIRTYPE_RAW_ENTRY,
                                                      NULL /*pGuid*/, idVar, phVfsObj);
                else
                    return rtEfiVarStore_NewFile(pVarStore, fOpen, pVar,
                                                 &g_aRawFiles[RTEFIVARSTORE_FILE_ENTRY_DATA], phVfsObj);
            }

            rc = VERR_FILE_NOT_FOUND;
            break;
        }
        case RTEFIVARSTOREDIRTYPE_BY_GUID:
        {
            /* Look for the name. */
            for (uint32_t i = 0; i < pVarStore->cGuids; i++)
            {
                PRTEFIGUID pGuid = &pVarStore->paGuids[i];
                char szUuid[RTUUID_STR_LENGTH];
                rc = RTUuidToStr(&pGuid->Uuid, szUuid, sizeof(szUuid));
                AssertRC(rc);

                if (!strcmp(pszEntry, szUuid))
                    return rtEfiVarStore_NewDirByType(pVarStore, RTEFIVARSTOREDIRTYPE_GUID,
                                                      pGuid, 0 /*idVar*/, phVfsObj);
            }

            rc = VERR_FILE_NOT_FOUND;
            break;
        }
        case RTEFIVARSTOREDIRTYPE_RAW_ENTRY:
        {
            /* Look for the name. */
            for (uint32_t i = 0; i < RT_ELEMENTS(g_aRawFiles); i++)
                if (!strcmp(pszEntry, g_aRawFiles[i].pszName))
                    return rtEfiVarStore_NewFile(pVarStore, fOpen, &pVarStore->paVars[pThis->idVar],
                                                 &g_aRawFiles[i], phVfsObj);

            rc = VERR_FILE_NOT_FOUND;
            break;
        }
        case RTEFIVARSTOREDIRTYPE_INVALID:
        default:
            AssertFailedReturn(VERR_INTERNAL_ERROR_3);
    }

    LogFlow(("rtEfiVarStoreDir_Open(%s): returns %Rrc\n", pszEntry, rc));
    return rc;
}


/**
 * @interface_method_impl{RTVFSDIROPS,pfnCreateDir}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_CreateDir(void *pvThis, const char *pszSubDir, RTFMODE fMode, PRTVFSDIR phVfsDir)
{
    PRTEFIVARSTOREDIR pThis     = (PRTEFIVARSTOREDIR)pvThis;
    PRTEFIVARSTORE    pVarStore = pThis->pVarStore;
    LogFlowFunc(("\n"));

    RT_NOREF(fMode, phVfsDir);

    if (pVarStore->fMntFlags & RTVFSMNT_F_READ_ONLY)
        return VERR_WRITE_PROTECT;

    /* We support creating directories only for GUIDs and RAW variable entries. */
    int rc = VINF_SUCCESS;
    if (pThis->pEntry->enmType == RTEFIVARSTOREDIRTYPE_BY_GUID)
    {
        RTUUID Uuid;
        rc = RTUuidFromStr(&Uuid, pszSubDir);
        if (RT_FAILURE(rc))
            return VERR_NOT_SUPPORTED;

        PRTEFIGUID pGuid = rtEfiVarStore_GetGuid(pVarStore, &Uuid);
        if (pGuid)
            return VERR_ALREADY_EXISTS;

        pGuid = rtEfiVarStore_AddGuid(pVarStore, &Uuid);
        if (!pGuid)
            return VERR_NO_MEMORY;
    }
    else if (pThis->pEntry->enmType == RTEFIVARSTOREDIRTYPE_RAW)
    {
        PRTEFIVAR pVar = rtEfiVarStore_VarGet(pVarStore, pszSubDir, NULL /*pidVar*/);
        if (!pVar)
        {
            if (sizeof(EFI_AUTH_VAR_HEADER) < pVarStore->cbVarStore - pVarStore->cbVarData)
            {
                uint32_t idVar = 0;
                RTUUID UuidNull;
                RTUuidClear(&UuidNull);

                pVar = rtEfiVarStore_VarAdd(pVarStore, pszSubDir, &UuidNull, &idVar);
                if (pVar)
                    pVarStore->cbVarData += sizeof(EFI_AUTH_VAR_HEADER);
                else
                    rc = VERR_NO_MEMORY;
            }
            else
                rc = VERR_DISK_FULL;
        }
        else
            rc = VERR_ALREADY_EXISTS;
    }
    else
        rc = VERR_NOT_SUPPORTED;

    return rc;
}


/**
 * @interface_method_impl{RTVFSDIROPS,pfnOpenSymlink}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_OpenSymlink(void *pvThis, const char *pszSymlink, PRTVFSSYMLINK phVfsSymlink)
{
    RT_NOREF(pvThis, pszSymlink, phVfsSymlink);
    LogFlowFunc(("\n"));
    return VERR_NOT_SUPPORTED;
}


/**
 * @interface_method_impl{RTVFSDIROPS,pfnCreateSymlink}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_CreateSymlink(void *pvThis, const char *pszSymlink, const char *pszTarget,
                                                        RTSYMLINKTYPE enmType, PRTVFSSYMLINK phVfsSymlink)
{
    RT_NOREF(pvThis, pszSymlink, pszTarget, enmType, phVfsSymlink);
    LogFlowFunc(("\n"));
    return VERR_WRITE_PROTECT;
}


/**
 * @interface_method_impl{RTVFSDIROPS,pfnUnlinkEntry}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_UnlinkEntry(void *pvThis, const char *pszEntry, RTFMODE fType)
{
    PRTEFIVARSTOREDIR pThis     = (PRTEFIVARSTOREDIR)pvThis;
    PRTEFIVARSTORE    pVarStore = pThis->pVarStore;
    LogFlowFunc(("\n"));

    RT_NOREF(fType);

    if (pVarStore->fMntFlags & RTVFSMNT_F_READ_ONLY)
        return VERR_WRITE_PROTECT;

    if (   pThis->pEntry->enmType == RTEFIVARSTOREDIRTYPE_RAW
        || pThis->pEntry->enmType == RTEFIVARSTOREDIRTYPE_BY_NAME
        || pThis->pEntry->enmType == RTEFIVARSTOREDIRTYPE_GUID)
        return rtEfiVarStore_VarDelByName(pVarStore, pszEntry);
    else if (pThis->pEntry->enmType == RTEFIVARSTOREDIRTYPE_BY_GUID)
    {
        /* Look for the name. */
        for (uint32_t i = 0; i < pVarStore->cGuids; i++)
        {
            PRTEFIGUID pGuid = &pVarStore->paGuids[i];
            char szUuid[RTUUID_STR_LENGTH];
            int rc = RTUuidToStr(&pGuid->Uuid, szUuid, sizeof(szUuid));
            AssertRC(rc); RT_NOREF(rc);

            if (!strcmp(pszEntry, szUuid))
            {
                for (uint32_t iVar = 0; iVar < pGuid->cVars; iVar++)
                    rtEfiVarStore_VarDelById(pVarStore, pGuid->paidxVars[iVar]);

                if (pGuid->paidxVars)
                    RTMemFree(pGuid->paidxVars);
                pGuid->paidxVars = NULL;
                pGuid->cVars     = 0;
                pGuid->cVarsMax  = 0;
                RTUuidClear(&pGuid->Uuid);
                return VINF_SUCCESS;
            }
        }

        return VERR_FILE_NOT_FOUND;
    }

    return VERR_NOT_SUPPORTED;
}


/**
 * @interface_method_impl{RTVFSDIROPS,pfnRenameEntry}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_RenameEntry(void *pvThis, const char *pszEntry, RTFMODE fType, const char *pszNewName)
{
    RT_NOREF(pvThis, pszEntry, fType, pszNewName);
    LogFlowFunc(("\n"));
    return VERR_WRITE_PROTECT;
}


/**
 * @interface_method_impl{RTVFSDIROPS,pfnRewindDir}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_RewindDir(void *pvThis)
{
    PRTEFIVARSTOREDIR pThis = (PRTEFIVARSTOREDIR)pvThis;
    LogFlowFunc(("\n"));

    pThis->idxNext = 0;
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSDIROPS,pfnReadDir}
 */
static DECLCALLBACK(int) rtEfiVarStoreDir_ReadDir(void *pvThis, PRTDIRENTRYEX pDirEntry, size_t *pcbDirEntry,
                                                  RTFSOBJATTRADD enmAddAttr)
{
    PRTEFIVARSTOREDIR pThis = (PRTEFIVARSTOREDIR)pvThis;
    PRTEFIVARSTORE    pVarStore = pThis->pVarStore;
    LogFlowFunc(("\n"));

    if (pThis->fNoMoreFiles)
        return VERR_NO_MORE_FILES;

    int        rc       = VINF_SUCCESS;
    char       aszUuid[RTUUID_STR_LENGTH];
    const char *pszName = NULL;
    size_t     cbName   = 0;
    uint64_t   cbObject = 0;
    bool       fIsDir   = false;
    bool       fNoMoreFiles = false;
    RTTIMESPEC   Time;
    PCRTTIMESPEC pTimeSpec = &Time;
    RTTimeNow(&Time);

    switch (pThis->pEntry->enmType)
    {
        case RTEFIVARSTOREDIRTYPE_ROOT:
        {
            if (pThis->idxNext == 0)
            {
                pszName  = "by-name";
                cbName   = sizeof("by-name");
                cbObject = 1;
                fIsDir   = true;
            }
            else if (pThis->idxNext == 1)
            {
                pszName  = "by-uuid";
                cbName   = sizeof("by-uuid");
                cbObject = 1;
                fIsDir   = true;
            }
            else if (pThis->idxNext == 2)
            {
                pszName  = "raw";
                cbName   = sizeof("raw");
                cbObject = 1;
                fIsDir   = true;
                fNoMoreFiles = true;
            }
            break;
        }
        case RTEFIVARSTOREDIRTYPE_BY_NAME:
        case RTEFIVARSTOREDIRTYPE_RAW:
        {
            PRTEFIVAR pVar = &pVarStore->paVars[pThis->idxNext];
            if (pThis->idxNext + 1 == pVarStore->cVars)
                fNoMoreFiles = true;
            pszName  = pVar->pszName;
            cbName   = strlen(pszName) + 1;
            cbObject = pVar->cbData;
            pTimeSpec = &pVar->Time;
            if (pThis->pEntry->enmType == RTEFIVARSTOREDIRTYPE_RAW)
                fIsDir = true;
            break;
        }
        case RTEFIVARSTOREDIRTYPE_BY_GUID:
        {
            PRTEFIGUID pGuid = &pVarStore->paGuids[pThis->idxNext];
            if (pThis->idxNext + 1 == pVarStore->cGuids)
                fNoMoreFiles = true;
            pszName  = &aszUuid[0];
            cbName   = sizeof(aszUuid);
            cbObject = 1;
            rc = RTUuidToStr(&pGuid->Uuid, &aszUuid[0], cbName);
            AssertRC(rc);
            break;
        }
        case RTEFIVARSTOREDIRTYPE_GUID:
        {
            PRTEFIGUID pGuid = pThis->pGuid;
            uint32_t   idVar = pGuid->paidxVars[pThis->idxNext];
            PRTEFIVAR  pVar  = &pVarStore->paVars[idVar];
            if (pThis->idxNext + 1 == pGuid->cVars)
                fNoMoreFiles = true;
            pszName  = pVar->pszName;
            cbName   = strlen(pszName) + 1;
            cbObject = pVar->cbData;
            pTimeSpec = &pVar->Time;
            break;
        }
        case RTEFIVARSTOREDIRTYPE_RAW_ENTRY:
        {
            PCRTEFIVARSTOREFILERAWENTRY pEntry = &g_aRawFiles[pThis->idxNext];
            PRTEFIVAR                   pVar   = &pVarStore->paVars[pThis->idVar];

            if (pThis->idxNext + 1 == RT_ELEMENTS(g_aRawFiles))
                fNoMoreFiles = true;
            pszName  = pEntry->pszName;
            cbName   = strlen(pszName) + 1;
            cbObject = pEntry->cbObject;
            if (!cbObject)
                cbObject = pVar->cbData;
            pTimeSpec = &pVar->Time;
            break;
        }
        case RTEFIVARSTOREDIRTYPE_INVALID:
        default:
            AssertFailedReturn(VERR_INTERNAL_ERROR_3);
    }

    if (cbName <= 255)
    {
        size_t const cbDirEntry = *pcbDirEntry;

        *pcbDirEntry = RT_UOFFSETOF_DYN(RTDIRENTRYEX, szName[cbName + 2]);
        if (*pcbDirEntry <= cbDirEntry)
        {
            memcpy(&pDirEntry->szName[0], pszName, cbName);
            pDirEntry->szName[cbName] = '\0';
            pDirEntry->cbName         = (uint16_t)cbName;
            rc = rtEfiVarStore_QueryInfo(cbObject, fIsDir, &Time, &pDirEntry->Info, enmAddAttr);
            if (RT_SUCCESS(rc))
            {
                pThis->fNoMoreFiles = fNoMoreFiles;
                pThis->idxNext++;
                return VINF_SUCCESS;
            }
        }
        else
            rc = VERR_BUFFER_OVERFLOW;
    }
    else
        rc = VERR_FILENAME_TOO_LONG;
    return rc;
}


/**
 * EFI variable store directory operations.
 */
static const RTVFSDIROPS g_rtEfiVarStoreDirOps =
{
    { /* Obj */
        RTVFSOBJOPS_VERSION,
        RTVFSOBJTYPE_DIR,
        "EfiVarStore Dir",
        rtEfiVarStoreDir_Close,
        rtEfiVarStoreDir_QueryInfo,
        NULL,
        RTVFSOBJOPS_VERSION
    },
    RTVFSDIROPS_VERSION,
    0,
    { /* ObjSet */
        RTVFSOBJSETOPS_VERSION,
        RT_UOFFSETOF(RTVFSDIROPS, ObjSet) - RT_UOFFSETOF(RTVFSDIROPS, Obj),
        rtEfiVarStoreDir_SetMode,
        rtEfiVarStoreDir_SetTimes,
        rtEfiVarStoreDir_SetOwner,
        RTVFSOBJSETOPS_VERSION
    },
    rtEfiVarStoreDir_Open,
    NULL /* pfnFollowAbsoluteSymlink */,
    NULL /* pfnOpenFile */,
    NULL /* pfnOpenDir */,
    rtEfiVarStoreDir_CreateDir,
    rtEfiVarStoreDir_OpenSymlink,
    rtEfiVarStoreDir_CreateSymlink,
    NULL /* pfnQueryEntryInfo */,
    rtEfiVarStoreDir_UnlinkEntry,
    rtEfiVarStoreDir_RenameEntry,
    rtEfiVarStoreDir_RewindDir,
    rtEfiVarStoreDir_ReadDir,
    RTVFSDIROPS_VERSION,
};


static int rtEfiVarStore_NewDirByType(PRTEFIVARSTORE pThis, RTEFIVARSTOREDIRTYPE enmDirType,
                                      PRTEFIGUID pGuid, uint32_t idVar, PRTVFSOBJ phVfsObj)
{
    RTVFSDIR hVfsDir;
    PRTEFIVARSTOREDIR pDir;
    int rc = RTVfsNewDir(&g_rtEfiVarStoreDirOps, sizeof(*pDir), 0 /*fFlags*/, pThis->hVfsSelf, NIL_RTVFSLOCK,
                         &hVfsDir, (void **)&pDir);
    if (RT_SUCCESS(rc))
    {
        PCRTEFIVARSTOREDIRENTRY pEntry = NULL;

        for (uint32_t i = 0; i < RT_ELEMENTS(g_aDirs); i++)
            if (g_aDirs[i].enmType == enmDirType)
            {
                pEntry = &g_aDirs[i];
                break;
            }

        AssertPtr(pEntry);
        pDir->idxNext   = 0;
        pDir->pEntry    = pEntry;
        pDir->pVarStore = pThis;
        pDir->pGuid     = pGuid;
        pDir->idVar     = idVar;
        RTTimeNow(&pDir->Time);

        *phVfsObj = RTVfsObjFromDir(hVfsDir);
        RTVfsDirRelease(hVfsDir);
        AssertStmt(*phVfsObj != NIL_RTVFSOBJ, rc = VERR_INTERNAL_ERROR_3);
    }

    return rc;
}


/*
 *
 * Volume level code.
 * Volume level code.
 * Volume level code.
 *
 */

/**
 * @interface_method_impl{RTVFSOBJOPS::Obj,pfnClose}
 */
static DECLCALLBACK(int) rtEfiVarStore_Close(void *pvThis)
{
    PRTEFIVARSTORE pThis = (PRTEFIVARSTORE)pvThis;

    /* Write the variable store if in read/write mode. */
    if (!(pThis->fMntFlags & RTVFSMNT_F_READ_ONLY))
    {
        int rc = rtEfiVarStore_Flush(pThis);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * Backing file and handles.
     */
    RTVfsFileRelease(pThis->hVfsBacking);
    pThis->hVfsBacking = NIL_RTVFSFILE;
    pThis->hVfsSelf    = NIL_RTVFS;
    if (pThis->paVars)
    {
        for (uint32_t i = 0; i < pThis->cVars; i++)
        {
            RTStrFree(pThis->paVars[i].pszName);
            if (pThis->paVars[i].pvData)
                RTMemFree(pThis->paVars[i].pvData);
        }

        RTMemFree(pThis->paVars);
        pThis->paVars   = NULL;
        pThis->cVars    = 0;
        pThis->cVarsMax = 0;
    }

    if (pThis->paGuids)
    {
        for (uint32_t i = 0; i < pThis->cGuids; i++)
        {
            PRTEFIGUID pGuid = &pThis->paGuids[i];

            if (pGuid->paidxVars)
            {
                RTMemFree(pGuid->paidxVars);
                pGuid->paidxVars = NULL;
            }
        }

        RTMemFree(pThis->paGuids);
        pThis->paGuids = NULL;
    }

    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSOBJOPS::Obj,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtEfiVarStore_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    RT_NOREF(pvThis, pObjInfo, enmAddAttr);
    return VERR_WRONG_TYPE;
}


/**
 * @interface_method_impl{RTVFSOBJOPS::Obj,pfnOpenRoot}
 */
static DECLCALLBACK(int) rtEfiVarStore_OpenRoot(void *pvThis, PRTVFSDIR phVfsDir)
{
    PRTEFIVARSTORE pThis = (PRTEFIVARSTORE)pvThis;
    RTVFSOBJ hVfsObj;
    int rc = rtEfiVarStore_NewDirByType(pThis, RTEFIVARSTOREDIRTYPE_ROOT,
                                        NULL /*pGuid*/, 0 /*idVar*/, &hVfsObj);
    if (RT_SUCCESS(rc))
    {
        *phVfsDir = RTVfsObjToDir(hVfsObj);
        RTVfsObjRelease(hVfsObj);
    }

    LogFlowFunc(("returns %Rrc\n", rc));
    return rc;
}


DECL_HIDDEN_CONST(const RTVFSOPS) g_rtEfiVarStoreOps =
{
    /* .Obj = */
    {
        /* .uVersion = */       RTVFSOBJOPS_VERSION,
        /* .enmType = */        RTVFSOBJTYPE_VFS,
        /* .pszName = */        "EfiVarStore",
        /* .pfnClose = */       rtEfiVarStore_Close,
        /* .pfnQueryInfo = */   rtEfiVarStore_QueryInfo,
        /* .pfnQueryInfoEx = */ NULL,
        /* .uEndMarker = */     RTVFSOBJOPS_VERSION
    },
    /* .uVersion = */           RTVFSOPS_VERSION,
    /* .fFeatures = */          0,
    /* .pfnOpenRoot = */        rtEfiVarStore_OpenRoot,
    /* .pfnQueryRangeState = */ NULL,
    /* .uEndMarker = */         RTVFSOPS_VERSION
};


/**
 * Validates the given firmware header.
 *
 * @returns true if the given header is considered valid, flse otherwise.
 * @param   pThis               The EFI variable store instance.
 * @param   pFvHdr              The firmware volume header to validate.
 * @param   poffData            The offset into the backing where the data area begins.
 * @param   pErrInfo            Where to return additional error info.
 */
static int rtEfiVarStoreFvHdr_Validate(PRTEFIVARSTORE pThis, PCEFI_FIRMWARE_VOLUME_HEADER pFvHdr, uint64_t *poffData,
                                       PRTERRINFO pErrInfo)
{
#ifdef LOG_ENABLED
    rtEfiVarStoreFvHdr_Log(pFvHdr);
#endif

    EFI_GUID GuidNvData = EFI_VARSTORE_FILESYSTEM_GUID;
    if (memcmp(&pFvHdr->GuidFilesystem, &GuidNvData, sizeof(GuidNvData)))
        return RTERRINFO_LOG_SET(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Filesystem GUID doesn't indicate a variable store");
    if (RT_LE2H_U64(pFvHdr->cbFv) > pThis->cbBacking)
        return RTERRINFO_LOG_SET(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Firmware volume length exceeds size of backing storage (truncated file?)");
    /* Signature was already verfied by caller. */
    /** @todo Check attributes. */
    if (pFvHdr->bRsvd != 0)
        return RTERRINFO_LOG_SET(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Reserved field of header is not 0");
    if (pFvHdr->bRevision != EFI_FIRMWARE_VOLUME_HEADER_REVISION)
        return RTERRINFO_LOG_SET(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Unexpected revision of the firmware volume header");
    if (RT_LE2H_U16(pFvHdr->offExtHdr) != 0)
        return RTERRINFO_LOG_SET(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Firmware volume header contains unsupported extended headers");

    /* Start calculating the checksum of the main header. */
    uint16_t u16Chksum = 0;
    const uint16_t *pu16 = (const uint16_t *)pFvHdr;
    while (pu16 < (const uint16_t *)pFvHdr + (sizeof(*pFvHdr) / sizeof(uint16_t)))
        u16Chksum += RT_LE2H_U16(*pu16++);

    /* Read in the block map and verify it as well. */
    uint64_t cbFvVol = 0;
    uint64_t cbFvHdr = sizeof(*pFvHdr);
    uint64_t offBlockMap = sizeof(*pFvHdr);
    for (;;)
    {
        EFI_FW_BLOCK_MAP BlockMap;
        int rc = RTVfsFileReadAt(pThis->hVfsBacking, offBlockMap, &BlockMap, sizeof(BlockMap), NULL);
        if (RT_FAILURE(rc))
            return RTERRINFO_LOG_SET_F(pErrInfo, rc, "Reading block map entry from %#RX64 failed", offBlockMap);

        cbFvHdr     += sizeof(BlockMap);
        offBlockMap += sizeof(BlockMap);

        /* A zero entry denotes the end. */
        if (   !RT_LE2H_U32(BlockMap.cBlocks)
            && !RT_LE2H_U32(BlockMap.cbBlock))
            break;

        cbFvVol += RT_LE2H_U32(BlockMap.cBlocks) * RT_LE2H_U32(BlockMap.cbBlock);

        pu16 = (const uint16_t *)&BlockMap;
        while (pu16 < (const uint16_t *)&BlockMap + (sizeof(BlockMap) / sizeof(uint16_t)))
            u16Chksum += RT_LE2H_U16(*pu16++);
    }

    *poffData = offBlockMap;

    if (u16Chksum)
        return RTERRINFO_LOG_SET(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Firmware volume header has incorrect checksum");
    if (RT_LE2H_U16(pFvHdr->cbFvHdr) != cbFvHdr)
        return RTERRINFO_LOG_SET(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Unexpected firmware volume header size");

    return VINF_SUCCESS;
}


/**
 * Validates the given variable store header.
 *
 * @returns true if the given header is considered valid, false otherwise.
 * @param   pThis               The EFI variable store instance.
 * @param   pHdr                The variable store header to validate.
 * @param   pfAuth              Where to store whether the variable store uses authenticated variables or not.
 * @param   pErrInfo            Where to return additional error info.
 */
static int rtEfiVarStoreHdr_Validate(PRTEFIVARSTORE pThis, PCEFI_VARSTORE_HEADER pHdr, bool *pfAuth, PRTERRINFO pErrInfo)
{
#ifdef LOG_ENABLED
    rtEfiVarStoreHdr_Log(pHdr);
#endif

    EFI_GUID GuidVarStoreAuth = EFI_VARSTORE_HEADER_GUID_AUTHENTICATED_VARIABLE;
    EFI_GUID GuidVarStore = EFI_VARSTORE_HEADER_GUID_VARIABLE;
    if (!memcmp(&pHdr->GuidVarStore, &GuidVarStoreAuth, sizeof(GuidVarStoreAuth)))
        *pfAuth = true;
    else if (!memcmp(&pHdr->GuidVarStore, &GuidVarStore, sizeof(GuidVarStore)))
        *pfAuth = false;
    else
        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT,
                                   "Variable store GUID doesn't indicate a variable store (%RTuuid)", pHdr->GuidVarStore);
    if (RT_LE2H_U32(pHdr->cbVarStore) >= pThis->cbBacking)
        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT,
                                   "Variable store length exceeds size of backing storage (truncated file?): %#RX32, max %#RX64",
                                   RT_LE2H_U32(pHdr->cbVarStore), pThis->cbBacking);
    if (pHdr->bFmt != EFI_VARSTORE_HEADER_FMT_FORMATTED)
        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Variable store is not formatted (%#x)", pHdr->bFmt);
    if (pHdr->bState != EFI_VARSTORE_HEADER_STATE_HEALTHY)
        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Variable store is not healthy (%#x)", pHdr->bState);

    return VINF_SUCCESS;
}


/**
 * Validates the given authenticate variable header.
 *
 * @returns true if the given header is considered valid, false otherwise.
 * @param   pThis               The EFI variable store instance.
 * @param   pVarHdr             The variable header to validate.
 * @param   offVar              Offset of the authenticated variable header.
 * @param   pErrInfo            Where to return additional error info.
 */
static int rtEfiVarStoreAuthVar_Validate(PRTEFIVARSTORE pThis, PCEFI_AUTH_VAR_HEADER pVarHdr, uint64_t offVar, PRTERRINFO pErrInfo)
{
#ifdef LOG_ENABLED
    rtEfiVarStoreAuthVarHdr_Log(pVarHdr, offVar);
#endif

    uint32_t cbName = RT_LE2H_U32(pVarHdr->cbName);
    uint32_t cbData = RT_LE2H_U32(pVarHdr->cbData);
    uint64_t cbVarMax = pThis->cbBacking - offVar - sizeof(*pVarHdr);
    if (   cbVarMax <= cbName
        || cbVarMax - cbName <= cbData)
        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Variable exceeds remaining space in store (cbName=%u cbData=%u cbVarMax=%llu)",
                                   cbName, cbData, cbVarMax);

    return VINF_SUCCESS;
}


/**
 * Loads the authenticated variable at the given offset.
 *
 * @returns IPRT status code.
 * @retval  VERR_EOF if the end of the store was reached.
 * @param   pThis               The EFI variable store instance.
 * @param   offVar              Offset of the variable to load.
 * @param   poffVarEnd          Where to store the offset pointing to the end of the variable.
 * @param   fIgnoreDelVars      Flag whether to ignore deleted variables.
 * @param   pErrInfo            Where to return additional error info.
 */
static int rtEfiVarStoreLoadAuthVar(PRTEFIVARSTORE pThis, uint64_t offVar, uint64_t *poffVarEnd,
                                    bool fIgnoreDelVars, PRTERRINFO pErrInfo)
{
    EFI_AUTH_VAR_HEADER VarHdr;
    int rc = RTVfsFileReadAt(pThis->hVfsBacking, offVar, &VarHdr, sizeof(VarHdr), NULL);
    if (RT_FAILURE(rc))
        return rc;

    rc = rtEfiVarStoreAuthVar_Validate(pThis, &VarHdr, offVar, pErrInfo);
    if (RT_FAILURE(rc))
        return rc;

    if (poffVarEnd)
        *poffVarEnd = offVar + sizeof(VarHdr) + RT_LE2H_U32(VarHdr.cbData) + RT_LE2H_U32(VarHdr.cbName);

    /* Only add complete variables or deleted variables when requested. */
    if (   (   fIgnoreDelVars
            && VarHdr.bState != EFI_AUTH_VAR_HEADER_STATE_ADDED)
        || VarHdr.bState == EFI_AUTH_VAR_HEADER_STATE_HDR_VALID_ONLY)
        return VINF_SUCCESS;

    pThis->cbVarData += sizeof(VarHdr) + RT_LE2H_U32(VarHdr.cbData) + RT_LE2H_U32(VarHdr.cbName);

    RTUTF16 awchName[128]; RT_ZERO(awchName);
    if (RT_LE2H_U32(VarHdr.cbName) > sizeof(awchName) - sizeof(RTUTF16))
        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_VFS_UNSUPPORTED_FORMAT, "Variable name is too long (%llu vs. %llu)\n",
                                   RT_LE2H_U32(VarHdr.cbName), sizeof(awchName));

    rc = RTVfsFileReadAt(pThis->hVfsBacking, offVar + sizeof(VarHdr), &awchName[0], RT_LE2H_U32(VarHdr.cbName), NULL);
    if (RT_FAILURE(rc))
        return rc;

    Log2(("Variable name '%ls'\n", &awchName[0]));
    rc = rtEfiVarStore_VarMaybeGrowEntries(pThis);
    if (RT_FAILURE(rc))
        return rc;

    PRTEFIVAR pVar = &pThis->paVars[pThis->cVars++];
    pVar->pVarStore  = pThis;
    if (RT_LE2H_U32(VarHdr.cbData))
        pVar->offVarData = offVar + sizeof(VarHdr) + RT_LE2H_U32(VarHdr.cbName);
    else
        pVar->offVarData = 0;
    pVar->fAttr      = RT_LE2H_U32(VarHdr.fAttr);
    pVar->cMonotonic = RT_LE2H_U64(VarHdr.cMonotonic);
    pVar->idPubKey   = RT_LE2H_U32(VarHdr.idPubKey);
    pVar->cbData     = RT_LE2H_U32(VarHdr.cbData);
    pVar->pvData     = NULL;
    pVar->fDeleted   = false;
    memcpy(&pVar->EfiTimestamp, &VarHdr.Timestamp, sizeof(VarHdr.Timestamp));

    if (VarHdr.Timestamp.u8Month)
        RTEfiTimeToTimeSpec(&pVar->Time, &VarHdr.Timestamp);
    else
        RTTimeNow(&pVar->Time);

    RTEfiGuidToUuid(&pVar->Uuid, &VarHdr.GuidVendor);

    rc = RTUtf16ToUtf8(&awchName[0], &pVar->pszName);
    if (RT_FAILURE(rc))
        pThis->cVars--;

    rc = rtEfiVarStore_AddVarByGuid(pThis, &pVar->Uuid, pThis->cVars - 1);

    return rc;
}


/**
 * Looks for the next variable starting at the given offset.
 *
 * @returns IPRT status code.
 * @retval  VERR_EOF if the end of the store was reached.
 * @param   pThis               The EFI variable store instance.
 * @param   offStart            Where in the image to start looking.
 * @param   poffVar             Where to store the start of the next variable if found.
 */
static int rtEfiVarStoreFindVar(PRTEFIVARSTORE pThis, uint64_t offStart, uint64_t *poffVar)
{
    /* Try to find the ID indicating a variable start by loading data in chunks. */
    uint64_t offEnd = pThis->offStoreData + pThis->cbVarStore;
    while (offStart < offEnd)
    {
        uint16_t au16Tmp[_1K / sizeof(uint16_t)];
        size_t cbThisRead = RT_MIN(sizeof(au16Tmp), offEnd - offStart);
        int rc = RTVfsFileReadAt(pThis->hVfsBacking, offStart, &au16Tmp[0], sizeof(au16Tmp), NULL);
        if (RT_FAILURE(rc))
            return rc;

        for (uint32_t i = 0; i < RT_ELEMENTS(au16Tmp); i++)
            if (RT_LE2H_U16(au16Tmp[i]) == EFI_AUTH_VAR_HEADER_START)
            {
                *poffVar = offStart + i * sizeof(uint16_t);
                return VINF_SUCCESS;
            }

        offStart += cbThisRead;
    }

    return VERR_EOF;
}


/**
 * Loads and parses the superblock of the filesystem.
 *
 * @returns IPRT status code.
 * @param   pThis               The EFI variable store instance.
 * @param   pErrInfo            Where to return additional error info.
 */
static int rtEfiVarStoreLoad(PRTEFIVARSTORE pThis, PRTERRINFO pErrInfo)
{
    EFI_FIRMWARE_VOLUME_HEADER FvHdr;
    int rc = RTVfsFileReadAt(pThis->hVfsBacking, 0, &FvHdr, sizeof(FvHdr), NULL);
    if (RT_FAILURE(rc))
        return RTERRINFO_LOG_SET(pErrInfo, rc, "Error reading firmware volume header");

    /* Validate the signature. */
    if (RT_LE2H_U32(FvHdr.u32Signature) != EFI_FIRMWARE_VOLUME_HEADER_SIGNATURE)
        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_VFS_UNKNOWN_FORMAT, "Not a EFI variable store - Signature mismatch: %RX32", RT_LE2H_U16(FvHdr.u32Signature));

    uint64_t offData = 0;
    rc = rtEfiVarStoreFvHdr_Validate(pThis, &FvHdr, &offData, pErrInfo);
    if (RT_FAILURE(rc))
        return rc;

    EFI_VARSTORE_HEADER StoreHdr;
    rc = RTVfsFileReadAt(pThis->hVfsBacking, offData, &StoreHdr, sizeof(StoreHdr), NULL);
    if (RT_FAILURE(rc))
        return RTERRINFO_LOG_SET(pErrInfo, rc, "Error reading variable store header");

    rc = rtEfiVarStoreHdr_Validate(pThis, &StoreHdr, &pThis->fAuth, pErrInfo);
    if (RT_FAILURE(rc))
        return rc;

    pThis->offStoreData = offData + sizeof(StoreHdr);
    pThis->cbVarStore   = RT_LE2H_U32(StoreHdr.cbVarStore) - sizeof(StoreHdr);

    /* Go over variables and set up the pointers. */
    offData = pThis->offStoreData;
    for (;;)
    {
        uint64_t offVar = 0;

        rc = rtEfiVarStoreFindVar(pThis, offData, &offVar);
        if (RT_FAILURE(rc))
            break;

        rc = rtEfiVarStoreLoadAuthVar(pThis, offVar, &offData, true /* fIgnoreDelVars*/, pErrInfo);
        if (RT_FAILURE(rc))
            break;

        /* Align to 16bit boundary. */
        offData = RT_ALIGN_64(offData, 2);
    }

    if (rc == VERR_EOF) /* Reached end of variable store. */
        rc = VINF_SUCCESS;

    return rc;
}


/**
 * Fills the given range with 0xff to match what a real NAND flash device would return for
 * unwritten storage.
 *
 * @returns IPRT status code.
 * @param   hVfsFile            The VFS file handle to write to.
 * @param   offStart            The start offset to fill.
 * @param   offEnd              Offset to fill up to (exclusive).
 */
static int rtEfiVarStoreFillWithFF(RTVFSFILE hVfsFile, uint64_t offStart, uint64_t offEnd)
{
    int rc = VINF_SUCCESS;
    uint8_t abFF[512];
    memset(&abFF[0], 0xff, sizeof(abFF));

    while (   offStart < offEnd
           && RT_SUCCESS(rc))
    {
        size_t cbThisWrite = RT_MIN(sizeof(abFF), offEnd - offStart);
        rc = RTVfsFileWriteAt(hVfsFile, offStart, &abFF[0], cbThisWrite, NULL);
        offStart += cbThisWrite;
    }

    return rc;
}


RTDECL(int) RTEfiVarStoreOpenAsVfs(RTVFSFILE hVfsFileIn, uint32_t fMntFlags, uint32_t fVarStoreFlags, PRTVFS phVfs, PRTERRINFO pErrInfo)
{
    AssertPtrReturn(phVfs, VERR_INVALID_POINTER);
    AssertReturn(!(fMntFlags & ~RTVFSMNT_F_VALID_MASK), VERR_INVALID_FLAGS);
    AssertReturn(!fVarStoreFlags, VERR_INVALID_FLAGS);

    uint32_t cRefs = RTVfsFileRetain(hVfsFileIn);
    AssertReturn(cRefs != UINT32_MAX, VERR_INVALID_HANDLE);

    /*
     * Create a VFS instance and initialize the data so rtFsExtVol_Close works.
     */
    RTVFS            hVfs;
    PRTEFIVARSTORE pThis;
    int rc = RTVfsNew(&g_rtEfiVarStoreOps, sizeof(*pThis), NIL_RTVFS, RTVFSLOCK_CREATE_RW, &hVfs, (void **)&pThis);
    if (RT_SUCCESS(rc))
    {
        pThis->hVfsBacking    = hVfsFileIn;
        pThis->hVfsSelf       = hVfs;
        pThis->fMntFlags      = fMntFlags;
        pThis->fVarStoreFlags = fVarStoreFlags;

        rc = RTVfsFileQuerySize(pThis->hVfsBacking, &pThis->cbBacking);
        if (RT_SUCCESS(rc))
        {
            rc = rtEfiVarStoreLoad(pThis, pErrInfo);
            if (RT_SUCCESS(rc))
            {
                *phVfs = hVfs;
                return VINF_SUCCESS;
            }
        }

        RTVfsRelease(hVfs);
        *phVfs = NIL_RTVFS;
    }
    else
        RTVfsFileRelease(hVfsFileIn);

    return rc;
}


RTDECL(int) RTEfiVarStoreCreate(RTVFSFILE hVfsFile, uint64_t offStore, uint64_t cbStore, uint32_t fFlags, uint32_t cbBlock,
                                PRTERRINFO pErrInfo)
{
    RT_NOREF(pErrInfo);

    /*
     * Validate input.
     */
    if (!cbBlock)
        cbBlock = 4096;
    else
        AssertMsgReturn(cbBlock <= 8192 && RT_IS_POWER_OF_TWO(cbBlock),
                        ("cbBlock=%#x\n", cbBlock), VERR_INVALID_PARAMETER);
    AssertReturn(!(fFlags & ~RTEFIVARSTORE_CREATE_F_VALID_MASK), VERR_INVALID_FLAGS);

    if (!cbStore)
    {
        uint64_t cbFile;
        int rc = RTVfsFileQuerySize(hVfsFile, &cbFile);
        AssertRCReturn(rc, rc);
        AssertMsgReturn(cbFile > offStore, ("cbFile=%#RX64 offStore=%#RX64\n", cbFile, offStore), VERR_INVALID_PARAMETER);
        cbStore = cbFile - offStore;
    }

    uint32_t cbFtw = 0;
    uint32_t offFtw = 0;
    uint32_t cbVarStore = cbStore;
    uint32_t cbNvEventLog = 0;
    uint32_t offNvEventLog = 0;
    if (!(fFlags & RTEFIVARSTORE_CREATE_F_NO_FTW_WORKING_SPACE))
    {
        /* Split the available space in half for the fault tolerant working area. */
        /** @todo Don't fully understand how these values come together right now but
         * we want to create NVRAM files matching the default OVMF_VARS.fd for now, see
         * https://github.com/tianocore/edk2/commit/b24fca05751f8222acf264853709012e0ab7bf49
         * for the layout.
         * Probably have toadd more arguments to control the different parameters.
         */
        cbNvEventLog  = _4K;
        cbVarStore    = cbStore / 2 - cbNvEventLog - _4K;
        cbFtw         = cbVarStore + _4K;
        offNvEventLog = cbVarStore;
        offFtw        = offNvEventLog + cbNvEventLog;
    }

    uint32_t const cBlocks = (uint32_t)(cbStore / cbBlock);

    EFI_GUID                   GuidVarStore = EFI_VARSTORE_FILESYSTEM_GUID;
    EFI_GUID                   GuidVarAuth  = EFI_VARSTORE_HEADER_GUID_AUTHENTICATED_VARIABLE;
    EFI_FIRMWARE_VOLUME_HEADER FvHdr;       RT_ZERO(FvHdr);
    EFI_FW_BLOCK_MAP           aBlockMap[2]; RT_ZERO(aBlockMap);
    EFI_VARSTORE_HEADER        VarStoreHdr; RT_ZERO(VarStoreHdr);

    /* Firmware volume header. */
    memcpy(&FvHdr.GuidFilesystem, &GuidVarStore, sizeof(GuidVarStore));
    FvHdr.cbFv           = RT_H2LE_U64(cbStore);
    FvHdr.u32Signature   = RT_H2LE_U32(EFI_FIRMWARE_VOLUME_HEADER_SIGNATURE);
    FvHdr.fAttr          = RT_H2LE_U32(0x4feff); /** @todo */
    FvHdr.cbFvHdr        = RT_H2LE_U16(sizeof(FvHdr) + sizeof(aBlockMap));
    FvHdr.bRevision      = EFI_FIRMWARE_VOLUME_HEADER_REVISION;

    /* Start calculating the checksum of the main header. */
    uint16_t u16Chksum = 0;
    const uint16_t *pu16 = (const uint16_t *)&FvHdr;
    while (pu16 < (const uint16_t *)&FvHdr + (sizeof(FvHdr) / sizeof(uint16_t)))
        u16Chksum += RT_LE2H_U16(*pu16++);

    /* Block map, the second entry remains 0 as it serves the delimiter. */
    aBlockMap[0].cbBlock     = RT_H2LE_U32(cbBlock);
    aBlockMap[0].cBlocks     = RT_H2LE_U32(cBlocks);

    pu16 = (const uint16_t *)&aBlockMap[0];
    while (pu16 < (const uint16_t *)&aBlockMap[0] + (sizeof(aBlockMap) / (sizeof(uint16_t))))
        u16Chksum += RT_LE2H_U16(*pu16++);

    FvHdr.u16Chksum          = RT_H2LE_U16(UINT16_MAX - u16Chksum + 1);

    /* Variable store header. */
    memcpy(&VarStoreHdr.GuidVarStore, &GuidVarAuth, sizeof(GuidVarAuth));
    VarStoreHdr.cbVarStore   = RT_H2LE_U32(cbVarStore - sizeof(FvHdr) - sizeof(aBlockMap));
    VarStoreHdr.bFmt         = EFI_VARSTORE_HEADER_FMT_FORMATTED;
    VarStoreHdr.bState       = EFI_VARSTORE_HEADER_STATE_HEALTHY;

    /* Write everything. */
    int rc = RTVfsFileWriteAt(hVfsFile, offStore, &FvHdr, sizeof(FvHdr), NULL);
    if (RT_SUCCESS(rc))
        rc = RTVfsFileWriteAt(hVfsFile, offStore + sizeof(FvHdr), &aBlockMap[0], sizeof(aBlockMap), NULL);
    if (RT_SUCCESS(rc))
        rc = RTVfsFileWriteAt(hVfsFile, offStore + sizeof(FvHdr) + sizeof(aBlockMap), &VarStoreHdr, sizeof(VarStoreHdr), NULL);
    if (RT_SUCCESS(rc))
    {
        /* Fill the remainder with 0xff as it would be the case for a real NAND flash device. */
        uint64_t offStart = offStore + sizeof(FvHdr) + sizeof(aBlockMap) + sizeof(VarStoreHdr);
        uint64_t offEnd   = offStore + cbVarStore;

        rc = rtEfiVarStoreFillWithFF(hVfsFile, offStart, offEnd);
    }

    if (   RT_SUCCESS(rc)
        && !(fFlags & RTEFIVARSTORE_CREATE_F_NO_FTW_WORKING_SPACE))
    {
        EFI_GUID             GuidFtwArea = EFI_WORKING_BLOCK_SIGNATURE_GUID;
        EFI_FTW_BLOCK_HEADER FtwHdr; RT_ZERO(FtwHdr);

        memcpy(&FtwHdr.GuidSignature, &GuidFtwArea, sizeof(GuidFtwArea));
        FtwHdr.fWorkingBlockValid = RT_H2LE_U32(0xfffffffe); /** @todo */
        FtwHdr.cbWriteQueue       = RT_H2LE_U64(0xfe0ULL); /* This comes from the default OVMF variable volume. */
        FtwHdr.u32Chksum          = RTCrc32(&FtwHdr, sizeof(FtwHdr));

        /* The area starts with the event log which defaults to 0xff. */
        rc = rtEfiVarStoreFillWithFF(hVfsFile, offNvEventLog, offNvEventLog + cbNvEventLog);
        if (RT_SUCCESS(rc))
        {
            /* Write the FTW header. */
            rc = RTVfsFileWriteAt(hVfsFile, offFtw, &FtwHdr, sizeof(FtwHdr), NULL);
            if (RT_SUCCESS(rc))
                rc = rtEfiVarStoreFillWithFF(hVfsFile, offFtw + sizeof(FtwHdr), offFtw + cbFtw);
        }
    }

    return rc;
}


/**
 * @interface_method_impl{RTVFSCHAINELEMENTREG,pfnValidate}
 */
static DECLCALLBACK(int) rtVfsChainEfiVarStore_Validate(PCRTVFSCHAINELEMENTREG pProviderReg, PRTVFSCHAINSPEC pSpec,
                                                        PRTVFSCHAINELEMSPEC pElement, uint32_t *poffError, PRTERRINFO pErrInfo)
{
    RT_NOREF(pProviderReg);

    /*
     * Basic checks.
     */
    if (pElement->enmTypeIn != RTVFSOBJTYPE_FILE)
        return pElement->enmTypeIn == RTVFSOBJTYPE_INVALID ? VERR_VFS_CHAIN_CANNOT_BE_FIRST_ELEMENT : VERR_VFS_CHAIN_TAKES_FILE;
    if (   pElement->enmType != RTVFSOBJTYPE_VFS
        && pElement->enmType != RTVFSOBJTYPE_DIR)
        return VERR_VFS_CHAIN_ONLY_DIR_OR_VFS;
    if (pElement->cArgs > 1)
        return VERR_VFS_CHAIN_AT_MOST_ONE_ARG;

    /*
     * Parse the flag if present, save in pElement->uProvider.
     */
    bool fReadOnly = (pSpec->fOpenFile & RTFILE_O_ACCESS_MASK) == RTFILE_O_READ;
    if (pElement->cArgs > 0)
    {
        const char *psz = pElement->paArgs[0].psz;
        if (*psz)
        {
            if (!strcmp(psz, "ro"))
                fReadOnly = true;
            else if (!strcmp(psz, "rw"))
                fReadOnly = false;
            else
            {
                *poffError = pElement->paArgs[0].offSpec;
                return RTErrInfoSet(pErrInfo, VERR_VFS_CHAIN_INVALID_ARGUMENT, "Expected 'ro' or 'rw' as argument");
            }
        }
    }

    pElement->uProvider = fReadOnly ? RTVFSMNT_F_READ_ONLY : 0;
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSCHAINELEMENTREG,pfnInstantiate}
 */
static DECLCALLBACK(int) rtVfsChainEfiVarStore_Instantiate(PCRTVFSCHAINELEMENTREG pProviderReg, PCRTVFSCHAINSPEC pSpec,
                                                           PCRTVFSCHAINELEMSPEC pElement, RTVFSOBJ hPrevVfsObj,
                                                           PRTVFSOBJ phVfsObj, uint32_t *poffError, PRTERRINFO pErrInfo)
{
    RT_NOREF(pProviderReg, pSpec, poffError);

    int         rc;
    RTVFSFILE   hVfsFileIn = RTVfsObjToFile(hPrevVfsObj);
    if (hVfsFileIn != NIL_RTVFSFILE)
    {
        RTVFS hVfs;
        rc = RTEfiVarStoreOpenAsVfs(hVfsFileIn, (uint32_t)pElement->uProvider, (uint32_t)(pElement->uProvider >> 32), &hVfs, pErrInfo);
        RTVfsFileRelease(hVfsFileIn);
        if (RT_SUCCESS(rc))
        {
            *phVfsObj = RTVfsObjFromVfs(hVfs);
            RTVfsRelease(hVfs);
            if (*phVfsObj != NIL_RTVFSOBJ)
                return VINF_SUCCESS;
            rc = VERR_VFS_CHAIN_CAST_FAILED;
        }
    }
    else
        rc = VERR_VFS_CHAIN_CAST_FAILED;
    return rc;
}


/**
 * @interface_method_impl{RTVFSCHAINELEMENTREG,pfnCanReuseElement}
 */
static DECLCALLBACK(bool) rtVfsChainEfiVarStore_CanReuseElement(PCRTVFSCHAINELEMENTREG pProviderReg,
                                                                PCRTVFSCHAINSPEC pSpec, PCRTVFSCHAINELEMSPEC pElement,
                                                                PCRTVFSCHAINSPEC pReuseSpec, PCRTVFSCHAINELEMSPEC pReuseElement)
{
    RT_NOREF(pProviderReg, pSpec, pReuseSpec);
    if (   pElement->paArgs[0].uProvider == pReuseElement->paArgs[0].uProvider
        || !pReuseElement->paArgs[0].uProvider)
        return true;
    return false;
}


/** VFS chain element 'efivarstore'. */
static RTVFSCHAINELEMENTREG g_rtVfsChainEfiVarStoreReg =
{
    /* uVersion = */            RTVFSCHAINELEMENTREG_VERSION,
    /* fReserved = */           0,
    /* pszName = */             "efivarstore",
    /* ListEntry = */           { NULL, NULL },
    /* pszHelp = */             "Open a EFI variable store, requires a file object on the left side.\n"
                                "First argument is an optional 'ro' (read-only) or 'rw' (read-write) flag.\n",
    /* pfnValidate = */         rtVfsChainEfiVarStore_Validate,
    /* pfnInstantiate = */      rtVfsChainEfiVarStore_Instantiate,
    /* pfnCanReuseElement = */  rtVfsChainEfiVarStore_CanReuseElement,
    /* uEndMarker = */          RTVFSCHAINELEMENTREG_VERSION
};

RTVFSCHAIN_AUTO_REGISTER_ELEMENT_PROVIDER(&g_rtVfsChainEfiVarStoreReg, rtVfsChainEfiVarStoreReg);