patina_dxe_core 18.1.0

A pure rust implementation of the UEFI DXE Core.
Documentation
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
//! DXE Core DXE Services
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!
use alloc::{boxed::Box, vec::Vec};
use core::{
    ffi::c_void,
    mem,
    slice::{self, from_raw_parts},
};
use patina::error::EfiError;
use patina_ffs::volume::VolumeRef;

use patina::pi::dxe_services;
use r_efi::efi;

use crate::{Core, GCD, PlatformInfo, allocator::core_allocate_pool, config_tables, gcd, systemtables::EfiSystemTable};

extern "efiapi" fn add_memory_space(
    gcd_memory_type: dxe_services::GcdMemoryType,
    base_address: efi::PhysicalAddress,
    length: u64,
    capabilities: u64,
) -> efi::Status {
    let result = unsafe { GCD.add_memory_space(gcd_memory_type, base_address as usize, length as usize, capabilities) };

    match result {
        Ok(_) => efi::Status::SUCCESS,
        Err(err) => efi::Status::from(err),
    }
}

extern "efiapi" fn allocate_memory_space(
    gcd_allocate_type: dxe_services::GcdAllocateType,
    gcd_memory_type: dxe_services::GcdMemoryType,
    alignment: usize,
    length: u64,
    base_address: *mut efi::PhysicalAddress,
    image_handle: efi::Handle,
    device_handle: efi::Handle,
) -> efi::Status {
    if base_address.is_null() {
        return efi::Status::INVALID_PARAMETER;
    }

    let allocate_type = match gcd_allocate_type {
        dxe_services::GcdAllocateType::Address => {
            // Safety: caller must ensure that base_address is a valid pointer. It is null-checked above.
            let desired_address = unsafe { base_address.read_unaligned() };
            gcd::AllocateType::Address(desired_address as usize)
        }
        dxe_services::GcdAllocateType::AnySearchBottomUp => gcd::AllocateType::BottomUp(None),
        dxe_services::GcdAllocateType::AnySearchTopDown => gcd::AllocateType::TopDown(None),
        dxe_services::GcdAllocateType::MaxAddressSearchBottomUp => {
            // Safety: caller must ensure that base_address is a valid pointer. It is null-checked above.
            let limit = unsafe { base_address.read_unaligned() };
            gcd::AllocateType::BottomUp(Some(limit as usize))
        }
        dxe_services::GcdAllocateType::MaxAddressSearchTopDown => {
            // Safety: caller must ensure that base_address is a valid pointer. It is null-checked above.
            let limit = unsafe { base_address.read_unaligned() };
            gcd::AllocateType::TopDown(Some(limit as usize))
        }
        _ => return efi::Status::INVALID_PARAMETER,
    };

    let result = GCD.allocate_memory_space(
        allocate_type,
        gcd_memory_type,
        alignment,
        length as usize,
        image_handle,
        if device_handle.is_null() { None } else { Some(device_handle) },
    );

    match result {
        Ok(allocated_addr) => {
            // Safety: caller must ensure that base_address is a valid pointer. It is null-checked above.
            unsafe { base_address.write_unaligned(allocated_addr as u64) };
            efi::Status::SUCCESS
        }
        Err(err) => efi::Status::from(err),
    }
}

extern "efiapi" fn free_memory_space(base_address: efi::PhysicalAddress, length: u64) -> efi::Status {
    let result = GCD.free_memory_space(base_address as usize, length as usize);

    match result {
        Ok(_) => efi::Status::SUCCESS,
        Err(err) => efi::Status::from(err),
    }
}

extern "efiapi" fn remove_memory_space(base_address: efi::PhysicalAddress, length: u64) -> efi::Status {
    let result = GCD.remove_memory_space(base_address as usize, length as usize);
    match result {
        Ok(_) => efi::Status::SUCCESS,
        Err(err) => efi::Status::from(err),
    }
}

extern "efiapi" fn get_memory_space_descriptor(
    base_address: efi::PhysicalAddress,
    descriptor: *mut dxe_services::MemorySpaceDescriptor,
) -> efi::Status {
    if descriptor.is_null() {
        return efi::Status::INVALID_PARAMETER;
    }

    match core_get_memory_space_descriptor(base_address) {
        Err(err) => return err.into(),
        Ok(target_descriptor) =>
        // Safety: caller must ensure that descriptor is a valid pointer. It is null-checked above.
        unsafe {
            descriptor.write_unaligned(target_descriptor);
        },
    }
    efi::Status::SUCCESS
}

pub fn core_get_memory_space_descriptor(
    base_address: efi::PhysicalAddress,
) -> Result<dxe_services::MemorySpaceDescriptor, EfiError> {
    GCD.get_memory_descriptor_for_address(base_address)
}

extern "efiapi" fn set_memory_space_attributes(
    base_address: efi::PhysicalAddress,
    length: u64,
    attributes: u64,
) -> efi::Status {
    match core_set_memory_space_attributes(base_address, length, attributes) {
        Ok(_) => efi::Status::SUCCESS,
        Err(err) => err.into(),
    }
}

pub fn core_set_memory_space_attributes(
    base_address: efi::PhysicalAddress,
    length: u64,
    attributes: u64,
) -> Result<(), EfiError> {
    match GCD.set_memory_space_attributes(base_address as usize, length as usize, attributes) {
        Ok(()) => Ok(()),
        Err(EfiError::NotReady) => {
            // Disambiguate "NotReady": if the GCD is initialized but paging
            // isn’t installed yet, the GCD state has been updated and callers
            // of the DXE Services wrapper expect SUCCESS. Only surface
            // NOT_READY when the GCD itself is uninitialized.
            if GCD.is_ready() {
                Ok(()) // GCD ready, paging not ready -> treat as success
            } else {
                Err(EfiError::NotReady) // GCD not initialized
            }
        }
        Err(e) => Err(e),
    }
}

extern "efiapi" fn set_memory_space_capabilities(
    base_address: efi::PhysicalAddress,
    length: u64,
    capabilities: u64,
) -> efi::Status {
    match core_set_memory_space_capabilities(base_address, length, capabilities) {
        Err(err) => err.into(),
        Ok(_) => efi::Status::SUCCESS,
    }
}

pub fn core_set_memory_space_capabilities(
    base_address: efi::PhysicalAddress,
    length: u64,
    capabilities: u64,
) -> Result<(), EfiError> {
    GCD.set_memory_space_capabilities(base_address as usize, length as usize, capabilities)
}

extern "efiapi" fn get_memory_space_map(
    number_of_descriptors: *mut usize,
    memory_space_map: *mut *mut dxe_services::MemorySpaceDescriptor,
) -> efi::Status {
    if number_of_descriptors.is_null() || memory_space_map.is_null() {
        return efi::Status::INVALID_PARAMETER;
    }

    //allocate an empty vector with enough space for all the descriptors with some padding (in the event)
    //that extra descriptors come into being after creation but before usage.
    let mut descriptors: Vec<dxe_services::MemorySpaceDescriptor> =
        Vec::with_capacity(GCD.memory_descriptor_count() + 10);
    let result = GCD.get_memory_descriptors(&mut descriptors);

    if let Err(err) = result {
        return efi::Status::from(err);
    }

    //caller is supposed to free the handle buffer using free pool, so we need to allocate it using allocate pool.
    let buffer_size = descriptors.len() * mem::size_of::<dxe_services::MemorySpaceDescriptor>();
    match core_allocate_pool(efi::BOOT_SERVICES_DATA, buffer_size) {
        Err(err) => err.into(),
        Ok(allocation) =>
        // Safety: caller must ensure that number_of_descriptors and memory_space_map are valid pointers. They are
        // null-checked above.
        unsafe {
            memory_space_map.write_unaligned(allocation as *mut dxe_services::MemorySpaceDescriptor);
            number_of_descriptors.write_unaligned(descriptors.len());
            slice::from_raw_parts_mut(memory_space_map.read_unaligned(), descriptors.len())
                .copy_from_slice(&descriptors);
            efi::Status::SUCCESS
        },
    }
}

extern "efiapi" fn add_io_space(
    gcd_io_type: dxe_services::GcdIoType,
    base_address: efi::PhysicalAddress,
    length: u64,
) -> efi::Status {
    let result = GCD.add_io_space(gcd_io_type, base_address as usize, length as usize);
    match result {
        Ok(_) => efi::Status::SUCCESS,
        Err(err) => efi::Status::from(err),
    }
}

extern "efiapi" fn allocate_io_space(
    gcd_allocate_type: dxe_services::GcdAllocateType,
    gcd_io_type: dxe_services::GcdIoType,
    alignment: usize,
    length: u64,
    base_address: *mut efi::PhysicalAddress,
    image_handle: efi::Handle,
    device_handle: efi::Handle,
) -> efi::Status {
    if base_address.is_null() {
        return efi::Status::INVALID_PARAMETER;
    }

    let allocate_type = match gcd_allocate_type {
        dxe_services::GcdAllocateType::Address => {
            // Safety: caller must ensure that base_address is a valid pointer. It is null-checked above.
            let desired_address = unsafe { base_address.read_unaligned() };
            gcd::AllocateType::Address(desired_address as usize)
        }
        dxe_services::GcdAllocateType::AnySearchBottomUp => gcd::AllocateType::BottomUp(None),
        dxe_services::GcdAllocateType::AnySearchTopDown => gcd::AllocateType::TopDown(None),
        dxe_services::GcdAllocateType::MaxAddressSearchBottomUp => {
            // Safety: caller must ensure that base_address is a valid pointer. It is null-checked above.
            let limit = unsafe { base_address.read_unaligned() };
            gcd::AllocateType::BottomUp(Some(limit as usize))
        }
        dxe_services::GcdAllocateType::MaxAddressSearchTopDown => {
            // Safety: caller must ensure that base_address is a valid pointer. It is null-checked above.
            let limit = unsafe { base_address.read_unaligned() };
            gcd::AllocateType::TopDown(Some(limit as usize))
        }
        _ => return efi::Status::INVALID_PARAMETER,
    };

    let result = GCD.allocate_io_space(
        allocate_type,
        gcd_io_type,
        alignment,
        length as usize,
        image_handle,
        if device_handle.is_null() { None } else { Some(device_handle) },
    );

    match result {
        Ok(allocated_addr) => {
            // Safety: caller must ensure that base_address is a valid pointer. It is null-checked above.
            unsafe { base_address.write_unaligned(allocated_addr as u64) };
            efi::Status::SUCCESS
        }
        Err(err) => efi::Status::from(err),
    }
}

extern "efiapi" fn free_io_space(base_address: efi::PhysicalAddress, length: u64) -> efi::Status {
    let result = GCD.free_io_space(base_address as usize, length as usize);

    match result {
        Ok(_) => efi::Status::SUCCESS,
        Err(err) => efi::Status::from(err),
    }
}

extern "efiapi" fn remove_io_space(base_address: efi::PhysicalAddress, length: u64) -> efi::Status {
    let result = GCD.remove_io_space(base_address as usize, length as usize);
    match result {
        Ok(_) => efi::Status::SUCCESS,
        Err(err) => efi::Status::from(err),
    }
}

extern "efiapi" fn get_io_space_descriptor(
    base_address: efi::PhysicalAddress,
    descriptor: *mut dxe_services::IoSpaceDescriptor,
) -> efi::Status {
    if descriptor.is_null() {
        return efi::Status::INVALID_PARAMETER;
    }

    //Note: this would be more efficient if it was done in the GCD; rather than retrieving all the descriptors and
    //searching them here. It is done this way for simplicity - it can be optimized if it proves too slow.

    //allocate an empty vector with enough space for all the descriptors with some padding (in the event)
    //that extra descriptors come into being after creation but before usage.
    let mut descriptors: Vec<dxe_services::IoSpaceDescriptor> = Vec::with_capacity(GCD.io_descriptor_count() + 10);
    let result = GCD.get_io_descriptors(&mut descriptors);

    if let Err(err) = result {
        return efi::Status::from(err);
    }

    let target_descriptor =
        descriptors.iter().find(|x| (x.base_address <= base_address) && (base_address < (x.base_address + x.length)));

    if let Some(target_descriptor) = target_descriptor {
        // Safety: caller must ensure that descriptor is a valid pointer. It is null-checked above.
        unsafe { descriptor.write_unaligned(*target_descriptor) };
        efi::Status::SUCCESS
    } else {
        efi::Status::NOT_FOUND
    }
}

extern "efiapi" fn get_io_space_map(
    number_of_descriptors: *mut usize,
    io_space_map: *mut *mut dxe_services::IoSpaceDescriptor,
) -> efi::Status {
    if number_of_descriptors.is_null() || io_space_map.is_null() {
        return efi::Status::INVALID_PARAMETER;
    }
    //allocate an empty vector with enough space for all the descriptors with some padding (in the event)
    //that extra descriptors come into being after creation but before usage.
    let mut descriptors: Vec<dxe_services::IoSpaceDescriptor> = Vec::with_capacity(GCD.io_descriptor_count() + 10);
    let result = GCD.get_io_descriptors(&mut descriptors);

    if let Err(err) = result {
        return efi::Status::from(err);
    }

    //caller is supposed to free the handle buffer using free pool, so we need to allocate it using allocate pool.
    let buffer_size = descriptors.len() * mem::size_of::<dxe_services::IoSpaceDescriptor>();

    match core_allocate_pool(efi::BOOT_SERVICES_DATA, buffer_size) {
        Err(err) => err.into(),
        Ok(allocation) =>
        // Safety: caller must ensure that number_of_descriptors and io_space_map are valid pointers. They are null-checked above.
        unsafe {
            io_space_map.write_unaligned(allocation as *mut dxe_services::IoSpaceDescriptor);
            number_of_descriptors.write_unaligned(descriptors.len());
            slice::from_raw_parts_mut(io_space_map.read_unaligned(), descriptors.len()).copy_from_slice(&descriptors);
            efi::Status::SUCCESS
        },
    }
}

impl<P: PlatformInfo> Core<P> {
    /// Initializes and installs the DXE Services table into the provided system table.
    pub(crate) fn install_dxe_services_table(&self, system_table: &mut EfiSystemTable) {
        let mut dxe_services_system_table = dxe_services::DxeServicesTable {
            header: efi::TableHeader {
                signature: efi::BOOT_SERVICES_SIGNATURE,
                revision: efi::BOOT_SERVICES_REVISION,
                header_size: mem::size_of::<dxe_services::DxeServicesTable>() as u32,
                crc32: 0,
                reserved: 0,
            },
            add_memory_space,
            allocate_memory_space,
            free_memory_space,
            remove_memory_space,
            get_memory_space_descriptor,
            set_memory_space_attributes,
            get_memory_space_map,
            add_io_space,
            allocate_io_space,
            free_io_space,
            remove_io_space,
            get_io_space_descriptor,
            get_io_space_map,
            dispatch: Self::dispatch_efiapi,
            schedule: Self::schedule_efiapi,
            trust: Self::trust_efiapi,
            process_firmware_volume: Self::process_firmware_volume_efiapi,
            set_memory_space_capabilities,
        };
        let dxe_services_system_table_ptr = &dxe_services_system_table as *const dxe_services::DxeServicesTable;
        let crc32 = unsafe {
            crc32fast::hash(from_raw_parts(
                dxe_services_system_table_ptr as *const u8,
                mem::size_of::<dxe_services::DxeServicesTable>(),
            ))
        };
        dxe_services_system_table.header.crc32 = crc32;

        let dxe_services_system_table = Box::new(dxe_services_system_table);

        let _ = config_tables::core_install_configuration_table(
            dxe_services::DXE_SERVICES_TABLE_GUID,
            Box::into_raw(dxe_services_system_table) as *mut c_void,
            system_table,
        );
    }

    extern "efiapi" fn process_firmware_volume_efiapi(
        firmware_volume_header: *const c_void,
        size: usize,
        firmware_volume_handle: *mut efi::Handle,
    ) -> efi::Status {
        if firmware_volume_handle.is_null() || firmware_volume_header.is_null() {
            return efi::Status::INVALID_PARAMETER;
        }

        // construct a FirmwareVolume to verify sanity
        // Safety: caller must ensure that firmware_volume_header is a valid pointer. It is null-checked above.
        let fv_slice = unsafe { slice::from_raw_parts(firmware_volume_header as *const u8, size) };
        if let Err(err) = VolumeRef::new(fv_slice) {
            return err.into();
        }
        // Safety: caller must ensure that firmware_volume_header is a valid firmware volume that will not be freed
        // or moved after being sent to the core for processing.
        let res =
            unsafe { Self::instance().pi_dispatcher.install_firmware_volume(firmware_volume_header as u64, None) };
        let handle = match res {
            Ok(handle) => handle,
            Err(err) => return err.into(),
        };

        // Safety: caller must ensure that firmware_volume_handle is a valid pointer. It is null-checked above.
        unsafe {
            firmware_volume_handle.write_unaligned(handle);
        }

        efi::Status::SUCCESS
    }

    #[coverage(off)]
    extern "efiapi" fn dispatch_efiapi() -> efi::Status {
        match Self::instance().pi_dispatcher.dispatcher() {
            Err(err) => err.into(),
            Ok(()) => efi::Status::SUCCESS,
        }
    }

    extern "efiapi" fn schedule_efiapi(
        firmware_volume_handle: efi::Handle,
        file_name: *const efi::Guid,
    ) -> efi::Status {
        if file_name.is_null() {
            return efi::Status::INVALID_PARAMETER;
        }
        // Safety: caller must ensure that file_name is a valid pointer. It is null-checked above.
        let file_name = unsafe { file_name.read_unaligned() };

        match Self::instance().pi_dispatcher.schedule(firmware_volume_handle, &file_name) {
            Err(status) => status.into(),
            Ok(_) => efi::Status::SUCCESS,
        }
    }

    extern "efiapi" fn trust_efiapi(firmware_volume_handle: efi::Handle, file_name: *const efi::Guid) -> efi::Status {
        if file_name.is_null() {
            return efi::Status::INVALID_PARAMETER;
        }
        // Safety: caller must ensure that file_name is a valid pointer. It is null-checked above.
        let file_name = unsafe { file_name.read_unaligned() };

        match Self::instance().pi_dispatcher.trust(firmware_volume_handle, &file_name) {
            Err(status) => status.into(),
            Ok(_) => efi::Status::SUCCESS,
        }
    }
}

#[cfg(test)]
#[coverage(off)]
mod tests {
    use super::*;
    use crate::{MockCore, test_support};
    use dxe_services::{GcdIoType, GcdMemoryType};
    use patina_ffs_extractors::NullSectionExtractor;

    fn with_locked_state<F: Fn() + std::panic::RefUnwindSafe>(f: F) {
        test_support::with_global_lock(|| {
            unsafe {
                crate::test_support::init_test_gcd(None);
                crate::test_support::init_test_protocol_db();
            }
            f();
        })
        .unwrap();
    }

    #[test]
    fn test_add_memory_space_success() {
        with_locked_state(|| {
            let result = add_memory_space(GcdMemoryType::SystemMemory, 0x80000000, 0x1000, efi::MEMORY_WB);

            assert_eq!(result, efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_add_memory_space_parameter_validation() {
        with_locked_state(|| {
            // Test: Zero length should return InvalidParameter
            let result = add_memory_space(
                GcdMemoryType::SystemMemory,
                0x80000000,
                0, // zero length should return InvalidParameter
                0,
            );
            assert_eq!(result, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_add_memory_space_overflow_returns_error() {
        with_locked_state(|| {
            // Test: Very large size that would overflow should return an error
            let result = add_memory_space(
                GcdMemoryType::SystemMemory,
                u64::MAX - 100,
                1000, // Would cause overflow
                0,
            );

            // Should return an error status, not SUCCESS
            assert_ne!(result, efi::Status::SUCCESS);
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_add_memory_space_different_memory_types() {
        with_locked_state(|| {
            // Test that our wrapper correctly handles different memory types
            let memory_types = [
                GcdMemoryType::SystemMemory,
                GcdMemoryType::Reserved,
                GcdMemoryType::MemoryMappedIo,
                GcdMemoryType::Persistent,
            ];

            for (i, mem_type) in memory_types.iter().enumerate() {
                let result = add_memory_space(
                    *mem_type,
                    0x100000 + (i as u64 * 0x10000), // Different addresses to avoid conflicts
                    0x1000,
                    0,
                );

                assert_eq!(result, efi::Status::SUCCESS, "Adding memory space for type {mem_type:?} failed");
            }
        });
    }

    #[test]
    fn test_add_memory_space_reserved_with_specific_attributes() {
        with_locked_state(|| {
            // Demonstrate adding a specific reserved memory region with detailed attributes
            // This example shows a firmware volume region that is:
            // - Memory-mapped I/O type
            // - Uncacheable for device access
            // - Execute-protected (XP) for security
            // - Read-only (RO) for integrity
            let result = add_memory_space(
                GcdMemoryType::Reserved,
                0xF0000000, // Typical firmware region address
                0x100000,   // 1MB firmware volume
                efi::MEMORY_UC | efi::MEMORY_XP | efi::MEMORY_RO,
            );

            assert_eq!(result, efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_allocate_memory_space_success() {
        with_locked_state(|| {
            let mut base_address: efi::PhysicalAddress = 0;
            let result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                12,      // 4KB alignment (2^12 = 4096)
                0x10000, // 64KB length
                &mut base_address,
                1 as _,
                core::ptr::null_mut(),
            );
            assert_eq!(result, efi::Status::SUCCESS);
            assert!(base_address != 0, "Base address should be set to a valid address");
        });
    }

    #[test]
    fn test_allocate_memory_space_null_base_address() {
        with_locked_state(|| {
            let result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                12,                    // 4KB alignment (2^12 = 4096)
                0x10000,               // 64KB length
                core::ptr::null_mut(), // null base address
                1 as _,
                core::ptr::null_mut(),
            );
            assert_eq!(result, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_allocate_memory_space_address_type() {
        with_locked_state(|| {
            let _ = add_memory_space(GcdMemoryType::SystemMemory, 0x100000, 0x100000, efi::MEMORY_WB);

            let mut base_address: efi::PhysicalAddress = 0x110000; // Specific address within the range
            let result = allocate_memory_space(
                dxe_services::GcdAllocateType::Address,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment (2^12 = 4096)
                0x1000, // 4KB length
                &mut base_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(result, efi::Status::SUCCESS, "Address allocation should succeed");
            assert_eq!(base_address, 0x110000, "Base address should match the requested address");
        });
    }

    #[test]
    fn test_allocate_memory_space_bottom_up() {
        with_locked_state(|| {
            let _ = add_memory_space(GcdMemoryType::SystemMemory, 0x200000, 0x100000, efi::MEMORY_WB);

            let mut base_address: efi::PhysicalAddress = 0;
            let result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment
                0x1000, // 4KB length
                &mut base_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(result, efi::Status::SUCCESS, "Bottom-up allocation should succeed");
        });
    }

    #[test]
    fn test_allocate_memory_space_top_down() {
        with_locked_state(|| {
            let _ = add_memory_space(GcdMemoryType::SystemMemory, 0x300000, 0x100000, efi::MEMORY_WB);

            let mut base_address: efi::PhysicalAddress = 0;
            let result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchTopDown,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment
                0x1000, // 4KB length
                &mut base_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(result, efi::Status::SUCCESS, "Top-down allocation should succeed");
        });
    }

    #[test]
    fn test_allocate_memory_space_max_address_bottom_up() {
        with_locked_state(|| {
            let _ = add_memory_space(GcdMemoryType::SystemMemory, 0x400000, 0x100000, efi::MEMORY_WB);

            let mut base_address: efi::PhysicalAddress = 0x480000; // Max address limit
            let result = allocate_memory_space(
                dxe_services::GcdAllocateType::MaxAddressSearchBottomUp,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment
                0x1000, // 4KB length
                &mut base_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(result, efi::Status::SUCCESS);
            assert!(base_address <= 0x480000, "Allocated address should be within the limit");
        });
    }

    #[test]
    fn test_allocate_memory_space_max_address_top_down() {
        with_locked_state(|| {
            // First add some memory space to allocate from
            let _ = add_memory_space(GcdMemoryType::SystemMemory, 0x500000, 0x100000, efi::MEMORY_WB);

            let mut base_address: efi::PhysicalAddress = 0x580000; // Max address limit
            let result = allocate_memory_space(
                dxe_services::GcdAllocateType::MaxAddressSearchTopDown,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment
                0x1000, // 4KB length
                &mut base_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(result, efi::Status::SUCCESS, "Max address top-down allocation should succeed");
            assert!(base_address != 0, "Allocated address should be non-zero");
            assert!(base_address >= 0x500000, "Address should be within added memory range");
        });
    }

    #[test]
    fn test_allocate_memory_space_different_memory_types() {
        with_locked_state(|| {
            // Test allocation with different memory types
            let memory_types = [
                GcdMemoryType::SystemMemory,
                GcdMemoryType::Reserved,
                GcdMemoryType::MemoryMappedIo,
                GcdMemoryType::Persistent,
            ];

            for (i, mem_type) in memory_types.iter().enumerate() {
                // Add memory space for each type
                let base = 0x600000 + (i as u64 * 0x100000);
                let _ = add_memory_space(*mem_type, base, 0x50000, efi::MEMORY_WB);

                let mut base_address: efi::PhysicalAddress = 0;
                let result = allocate_memory_space(
                    dxe_services::GcdAllocateType::AnySearchBottomUp,
                    *mem_type,
                    12,     // 4KB alignment
                    0x1000, // 4KB length
                    &mut base_address,
                    1 as _,
                    core::ptr::null_mut(),
                );

                assert_eq!(result, efi::Status::SUCCESS, "Allocation for memory type {mem_type:?} should succeed");
            }
        });
    }

    #[test]
    fn test_allocate_memory_space_zero_length() {
        with_locked_state(|| {
            let mut base_address: efi::PhysicalAddress = 0;
            let result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                12, // 4KB alignment
                0,  // Zero length
                &mut base_address,
                1 as _,
                core::ptr::null_mut(),
            );

            // Zero length should return an error
            assert_ne!(result, efi::Status::SUCCESS, "Zero length allocation should fail");
        });
    }

    #[test]
    fn test_allocate_memory_space_excessive_alignment() {
        with_locked_state(|| {
            let mut base_address: efi::PhysicalAddress = 0;
            let result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                63, // Excessive alignment (2^63 would overflow)
                0x1000,
                &mut base_address,
                1 as _,
                core::ptr::null_mut(),
            );

            // Excessive alignment should return an error
            assert_ne!(result, efi::Status::SUCCESS, "Excessive alignment should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_free_memory_space_success() {
        with_locked_state(|| {
            // First add memory space
            let base = 0x200000;
            let length = 0x10000;
            let _ = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);

            // Then allocate some memory
            let mut allocated_address: efi::PhysicalAddress = 0;
            let allocate_result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment
                0x1000, // 4KB length
                &mut allocated_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(allocate_result, efi::Status::SUCCESS, "Should successfully allocate memory");
            let free_result = free_memory_space(allocated_address, 0x1000);
            assert_eq!(free_result, efi::Status::SUCCESS, "Should successfully free allocated memory");
        });
    }

    #[test]
    fn test_free_memory_space_zero_length() {
        with_locked_state(|| {
            let result = free_memory_space(0x100000, 0);
            // Zero length should return an error
            assert_ne!(result, efi::Status::SUCCESS, "Zero length should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_free_memory_space_unallocated_memory() {
        with_locked_state(|| {
            // Try to free memory that was never allocated
            let result = free_memory_space(0x300000, 0x1000);
            // Should return an error since this memory was never allocated
            assert_ne!(result, efi::Status::SUCCESS, "Freeing unallocated memory should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_free_memory_space_invalid_address() {
        with_locked_state(|| {
            // Try to free memory at an invalid/unmanaged address
            let result = free_memory_space(0, 0x1000);
            // Should return an error for invalid address
            assert_ne!(result, efi::Status::SUCCESS, "Freeing at address 0 should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_free_memory_space_double_free() {
        with_locked_state(|| {
            // Add memory space
            let base = 0x400000;
            let length = 0x10000;
            let _ = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);

            // Allocate memory
            let mut allocated_address: efi::PhysicalAddress = 0;
            let allocate_result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment
                0x1000, // 4KB length
                &mut allocated_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(allocate_result, efi::Status::SUCCESS, "Should successfully allocate memory");
            // Free once - should succeed
            let first_free = free_memory_space(allocated_address, 0x1000);
            assert_eq!(first_free, efi::Status::SUCCESS, "First free should succeed");

            // Try to free again - should fail
            let second_free = free_memory_space(allocated_address, 0x1000);
            assert_ne!(second_free, efi::Status::SUCCESS, "Double free should fail");
            assert!(second_free.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_free_memory_space_partial_overlap() {
        with_locked_state(|| {
            // Add memory space
            let base = 0x500000;
            let length = 0x10000;
            let _ = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);

            // Allocate memory
            let mut allocated_address: efi::PhysicalAddress = 0;
            let allocate_result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment
                0x2000, // 8KB length
                &mut allocated_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(allocate_result, efi::Status::SUCCESS, "Should successfully allocate memory");
            let partial_free = free_memory_space(allocated_address, 0x1000); // Only 4KB instead of 8KB
            assert_eq!(partial_free, efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_free_memory_space_wrong_length() {
        with_locked_state(|| {
            // Add memory space
            let base = 0x600000;
            let length = 0x10000;
            let _ = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);

            // Allocate memory
            let mut allocated_address: efi::PhysicalAddress = 0;
            let allocate_result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment
                0x1000, // 4KB length
                &mut allocated_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(allocate_result, efi::Status::SUCCESS, "Should successfully allocate memory");
            // Try to free with wrong length
            let wrong_length_free = free_memory_space(allocated_address, 0x2000); // 8KB instead of 4KB
            assert_ne!(wrong_length_free, efi::Status::SUCCESS);
            assert!(wrong_length_free.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_free_memory_space_large_values() {
        with_locked_state(|| {
            // Test with large but not overflow-causing values
            // Use a high address but leave room to avoid overflow
            let large_base = 0x7FFFFFFF00000000u64; // Large but safe value
            let length = 0x1000u64; // 4KB length

            let result = free_memory_space(large_base, length);
            // Should return an error for invalid large values (not allocated)
            assert_ne!(result, efi::Status::SUCCESS, "Large unallocated values should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_free_memory_space_allocate_free_cycle() {
        with_locked_state(|| {
            // Add memory space
            let base = 0x700000;
            let length = 0x10000;
            let _ = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);

            // Test multiple allocate/free cycles
            for i in 0..3 {
                let mut allocated_address: efi::PhysicalAddress = 0;
                let allocate_result = allocate_memory_space(
                    dxe_services::GcdAllocateType::AnySearchBottomUp,
                    GcdMemoryType::SystemMemory,
                    12,     // 4KB alignment
                    0x1000, // 4KB length
                    &mut allocated_address,
                    1 as _,
                    core::ptr::null_mut(),
                );

                assert_eq!(allocate_result, efi::Status::SUCCESS, "Cycle {i} allocate should succeed");
                let free_result = free_memory_space(allocated_address, 0x1000);
                assert_eq!(free_result, efi::Status::SUCCESS, "Cycle {i} free should succeed");
            }
        });
    }

    #[test]
    fn test_remove_memory_space_success() {
        with_locked_state(|| {
            let base = 0x800000;
            let length = 0x10000;
            let result = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);
            assert_eq!(result, efi::Status::SUCCESS, "Should successfully add memory space");

            let result = remove_memory_space(base, length);
            assert_eq!(result, efi::Status::SUCCESS, "Should successfully remove memory space");
        });
    }

    #[test]
    fn test_remove_memory_space_zero_length() {
        with_locked_state(|| {
            let result = remove_memory_space(0x800000, 0);
            assert_ne!(result, efi::Status::SUCCESS, "Zero length should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_remove_memory_space_not_found() {
        with_locked_state(|| {
            let result = remove_memory_space(0x900000, 0x1000);
            assert_ne!(result, efi::Status::SUCCESS, "Removing non-existent memory space should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_remove_memory_space_wrong_base_address() {
        with_locked_state(|| {
            let base = 0xB00000;
            let length = 0x10000;
            let result = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);
            assert_eq!(result, efi::Status::SUCCESS, "Should successfully add memory space");

            let result = remove_memory_space(base + 0x1000, length); // Offset base address
            assert_ne!(result, efi::Status::SUCCESS, "Wrong base address should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_remove_memory_space_wrong_length() {
        with_locked_state(|| {
            let base = 0xC00000;
            let length = 0x10000;
            let result = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);
            assert_eq!(result, efi::Status::SUCCESS, "Should successfully add memory space");

            let result = remove_memory_space(base, length * 2); // Double the length
            assert_ne!(result, efi::Status::SUCCESS, "Wrong length should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_remove_memory_space_double_remove() {
        with_locked_state(|| {
            // Add memory space
            let base = 0xD00000;
            let length = 0x10000;
            let result = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);
            assert_eq!(result, efi::Status::SUCCESS, "Should successfully add memory space");

            let first_remove = remove_memory_space(base, length);
            assert_eq!(first_remove, efi::Status::SUCCESS, "First removal should succeed");

            let second_remove = remove_memory_space(base, length);
            assert_ne!(second_remove, efi::Status::SUCCESS, "Double removal should fail");
            assert!(second_remove.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_remove_memory_space_different_memory_types() {
        with_locked_state(|| {
            // Test removal of different memory types
            let memory_types = [
                GcdMemoryType::SystemMemory,
                GcdMemoryType::Reserved,
                GcdMemoryType::MemoryMappedIo,
                GcdMemoryType::Persistent,
            ];

            for (i, mem_type) in memory_types.iter().enumerate() {
                // Add memory space for each type
                let base = 0xE00000 + (i as u64 * 0x100000);
                let length = 0x10000;
                let result = add_memory_space(*mem_type, base, length, efi::MEMORY_WB);
                assert_eq!(result, efi::Status::SUCCESS, "Adding memory space for type {mem_type:?} failed");

                // Remove the memory space
                let result = remove_memory_space(base, length);
                assert_eq!(result, efi::Status::SUCCESS, "Removing memory type {mem_type:?} should succeed");
            }
        });
    }

    #[test]
    fn test_remove_memory_space_with_allocated_memory() {
        with_locked_state(|| {
            let base = 0x1200000;
            let length = 0x10000;
            let result = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);
            assert_eq!(result, efi::Status::SUCCESS, "Should successfully add memory space");

            let mut allocated_address: efi::PhysicalAddress = 0;
            let allocate_result = allocate_memory_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdMemoryType::SystemMemory,
                12,     // 4KB alignment
                0x1000, // 4KB length
                &mut allocated_address,
                1 as _,
                core::ptr::null_mut(),
            );

            assert_eq!(allocate_result, efi::Status::SUCCESS, "Should successfully allocate memory");

            let result = remove_memory_space(base, length);
            assert_ne!(result, efi::Status::SUCCESS, "Removing memory space with allocations should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_remove_memory_space_large_values() {
        with_locked_state(|| {
            let large_base = 0x7FFFFFFF00000000u64; // Large but safe value
            let length = 0x1000u64; // 4KB length

            let result = remove_memory_space(large_base, length);
            assert_ne!(result, efi::Status::SUCCESS, "Large non-existent values should fail");
            assert!(result.as_usize() & 0x8000000000000000 != 0, "Should return an error status");
        });
    }

    #[test]
    fn test_remove_memory_space_add_remove_cycle() {
        with_locked_state(|| {
            let base = 0x1300000;
            let length = 0x10000;

            for i in 0..3 {
                let add_result = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);
                assert_eq!(add_result, efi::Status::SUCCESS, "Cycle {i} add should succeed");

                let remove_result = remove_memory_space(base, length);
                assert_eq!(remove_result, efi::Status::SUCCESS, "Cycle {i} remove should succeed");
            }
        });
    }

    #[test]
    fn test_remove_memory_space_multiple_regions_independence() {
        with_locked_state(|| {
            let regions = [(0x1400000, 0x10000), (0x1500000, 0x20000), (0x1600000, 0x15000)];

            for (base, length) in regions {
                let result = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);
                assert_eq!(result, efi::Status::SUCCESS, "Should add region at 0x{base:x}");
            }

            let remove_result = remove_memory_space(regions[1].0, regions[1].1);
            assert_eq!(remove_result, efi::Status::SUCCESS, "Should remove middle region");

            let remove_first = remove_memory_space(regions[0].0, regions[0].1);
            assert_eq!(remove_first, efi::Status::SUCCESS, "Should remove first region");

            let remove_third = remove_memory_space(regions[2].0, regions[2].1);
            assert_eq!(remove_third, efi::Status::SUCCESS, "Should remove third region");
        });
    }

    #[test]
    fn test_get_memory_space_descriptor_success() {
        with_locked_state(|| {
            let base = 0x1700000;
            let length = 0x20000;
            let capabilities = efi::MEMORY_WB | efi::MEMORY_WT;

            // Add memory space first
            let result = add_memory_space(GcdMemoryType::SystemMemory, base, length, capabilities);
            assert_eq!(result, efi::Status::SUCCESS, "Should add memory space");

            // Get descriptor for the added memory space
            let mut descriptor = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            let result = get_memory_space_descriptor(base, descriptor.as_mut_ptr());
            assert_eq!(result, efi::Status::SUCCESS, "Should get memory space descriptor");

            let descriptor = unsafe { descriptor.assume_init() };
            assert_eq!(descriptor.base_address, base, "Base address should match");
            assert_eq!(descriptor.length, length, "Length should match");
            assert_eq!(descriptor.memory_type, GcdMemoryType::SystemMemory, "Memory type should match");
            // Note: GCD may add additional capability flags, so we check that our requested capabilities are present
            assert!(
                descriptor.capabilities & capabilities == capabilities,
                "Requested capabilities should be present. Expected: 0x{:x}, Got: 0x{:x}",
                capabilities,
                descriptor.capabilities
            );
        });
    }

    #[test]
    fn test_get_memory_space_descriptor_null_descriptor() {
        with_locked_state(|| {
            let result = get_memory_space_descriptor(0x1000000, core::ptr::null_mut());
            assert_eq!(result, efi::Status::INVALID_PARAMETER, "Null descriptor should return INVALID_PARAMETER");
        });
    }

    #[test]
    fn test_get_memory_space_descriptor_address_within_range() {
        with_locked_state(|| {
            let base = 0x1800000;
            let length = 0x10000;
            let capabilities = efi::MEMORY_UC;

            // Add memory space
            let result = add_memory_space(GcdMemoryType::Reserved, base, length, capabilities);
            assert_eq!(result, efi::Status::SUCCESS, "Should add memory space");

            // Test getting descriptor for address within the range (not at the base)
            let test_address = base + 0x5000; // Address within the range
            let mut descriptor = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            let result = get_memory_space_descriptor(test_address, descriptor.as_mut_ptr());

            assert_eq!(result, efi::Status::SUCCESS, "Should get descriptor for address within range");

            let descriptor = unsafe { descriptor.assume_init() };
            assert_eq!(descriptor.base_address, base, "Base address should be the region base");
            assert_eq!(descriptor.length, length, "Length should match the region length");
            assert_eq!(descriptor.memory_type, GcdMemoryType::Reserved, "Memory type should match");
        });
    }

    #[test]
    fn test_get_memory_space_descriptor_different_memory_types() {
        with_locked_state(|| {
            let memory_types = [
                (GcdMemoryType::SystemMemory, 0x1A00000),
                (GcdMemoryType::Reserved, 0x1B00000),
                (GcdMemoryType::MemoryMappedIo, 0x1C00000),
                (GcdMemoryType::Persistent, 0x1D00000),
            ];

            // Add different memory types
            for (mem_type, base) in memory_types.iter() {
                let result = add_memory_space(*mem_type, *base, 0x10000, efi::MEMORY_WB);
                assert_eq!(result, efi::Status::SUCCESS, "Should add memory space for type {mem_type:?}");
            }

            // Verify each memory type can be retrieved correctly
            for (expected_type, base) in memory_types.iter() {
                let mut descriptor = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
                let result = get_memory_space_descriptor(*base, descriptor.as_mut_ptr());

                assert_eq!(result, efi::Status::SUCCESS, "Should get descriptor for type {expected_type:?}");

                let descriptor = unsafe { descriptor.assume_init() };
                assert_eq!(descriptor.memory_type, *expected_type, "Memory type should match for {expected_type:?}");
                assert_eq!(descriptor.base_address, *base, "Base address should match for type {expected_type:?}");
            }
        });
    }

    #[test]
    fn test_get_memory_space_descriptor_different_capabilities() {
        with_locked_state(|| {
            let capabilities_tests = [
                (0x1E00000, efi::MEMORY_WB),
                (0x1F00000, efi::MEMORY_WT),
                (0x2000000, efi::MEMORY_UC),
                (0x2100000, efi::MEMORY_WB | efi::MEMORY_WT),
                (0x2200000, efi::MEMORY_XP | efi::MEMORY_RO),
            ];

            // Add memory spaces with different capabilities
            for (base, capabilities) in capabilities_tests.iter() {
                let result = add_memory_space(GcdMemoryType::SystemMemory, *base, 0x10000, *capabilities);
                assert_eq!(
                    result,
                    efi::Status::SUCCESS,
                    "Should add memory space with capabilities 0x{capabilities:x}",
                );
            }

            // Verify capabilities are preserved (may have additional flags)
            for (base, expected_capabilities) in capabilities_tests.iter() {
                let mut descriptor = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
                let result = get_memory_space_descriptor(*base, descriptor.as_mut_ptr());

                assert_eq!(
                    result,
                    efi::Status::SUCCESS,
                    "Should get descriptor for capabilities 0x{expected_capabilities:x}",
                );

                let descriptor = unsafe { descriptor.assume_init() };
                // Check that our requested capabilities are present (GCD may add additional flags)
                assert!(
                    descriptor.capabilities & expected_capabilities == *expected_capabilities,
                    "Requested capabilities should be present. Expected: 0x{:x}, Got: 0x{:x}",
                    expected_capabilities,
                    descriptor.capabilities
                );
            }
        });
    }

    #[test]
    fn test_get_memory_space_descriptor_boundary_addresses() {
        with_locked_state(|| {
            let base = 0x2300000;
            let length = 0x10000;

            let result = add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB);
            assert_eq!(result, efi::Status::SUCCESS, "Should add memory space");

            let mut descriptor = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            let result = get_memory_space_descriptor(base, descriptor.as_mut_ptr());
            assert_eq!(result, efi::Status::SUCCESS, "Should get descriptor at base address");

            let mut descriptor = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            let result = get_memory_space_descriptor(base + length - 1, descriptor.as_mut_ptr());
            assert_eq!(result, efi::Status::SUCCESS, "Should get descriptor at last valid address");

            let mut descriptor = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            let result = get_memory_space_descriptor(base - 1, descriptor.as_mut_ptr());
            assert_eq!(result, efi::Status::SUCCESS, "Should get descriptor at address before base");

            let mut descriptor = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            let result = get_memory_space_descriptor(base + length, descriptor.as_mut_ptr());
            assert_eq!(result, efi::Status::SUCCESS, "Should get descriptor at address after end of range");
        });
    }

    #[test]
    fn test_set_memory_space_attributes_success_and_readback() {
        with_locked_state(|| {
            let base = 0x2400000;
            let length = 0x2000; // 2 pages

            // Prepare a region
            assert_eq!(
                add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB),
                efi::Status::SUCCESS
            );

            // Allow changing RO/XP and keep WB. Also include RP to continue supporting current attributes.
            let allowed = efi::MEMORY_RO | efi::MEMORY_XP | efi::MEMORY_WB | efi::MEMORY_RP;
            assert_eq!(set_memory_space_capabilities(base, length, allowed), efi::Status::SUCCESS);

            // Apply RO + XP + keep WB caching
            let attrs = efi::MEMORY_RO | efi::MEMORY_XP | efi::MEMORY_WB;
            let s = set_memory_space_attributes(base, length, attrs);
            assert_eq!(s, efi::Status::SUCCESS);

            // Read back and verify bits are set
            let mut d = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            assert_eq!(get_memory_space_descriptor(base, d.as_mut_ptr()), efi::Status::SUCCESS);
            let d = unsafe { d.assume_init() };
            assert_eq!(d.base_address, base);
            assert_eq!(d.length, length);
            assert!(d.attributes & attrs == attrs, "expected attrs 0x{:x} to be set in 0x{:x}", attrs, d.attributes);
        });
    }

    #[test]
    fn test_set_memory_space_attributes_partial_range_only_affects_subset() {
        with_locked_state(|| {
            let base = 0x2410000;
            let length = 0x4000; // 4 pages
            assert_eq!(
                add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB),
                efi::Status::SUCCESS
            );

            // Allow RO and keep existing WB/XP so current attributes remain supported. Include RP to cover current attrs.
            assert_eq!(
                set_memory_space_capabilities(
                    base,
                    length,
                    efi::MEMORY_RO | efi::MEMORY_WB | efi::MEMORY_XP | efi::MEMORY_RP
                ),
                efi::Status::SUCCESS
            );

            // Change attributes for first page only
            let first_len = 0x1000u64;
            let attrs = efi::MEMORY_RO | efi::MEMORY_WB;
            let s = set_memory_space_attributes(base, first_len, attrs);
            assert_eq!(s, efi::Status::SUCCESS);

            // The first page should have RO set
            let mut d0 = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            assert_eq!(get_memory_space_descriptor(base, d0.as_mut_ptr()), efi::Status::SUCCESS);
            let d0 = unsafe { d0.assume_init() };
            assert!(d0.attributes & efi::MEMORY_RO != 0);

            // A later page should not necessarily have RO (split expected). We only assert that RO is not set there.
            let mut d1 = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            assert_eq!(get_memory_space_descriptor(base + 0x3000, d1.as_mut_ptr()), efi::Status::SUCCESS);
            let d1 = unsafe { d1.assume_init() };
            assert!(d1.attributes & efi::MEMORY_RO == 0, "RO should not be set on untouched pages");
        });
    }

    #[test]
    fn test_set_memory_space_attributes_not_ready() {
        with_locked_state(|| {
            unsafe { GCD.reset() };
            let s = set_memory_space_attributes(0x2421000, 0x1000, efi::MEMORY_WB);
            assert_eq!(s, efi::Status::NOT_READY);
        });
    }

    // Note: We intentionally do not test out-of-range behavior for set_memory_space_attributes here,
    // as the debug build asserts on internal GCD errors for this path. The out-of-range case is covered
    // by set_memory_space_capabilities tests above, which return UNSUPPORTED without asserting.

    #[test]
    fn test_get_memory_space_map_invalid_parameters() {
        with_locked_state(|| {
            let mut out_count: usize = 0;
            let mut out_ptr: *mut dxe_services::MemorySpaceDescriptor = core::ptr::null_mut();

            let s = get_memory_space_map(core::ptr::null_mut(), &mut out_ptr);
            assert_eq!(s, efi::Status::INVALID_PARAMETER);

            let s = get_memory_space_map(&mut out_count, core::ptr::null_mut());
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_get_memory_space_map_not_ready() {
        with_locked_state(|| {
            unsafe { GCD.reset() };

            let mut out_count: usize = 0;
            let mut out_ptr: *mut dxe_services::MemorySpaceDescriptor = core::ptr::null_mut();

            let s = get_memory_space_map(&mut out_count, &mut out_ptr);
            assert_eq!(s, efi::Status::NOT_READY, "Expected NOT_READY when GCD is uninitialized");
        });
    }

    #[test]
    fn test_get_memory_space_map_success_and_contents() {
        with_locked_state(|| {
            unsafe {
                crate::test_support::reset_allocators();
            }

            let expected_count = GCD.memory_descriptor_count();
            let mut expected: Vec<dxe_services::MemorySpaceDescriptor> = Vec::with_capacity(expected_count + 10);
            GCD.get_memory_descriptors(&mut expected).expect("get_memory_descriptors failed");
            assert!(!expected.is_empty());

            let mut out_count: usize = 0;
            let mut out_ptr: *mut dxe_services::MemorySpaceDescriptor = core::ptr::null_mut();
            let s = get_memory_space_map(&mut out_count, &mut out_ptr);
            assert_eq!(s, efi::Status::SUCCESS);
            assert_eq!(out_count, expected.len());
            assert!(!out_ptr.is_null());

            let out_slice = unsafe { core::slice::from_raw_parts(out_ptr, out_count) };
            assert_eq!(out_slice, expected.as_slice());

            assert!(crate::allocator::core_free_pool(out_ptr as *mut core::ffi::c_void).is_ok());
        });
    }

    #[test]
    fn test_get_memory_space_map_with_additional_regions() {
        with_locked_state(|| {
            unsafe {
                crate::test_support::reset_allocators();
            }

            // Add a few extra regions of varying types
            let _ = add_memory_space(GcdMemoryType::SystemMemory, 0x2600000, 0x20000, efi::MEMORY_WB);
            let _ = add_memory_space(GcdMemoryType::Reserved, 0x2700000, 0x10000, efi::MEMORY_UC | efi::MEMORY_XP);
            let _ = add_memory_space(GcdMemoryType::MemoryMappedIo, 0x2800000, 0x30000, efi::MEMORY_UC);

            // Fetch expected
            let expected_count = GCD.memory_descriptor_count();
            let mut expected: Vec<dxe_services::MemorySpaceDescriptor> = Vec::with_capacity(expected_count + 10);
            GCD.get_memory_descriptors(&mut expected).expect("get_memory_descriptors failed");
            assert!(expected.len() >= 3);

            // Call API
            let mut out_count: usize = 0;
            let mut out_ptr: *mut dxe_services::MemorySpaceDescriptor = core::ptr::null_mut();
            let s = get_memory_space_map(&mut out_count, &mut out_ptr);
            assert_eq!(s, efi::Status::SUCCESS);
            assert_eq!(out_count, expected.len());

            // Verify first and last few entries match (order should be the same as GCD enumeration)
            let out_slice = unsafe { core::slice::from_raw_parts(out_ptr, out_count) };
            assert_eq!(out_slice, expected.as_slice());

            // cleanup
            assert!(crate::allocator::core_free_pool(out_ptr as *mut core::ffi::c_void).is_ok());
        });
    }

    #[test]
    fn test_get_io_space_map_invalid_parameters() {
        with_locked_state(|| {
            let mut out_count: usize = 0;
            let mut out_ptr: *mut dxe_services::IoSpaceDescriptor = core::ptr::null_mut();

            let s = get_io_space_map(core::ptr::null_mut(), &mut out_ptr);
            assert_eq!(s, efi::Status::INVALID_PARAMETER);

            let s = get_io_space_map(&mut out_count, core::ptr::null_mut());
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_get_io_space_map_not_ready() {
        with_locked_state(|| {
            unsafe { GCD.reset() };

            let mut out_count: usize = 0;
            let mut out_ptr: *mut dxe_services::IoSpaceDescriptor = core::ptr::null_mut();

            let s = get_io_space_map(&mut out_count, &mut out_ptr);
            assert_eq!(s, efi::Status::NOT_READY, "Expected NOT_READY when GCD is uninitialized");
        });
    }

    #[test]
    fn test_get_io_space_map_success_and_contents() {
        with_locked_state(|| {
            unsafe {
                crate::test_support::reset_allocators();
            }

            let expected_count = GCD.io_descriptor_count();
            let mut expected: Vec<dxe_services::IoSpaceDescriptor> = Vec::with_capacity(expected_count + 10);
            GCD.get_io_descriptors(&mut expected).expect("get_io_descriptors failed");
            assert!(!expected.is_empty());

            let mut out_count: usize = 0;
            let mut out_ptr: *mut dxe_services::IoSpaceDescriptor = core::ptr::null_mut();
            let s = get_io_space_map(&mut out_count, &mut out_ptr);
            assert_eq!(s, efi::Status::SUCCESS);
            assert_eq!(out_count, expected.len());
            assert!(!out_ptr.is_null());

            let out_slice = unsafe { core::slice::from_raw_parts(out_ptr, out_count) };
            assert_eq!(out_slice, expected.as_slice());

            assert!(crate::allocator::core_free_pool(out_ptr as *mut core::ffi::c_void).is_ok());
        });
    }

    #[test]
    fn test_get_io_space_map_with_additional_regions() {
        with_locked_state(|| {
            unsafe {
                crate::test_support::reset_allocators();
            }

            assert_eq!(add_io_space(GcdIoType::Io, 0x2000, 0x100), efi::Status::SUCCESS);
            assert_eq!(add_io_space(GcdIoType::Reserved, 0x2400, 0x80), efi::Status::SUCCESS);
            assert_eq!(add_io_space(GcdIoType::Io, 0x2600, 0x180), efi::Status::SUCCESS);

            let expected_count = GCD.io_descriptor_count();
            let mut expected: Vec<dxe_services::IoSpaceDescriptor> = Vec::with_capacity(expected_count + 10);
            GCD.get_io_descriptors(&mut expected).expect("get_io_descriptors failed");
            assert!(!expected.is_empty());

            let mut out_count: usize = 0;
            let mut out_ptr: *mut dxe_services::IoSpaceDescriptor = core::ptr::null_mut();
            let s = get_io_space_map(&mut out_count, &mut out_ptr);
            assert_eq!(s, efi::Status::SUCCESS);
            assert_eq!(out_count, expected.len());

            let out_slice = unsafe { core::slice::from_raw_parts(out_ptr, out_count) };
            assert_eq!(out_slice, expected.as_slice());

            assert!(crate::allocator::core_free_pool(out_ptr as *mut core::ffi::c_void).is_ok());
        });
    }

    #[test]
    fn test_set_memory_space_capabilities_success() {
        with_locked_state(|| {
            // Add a page-aligned region we can operate on
            let base = 0x2A00000;
            let length = 0x2000; // 2 pages
            assert_eq!(
                add_memory_space(GcdMemoryType::SystemMemory, base, length, efi::MEMORY_WB),
                efi::Status::SUCCESS
            );

            // Set a combination of reasonable capabilities
            let caps = efi::MEMORY_RP | efi::MEMORY_RO | efi::MEMORY_XP;
            let s = set_memory_space_capabilities(base, length, caps);
            assert_eq!(s, efi::Status::SUCCESS);

            // Verify capabilities include the requested bits
            let mut d = core::mem::MaybeUninit::<dxe_services::MemorySpaceDescriptor>::uninit();
            assert_eq!(get_memory_space_descriptor(base, d.as_mut_ptr()), efi::Status::SUCCESS);
            let d = unsafe { d.assume_init() };
            assert_eq!(d.base_address, base);
            assert!(d.capabilities & caps == caps, "Expected caps 0x{:x} to be set in 0x{:x}", caps, d.capabilities);
        });
    }

    #[test]
    fn test_set_memory_space_capabilities_zero_length_invalid_param() {
        with_locked_state(|| {
            let s = set_memory_space_capabilities(0x2B00000, 0, efi::MEMORY_WB);
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_set_memory_space_capabilities_not_ready() {
        with_locked_state(|| {
            // Force GCD to an uninitialized state
            unsafe { GCD.reset() };
            let s = set_memory_space_capabilities(0x200000, 0x1000, efi::MEMORY_WB);
            assert_eq!(s, efi::Status::NOT_READY, "Expected NOT_READY when GCD is reset");
        });
    }

    #[test]
    fn test_set_memory_space_capabilities_unaligned_length() {
        with_locked_state(|| {
            // Add a valid region first
            let base = 0x2C00000;
            let _ = add_memory_space(GcdMemoryType::SystemMemory, base, 0x4000, efi::MEMORY_WB);
            // Use an unaligned length
            let s = set_memory_space_capabilities(base, 0x1234, efi::MEMORY_WB);
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_set_memory_space_capabilities_unaligned_base() {
        with_locked_state(|| {
            // Add a valid region first
            let base = 0x2D00000;
            let _ = add_memory_space(GcdMemoryType::SystemMemory, base, 0x4000, efi::MEMORY_WB);
            // Use an unaligned base
            let s = set_memory_space_capabilities(base + 1, 0x1000, efi::MEMORY_WB);
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_set_memory_space_capabilities_out_of_range_unsupported() {
        with_locked_state(|| {
            // The test GCD uses 48-bit physical address space
            let max_addr = 1u64 << 48;
            // Choose a base such that base + len > maximum_address
            let base = max_addr - 0x1000;
            let len = 0x2000;
            let s = set_memory_space_capabilities(base, len, efi::MEMORY_WB);
            assert_eq!(s, efi::Status::UNSUPPORTED);
        });
    }

    #[test]
    fn test_add_io_space_success_io() {
        with_locked_state(|| {
            let base = 0x2000u64;
            let len = 0x100u64;
            let s = add_io_space(GcdIoType::Io, base, len);
            assert_eq!(s, efi::Status::SUCCESS);

            // Verify via descriptor query
            let mut desc = core::mem::MaybeUninit::<dxe_services::IoSpaceDescriptor>::uninit();
            let s = get_io_space_descriptor(base, desc.as_mut_ptr());
            assert_eq!(s, efi::Status::SUCCESS);
            let desc = unsafe { desc.assume_init() };
            assert_eq!(desc.base_address, base);
            assert_eq!(desc.length, len);
            assert_eq!(desc.io_type, GcdIoType::Io);
        });
    }

    #[test]
    fn test_add_io_space_success_reserved() {
        with_locked_state(|| {
            let base = 0x3000u64;
            let len = 0x80u64;
            let s = add_io_space(GcdIoType::Reserved, base, len);
            assert_eq!(s, efi::Status::SUCCESS);

            let mut desc = core::mem::MaybeUninit::<dxe_services::IoSpaceDescriptor>::uninit();
            assert_eq!(get_io_space_descriptor(base, desc.as_mut_ptr()), efi::Status::SUCCESS);
            let desc = unsafe { desc.assume_init() };
            assert_eq!(desc.base_address, base);
            assert_eq!(desc.length, len);
            assert_eq!(desc.io_type, GcdIoType::Reserved);
        });
    }

    #[test]
    fn test_add_io_space_zero_length_invalid_parameter() {
        with_locked_state(|| {
            let s = add_io_space(GcdIoType::Io, 0x1000, 0);
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_add_io_space_out_of_range_unsupported() {
        with_locked_state(|| {
            // IO address space is 16 bits in tests => maximum address 0x10000
            // Pick a range that exceeds the maximum
            let s = add_io_space(GcdIoType::Io, 0xFF80, 0x200);
            assert_eq!(s, efi::Status::UNSUPPORTED);
        });
    }

    #[test]
    fn test_add_io_space_not_ready() {
        with_locked_state(|| {
            // Force GCD to uninitialized state for IO
            unsafe { GCD.reset() };
            let s = add_io_space(GcdIoType::Io, 0x1000, 0x10);
            assert_eq!(s, efi::Status::NOT_READY);
        });
    }

    #[test]
    fn test_add_io_space_overlap_access_denied() {
        with_locked_state(|| {
            let base = 0x4000u64;
            let len = 0x100u64;
            assert_eq!(add_io_space(GcdIoType::Io, base, len), efi::Status::SUCCESS);
            // Overlapping add should be denied since region is no longer NonExistent
            let s = add_io_space(GcdIoType::Reserved, base, 0x80);
            assert_eq!(s, efi::Status::ACCESS_DENIED);
        });
    }

    #[test]
    fn test_allocate_io_space_null_base_ptr_invalid_parameter() {
        with_locked_state(|| {
            let s = allocate_io_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdIoType::Io,
                3,
                0x10,
                core::ptr::null_mut(),
                1 as _,
                core::ptr::null_mut(),
            );
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_allocate_io_space_not_ready() {
        with_locked_state(|| {
            unsafe { GCD.reset() };
            let mut out: efi::PhysicalAddress = 0;
            let s = allocate_io_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdIoType::Io,
                3,
                0x10,
                &mut out,
                1 as _,
                core::ptr::null_mut(),
            );
            assert_eq!(s, efi::Status::NOT_READY);
        });
    }

    #[test]
    fn test_allocate_io_space_zero_length_invalid_parameter() {
        with_locked_state(|| {
            // Need an IO region present to allocate from, but length 0 should still fail early
            assert_eq!(add_io_space(GcdIoType::Io, 0x2000, 0x200), efi::Status::SUCCESS);
            let mut out: efi::PhysicalAddress = 0;
            let s = allocate_io_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdIoType::Io,
                3,
                0,
                &mut out,
                1 as _,
                core::ptr::null_mut(),
            );
            assert_ne!(s, efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_allocate_io_space_null_image_handle_invalid_parameter() {
        with_locked_state(|| {
            assert_eq!(add_io_space(GcdIoType::Io, 0x2200, 0x200), efi::Status::SUCCESS);
            let mut out: efi::PhysicalAddress = 0;
            let s = allocate_io_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdIoType::Io,
                3,
                0x20,
                &mut out,
                core::ptr::null_mut(), // null image handle should be invalid
                core::ptr::null_mut(),
            );
            assert_ne!(s, efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_allocate_io_space_bottom_up_success_and_sets_base() {
        with_locked_state(|| {
            // Prepare IO space to allocate from
            assert_eq!(add_io_space(GcdIoType::Io, 0x3000, 0x300), efi::Status::SUCCESS);

            let mut out: efi::PhysicalAddress = 0;
            let s = allocate_io_space(
                dxe_services::GcdAllocateType::AnySearchBottomUp,
                GcdIoType::Io,
                3,    // 8-byte alignment
                0x20, // 32 bytes
                &mut out,
                1 as _, // valid image handle
                core::ptr::null_mut(),
            );
            assert_eq!(s, efi::Status::SUCCESS);
            assert!((0x3000..0x3300).contains(&out));
            assert_eq!(out & 0x7, 0, "alignment not respected");
        });
    }

    #[test]
    fn test_allocate_io_space_top_down_success() {
        with_locked_state(|| {
            assert_eq!(add_io_space(GcdIoType::Io, 0x4000, 0x400), efi::Status::SUCCESS);

            let mut out: efi::PhysicalAddress = 0;
            let s = allocate_io_space(
                dxe_services::GcdAllocateType::AnySearchTopDown,
                GcdIoType::Io,
                4,    // 16-byte alignment
                0x40, // 64 bytes
                &mut out,
                1 as _,
                core::ptr::null_mut(),
            );
            assert_eq!(s, efi::Status::SUCCESS);
            assert!((0x4000..0x4400).contains(&out));
            assert_eq!(out & 0xF, 0);
        });
    }

    #[test]
    fn test_allocate_io_space_address_success() {
        with_locked_state(|| {
            assert_eq!(add_io_space(GcdIoType::Io, 0x5000, 0x200), efi::Status::SUCCESS);

            let mut desired: efi::PhysicalAddress = 0x5080;
            let s = allocate_io_space(
                dxe_services::GcdAllocateType::Address,
                GcdIoType::Io,
                0,    // no extra alignment
                0x20, // 32 bytes
                &mut desired,
                1 as _,
                core::ptr::null_mut(),
            );
            assert_eq!(s, efi::Status::SUCCESS);
            assert_eq!(desired, 0x5080);
        });
    }

    #[test]
    fn test_allocate_io_space_address_unsupported_when_out_of_io_range() {
        with_locked_state(|| {
            let mut desired: efi::PhysicalAddress = 0xFF80;
            let s = allocate_io_space(
                dxe_services::GcdAllocateType::Address,
                GcdIoType::Io,
                0,
                0x200,
                &mut desired,
                1 as _,
                core::ptr::null_mut(),
            );
            assert_eq!(s, efi::Status::UNSUPPORTED);
        });
    }

    #[test]
    fn test_allocate_io_space_max_address_bottom_up_respected() {
        with_locked_state(|| {
            assert_eq!(add_io_space(GcdIoType::Io, 0x6000, 0x400), efi::Status::SUCCESS);

            let mut limit: efi::PhysicalAddress = 0x6100;
            let s = allocate_io_space(
                dxe_services::GcdAllocateType::MaxAddressSearchBottomUp,
                GcdIoType::Io,
                3,
                0x20,
                &mut limit,
                1 as _,
                core::ptr::null_mut(),
            );
            assert_eq!(s, efi::Status::SUCCESS);
            assert!(limit <= 0x6100);
        });
    }

    #[test]
    fn test_free_io_space_success() {
        with_locked_state(|| {
            let base = 0x7000u64;
            let len = 0x80u64;
            assert_eq!(add_io_space(GcdIoType::Io, base, len), efi::Status::SUCCESS);

            let mut desired = base;
            assert_eq!(
                allocate_io_space(
                    dxe_services::GcdAllocateType::Address,
                    GcdIoType::Io,
                    0,
                    len,
                    &mut desired,
                    1 as _,
                    core::ptr::null_mut(),
                ),
                efi::Status::SUCCESS
            );

            let s = free_io_space(base, len);
            assert_eq!(s, efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_free_io_space_zero_length_invalid_parameter() {
        with_locked_state(|| {
            assert_eq!(free_io_space(0x1000, 0), efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_free_io_space_not_ready() {
        with_locked_state(|| {
            unsafe { GCD.reset() };
            let s = free_io_space(0x1000, 0x10);
            assert_eq!(s, efi::Status::NOT_READY);
        });
    }

    #[test]
    fn test_free_io_space_out_of_range_unsupported() {
        with_locked_state(|| {
            let s = free_io_space(0xFF80, 0x200);
            assert_eq!(s, efi::Status::UNSUPPORTED);
        });
    }

    #[test]
    fn test_free_io_space_unallocated_not_found() {
        with_locked_state(|| {
            // Add region but do not allocate
            assert_eq!(add_io_space(GcdIoType::Io, 0x8000, 0x100), efi::Status::SUCCESS);
            let s = free_io_space(0x8000, 0x20);
            assert_eq!(s, efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_free_io_space_double_free() {
        with_locked_state(|| {
            assert_eq!(add_io_space(GcdIoType::Io, 0x9000, 0x100), efi::Status::SUCCESS);

            let mut desired: efi::PhysicalAddress = 0x9000;
            assert_eq!(
                allocate_io_space(
                    dxe_services::GcdAllocateType::Address,
                    GcdIoType::Io,
                    0,
                    0x40,
                    &mut desired,
                    1 as _,
                    core::ptr::null_mut(),
                ),
                efi::Status::SUCCESS
            );
            assert_eq!(free_io_space(0x9000, 0x40), efi::Status::SUCCESS);

            // second free should fail with NOT_FOUND
            assert_eq!(free_io_space(0x9000, 0x40), efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_free_io_space_partial_free() {
        with_locked_state(|| {
            assert_eq!(add_io_space(GcdIoType::Io, 0xA000, 0x100), efi::Status::SUCCESS);

            // allocate 0x80 bytes starting at 0xA000
            let mut desired: efi::PhysicalAddress = 0xA000;
            assert_eq!(
                allocate_io_space(
                    dxe_services::GcdAllocateType::Address,
                    GcdIoType::Io,
                    0,
                    0x80,
                    &mut desired,
                    1 as _,
                    core::ptr::null_mut(),
                ),
                efi::Status::SUCCESS
            );

            // Free first half
            assert_eq!(free_io_space(0xA000, 0x40), efi::Status::SUCCESS);
            // Free second half
            assert_eq!(free_io_space(0xA000 + 0x40, 0x40), efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_remove_io_space_success() {
        with_locked_state(|| {
            let base = 0xB000u64;
            let len = 0x80u64;
            assert_eq!(add_io_space(GcdIoType::Io, base, len), efi::Status::SUCCESS);
            assert_eq!(remove_io_space(base, len), efi::Status::SUCCESS);
        });
    }

    #[test]
    fn test_remove_io_space_zero_length_invalid_parameter() {
        with_locked_state(|| {
            assert_eq!(remove_io_space(0x1000, 0), efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_remove_io_space_not_ready() {
        with_locked_state(|| {
            unsafe { GCD.reset() };
            assert_eq!(remove_io_space(0x1000, 0x10), efi::Status::NOT_READY);
        });
    }

    #[test]
    fn test_remove_io_space_out_of_range_unsupported() {
        with_locked_state(|| {
            // IO address space is 16 bits in tests => maximum address 0x10000
            assert_eq!(remove_io_space(0xFF80, 0x200), efi::Status::UNSUPPORTED);
        });
    }

    #[test]
    fn test_remove_io_space_not_found_when_never_added() {
        with_locked_state(|| {
            assert_eq!(remove_io_space(0xC000, 0x40), efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_remove_io_space_double_remove_not_found() {
        with_locked_state(|| {
            let base = 0xE000u64;
            let len = 0x40u64;
            assert_eq!(add_io_space(GcdIoType::Io, base, len), efi::Status::SUCCESS);
            assert_eq!(remove_io_space(base, len), efi::Status::SUCCESS);
            assert_eq!(remove_io_space(base, len), efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_dispatch_returns_not_found_when_nothing_to_do() {
        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            let s = MockCore::dispatch_efiapi();
            assert_eq!(s, efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_dispatch_is_idempotent_and_consistently_not_found() {
        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            let s1 = MockCore::dispatch_efiapi();
            let s2 = MockCore::dispatch_efiapi();
            assert_eq!(s1, efi::Status::NOT_FOUND);
            assert_eq!(s2, efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_dispatch_with_installed_fv_still_not_found() {
        use crate::test_collateral;
        use std::{fs::File, io::Read};

        let mut file = File::open(test_collateral!("DXEFV.Fv")).unwrap();
        let mut fv: Vec<u8> = Vec::new();
        file.read_to_end(&mut fv).expect("failed to read test file");

        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            // Install the FV to obtain a real handle
            unsafe { CORE.pi_dispatcher.install_firmware_volume(fv.as_ptr() as u64, None).unwrap() };

            // Wrapper should still surface NOT_FOUND (no pending drivers to dispatch in tests)
            let s = MockCore::dispatch_efiapi();
            assert_eq!(s, efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_schedule_invalid_parameter_when_file_is_null() {
        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            // Passing a null file GUID pointer should return INVALID_PARAMETER
            let s = MockCore::schedule_efiapi(core::ptr::null_mut(), core::ptr::null());
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_schedule_not_found_without_pending_drivers() {
        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            // Any GUID is fine; there are no pending drivers in this test harness
            let guid = efi::Guid::from_fields(0, 0, 0, 0, 0, &[0, 0, 0, 0, 0, 0]);
            let s = MockCore::schedule_efiapi(core::ptr::null_mut(), &guid);
            assert_eq!(s, efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_schedule_with_installed_fv_returns_not_found() {
        use crate::test_collateral;
        use std::{fs::File, io::Read};
        use uuid::Uuid;

        let mut file = File::open(test_collateral!("DXEFV.Fv")).unwrap();
        let mut fv: Vec<u8> = Vec::new();
        file.read_to_end(&mut fv).expect("failed to read test file");

        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            // Install the FV to obtain a real handle
            let handle = unsafe { CORE.pi_dispatcher.install_firmware_volume(fv.as_ptr() as u64, None).unwrap() };

            // Use the same GUID as the dispatcher tests; wrapper should map NotFound correctly
            let file_guid = efi::Guid::from_bytes(Uuid::from_u128(0x1fa1f39e_feff_4aae_bd7b_38a070a3b609).as_bytes());
            let s = MockCore::schedule_efiapi(handle, &file_guid);
            assert_eq!(s, efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_trust_invalid_parameter_when_file_is_null() {
        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            let s = MockCore::trust_efiapi(core::ptr::null_mut(), core::ptr::null());
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_trust_not_found_without_pending_drivers() {
        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            // Any GUID and handle are fine; there are no pending drivers in this harness
            let guid = efi::Guid::from_fields(0, 0, 0, 0, 0, &[1, 2, 3, 4, 5, 6]);
            let s = MockCore::trust_efiapi(core::ptr::null_mut(), &guid);
            assert_eq!(s, efi::Status::NOT_FOUND);
        });
    }

    #[test]
    fn test_process_firmware_volume_invalid_parameters() {
        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            let mut out_handle: efi::Handle = core::ptr::null_mut();

            // Null header
            let s = MockCore::process_firmware_volume_efiapi(core::ptr::null(), 0, &mut out_handle);
            assert_eq!(s, efi::Status::INVALID_PARAMETER);

            // Null output handle pointer
            let bogus = 0xDEAD_BEEFu64 as *const core::ffi::c_void;
            let s = MockCore::process_firmware_volume_efiapi(bogus, 0, core::ptr::null_mut());
            assert_eq!(s, efi::Status::INVALID_PARAMETER);
        });
    }

    #[test]
    fn test_process_firmware_volume_volume_corrupted_on_bad_input() {
        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            // Provide a tiny, obviously invalid buffer
            let bad_buf: [u8; 16] = [0u8; 16];
            let mut out_handle: efi::Handle = core::ptr::null_mut();
            let s = MockCore::process_firmware_volume_efiapi(
                bad_buf.as_ptr() as *const core::ffi::c_void,
                bad_buf.len(),
                &mut out_handle,
            );
            assert_eq!(s, efi::Status::VOLUME_CORRUPTED);
        });
    }

    #[test]
    fn test_process_firmware_volume_success_with_real_fv() {
        use crate::test_collateral;
        use std::{fs::File, io::Read};

        let mut file = File::open(test_collateral!("DXEFV.Fv")).unwrap();
        let mut fv: Vec<u8> = Vec::new();
        file.read_to_end(&mut fv).expect("failed to read test file");

        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            let mut out_handle: efi::Handle = core::ptr::null_mut();
            let s = MockCore::process_firmware_volume_efiapi(
                fv.as_ptr() as *const core::ffi::c_void,
                fv.len(),
                &mut out_handle,
            );

            assert_eq!(s, efi::Status::SUCCESS);
            assert!(!out_handle.is_null(), "process_firmware_volume should return a valid handle");
        });
    }

    #[test]
    fn test_install_dxe_services_table_installs_config_table_with_valid_crc_and_functions() {
        with_locked_state(|| {
            static CORE: MockCore = MockCore::new(NullSectionExtractor::new());
            CORE.override_instance();
            // Initialize a fresh System Table (requires GCD already initialized by with_locked_state)
            crate::systemtables::init_system_table();

            // Get a mutable reference to the system table
            let mut st_guard = crate::systemtables::SYSTEM_TABLE.lock();
            let st = st_guard.as_mut().expect("System Table not initialized");

            // Before: no configuration tables are expected on a fresh init
            assert_eq!(st.system_table().number_of_table_entries, 0);

            // Act: install the DXE Services table
            CORE.install_dxe_services_table(st);

            // After: one entry should exist and match DXE_SERVICES_TABLE_GUID
            let st_ref = st.system_table();
            assert_eq!(st_ref.number_of_table_entries, 1);
            assert!(!st_ref.configuration_table.is_null());

            let entries =
                unsafe { core::slice::from_raw_parts(st_ref.configuration_table, st_ref.number_of_table_entries) };

            let entry = entries
                .iter()
                .find(|e| e.vendor_guid == dxe_services::DXE_SERVICES_TABLE_GUID)
                .expect("DXE Services table entry not found in configuration table");
            assert!(!entry.vendor_table.is_null(), "DXE Services vendor_table pointer should be non-null");

            // Validate the contents of the installed DXE Services table
            let dxe_tbl = unsafe { &*(entry.vendor_table as *const dxe_services::DxeServicesTable) };

            // Header signature/revision should match what install_dxe_services_table sets
            assert_eq!(dxe_tbl.header.signature, efi::BOOT_SERVICES_SIGNATURE);
            assert_eq!(dxe_tbl.header.revision, efi::BOOT_SERVICES_REVISION);

            // Recompute CRC32 by zeroing the field in a local copy
            let mut copy = unsafe { core::ptr::read(dxe_tbl) };
            copy.header.crc32 = 0;
            let crc = crc32fast::hash(unsafe {
                core::slice::from_raw_parts(
                    (&copy as *const dxe_services::DxeServicesTable) as *const u8,
                    core::mem::size_of::<dxe_services::DxeServicesTable>(),
                )
            });
            assert_eq!(dxe_tbl.header.crc32, crc, "DXE Services table CRC32 should be valid");

            // Spot-check a few function pointers are correctly wired
            assert_eq!(dxe_tbl.add_memory_space as usize, add_memory_space as usize);
            assert_eq!(dxe_tbl.dispatch as usize, MockCore::dispatch_efiapi as usize);
            assert_eq!(dxe_tbl.process_firmware_volume as usize, MockCore::process_firmware_volume_efiapi as usize);
        });
    }
}