patina 21.1.1

Common types and functionality used in UEFI development.
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
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
//! UEFI Boot Services trait definition and implementations.
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!

#[cfg(feature = "global_allocator")]
pub mod global_allocator;

pub mod allocation;
pub mod boxed;
pub mod c_ptr;
pub mod event;
pub mod protocol_handler;
pub mod tpl;

#[cfg(any(test, feature = "mockall"))]
use mockall::automock;

use alloc::vec::Vec;
use c_ptr::{CMutPtr, CMutRef, CPtr, PtrMetadata};
use core::{
    any,
    ffi::c_void,
    fmt::Debug,
    mem::{self, MaybeUninit},
    option::Option,
    ptr::{self, NonNull},
};
use spin::Once;

use r_efi::efi;

use crate::{efi_types::EfiMemoryType, uefi_protocol::ProtocolInterface};
use allocation::{AllocType, MemoryMap};
use boxed::BootServicesBox;
use event::{EventNotifyCallback, EventTimerType, EventType};
use protocol_handler::{HandleSearchType, Registration};
use tpl::{Tpl, TplGuard};

/// This is the boot services used in the UEFI.
pub struct StandardBootServices {
    efi_boot_services: Once<*mut efi::BootServices>,
}

// Safety: efi::BootServices is not Sync/Send automatically due to the use of *mut c_void as part of function signatures
// within the struct. Those pointers are only used by spec-defined APIs. With respect to the efi_boot_services pointer
// itself, that is protected by the Once wrapper, and is not expected to change once initialized.
unsafe impl Sync for StandardBootServices {}
// Safety: See Sync impl above.
unsafe impl Send for StandardBootServices {}

impl StandardBootServices {
    /// Create a new StandardBootServices with the provided [efi::BootServices].
    pub fn new(efi_boot_services: *mut efi::BootServices) -> Self {
        let this = Self::new_uninit();
        this.init(efi_boot_services);
        this
    }

    /// Create a new StandardBootServices that has not been initialized.
    pub const fn new_uninit() -> Self {
        StandardBootServices { efi_boot_services: Once::new() }
    }

    /// Initialize the StandardBootServices.
    pub fn init(&self, efi_boot_services: *mut efi::BootServices) {
        // This struct never mutate the efi_boot_services.
        self.efi_boot_services.call_once(|| efi_boot_services);
    }

    /// Return true if StandardBootServices is initialized.
    pub fn is_init(&self) -> bool {
        self.efi_boot_services.is_completed()
    }

    // Returns the boot services pointer if initialized, panics otherwise.
    fn as_mut_ptr(&self) -> *mut efi::BootServices {
        *self.efi_boot_services.get().expect("Standard Boot Services is not initialized!")
    }
}

impl AsRef<StandardBootServices> for StandardBootServices {
    fn as_ref(&self) -> &StandardBootServices {
        self
    }
}

impl Clone for StandardBootServices {
    fn clone(&self) -> Self {
        if let Some(efi_boot_services) = self.efi_boot_services.get() {
            StandardBootServices::new(*efi_boot_services)
        } else {
            StandardBootServices::new_uninit()
        }
    }
}

impl Debug for StandardBootServices {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if !self.is_init() {
            return f.debug_struct("StandardBootServices").field("efi_boot_services", &"Not Initialized").finish();
        }

        // SAFETY: assume that boot services struct is not being externally modified while static reference is in use
        // In this case, if the struct is being modified, the debug print may be inaccurate, but it won't cause
        // undefined behavior beyond that.
        let bs = unsafe { &*self.as_mut_ptr() };
        f.debug_struct("StandardBootServices")
            .field("create_event", &bs.create_event)
            .field("create_event_ex", &bs.create_event_ex)
            .field("close_event", &bs.close_event)
            .field("signal_event", &bs.signal_event)
            .field("wait_for_event", &bs.wait_for_event)
            .field("check_event", &bs.check_event)
            .field("set_timer", &bs.set_timer)
            .field("raise_tpl", &bs.raise_tpl)
            .field("restore_tpl", &bs.restore_tpl)
            .field("allocate_page", &bs.allocate_pages)
            .field("free_pages", &bs.free_pages)
            .field("get_memory_map", &bs.get_memory_map)
            .field("allocate_pool", &bs.allocate_pool)
            .field("free_pool", &bs.free_pool)
            .field("install_protocol_interface", &bs.install_protocol_interface)
            .field("uninstall_protocol_interface", &bs.uninstall_protocol_interface)
            .field("reinstall_protocol_interface", &bs.reinstall_protocol_interface)
            .field("register_protocol_notify", &bs.register_protocol_notify)
            .field("locate_handle", &bs.locate_handle)
            .field("handle_protocol", &bs.handle_protocol)
            .field("locate_device_path", &bs.locate_device_path)
            .field("open_protocol", &bs.open_protocol)
            .field("close_protocol", &bs.close_protocol)
            .field("open_protocol_information", &bs.open_protocol_information)
            .field("connect_controller", &bs.connect_controller)
            .field("disconnect_controller", &bs.disconnect_controller)
            .field("protocols_per_handle", &bs.protocols_per_handle)
            .field("locate_handle_buffer", &bs.locate_handle_buffer)
            .field("locate_protocol", &bs.locate_protocol)
            .field("install_multiple_protocol_interfaces", &bs.install_multiple_protocol_interfaces)
            .field("uninstall_multiple_protocol_interfaces", &bs.uninstall_multiple_protocol_interfaces)
            .field("load_image", &bs.load_image)
            .field("start_image", &bs.start_image)
            .field("unload_image", &bs.unload_image)
            .field("exit", &bs.exit)
            .field("exit_boot_services", &bs.exit_boot_services)
            .field("set_watchdog_timer", &bs.set_watchdog_timer)
            .field("stall", &bs.stall)
            .field("copy_mem", &bs.copy_mem)
            .field("set_mem", &bs.set_mem)
            .field("get_next_monotonic_count", &bs.get_next_monotonic_count)
            .field("install_configuration_table", &bs.install_configuration_table)
            .field("calculate_crc32", &bs.calculate_crc32)
            .finish()
    }
}

/// Functions that are available *before* a successful call to EFI_BOOT_SERVICES.ExitBootServices().
#[cfg_attr(any(test, feature = "mockall"), automock)]
#[allow(clippy::needless_lifetimes)] //https://github.com/rust-lang/rust-clippy/issues/6622
pub trait BootServices {
    /// Create an event.
    ///
    /// [UEFI Spec Documentation: 7.1.1. EFI_BOOT_SERVICES.CreateEvent()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-createevent)
    fn create_event<T>(
        &self,
        event_type: EventType,
        notify_tpl: Tpl,
        notify_function: Option<EventNotifyCallback<T>>,
        notify_context: T,
    ) -> Result<efi::Event, efi::Status>
    where
        T: CPtr<'static> + 'static,
    {
        //SAFETY: ['StaticPtr`] generic is used to guaranteed that rust borowing and rules are meet.
        unsafe {
            self.create_event_unchecked(
                event_type,
                notify_tpl,
                mem::transmute::<
                    Option<extern "efiapi" fn(*mut c_void, T)>,
                    Option<extern "efiapi" fn(*mut c_void, *mut <T as c_ptr::CPtr<'_>>::Type)>,
                >(notify_function),
                notify_context.into_ptr() as *mut T::Type,
            )
        }
    }

    /// Use [`BootServices::create_event`] when possible.
    ///
    /// # Safety
    ///
    /// When calling this method, you have to make sure that *notify_context* pointer is **null** or all of the following is true:
    /// * The pointer must be properly aligned.
    /// * It must be "dereferenceable" into type `T`
    /// * It must remain a valid pointer for the lifetime of the event.
    /// * You must enforce Rust’s borrowing[^borrowing rules] rules rules.
    ///
    /// [^borrowing rules]:
    /// [Rust By Example Book: 15.3. Borrowing](https://doc.rust-lang.org/beta/rust-by-example/scope/borrow.html)
    unsafe fn create_event_unchecked<T: Sized + 'static>(
        &self,
        event_type: EventType,
        notify_tpl: Tpl,
        notify_function: Option<EventNotifyCallback<*mut T>>,
        notify_context: *mut T,
    ) -> Result<efi::Event, efi::Status>;

    /// Create an event in a group.
    ///
    /// [UEFI Spec Documentation: 7.1.2. EFI_BOOT_SERVICES.CreateEventEx()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-createeventex)
    fn create_event_ex<T>(
        &self,
        event_type: EventType,
        notify_tpl: Tpl,
        notify_function: Option<EventNotifyCallback<T>>,
        notify_context: T,
        event_group: &'static efi::Guid,
    ) -> Result<efi::Event, efi::Status>
    where
        T: CPtr<'static> + 'static,
    {
        //SAFETY: [`StaticPtr`] generic is used to guaranteed that rust borowing and rules are meet.
        unsafe {
            self.create_event_ex_unchecked(
                event_type,
                notify_tpl,
                mem::transmute::<
                    Option<extern "efiapi" fn(*mut c_void, T)>,
                    Option<extern "efiapi" fn(*mut c_void, *mut <T as c_ptr::CPtr<'_>>::Type)>,
                >(notify_function),
                notify_context.into_ptr() as *mut <T as CPtr>::Type,
                event_group,
            )
        }
    }

    /// Use [`BootServices::create_event_ex`] when possible.
    ///
    /// # Safety
    ///
    /// Make sure to comply to the same constraint as [`BootServices::create_event_unchecked`]
    unsafe fn create_event_ex_unchecked<T: Sized + 'static>(
        &self,
        event_type: EventType,
        notify_tpl: Tpl,
        notify_function: Option<EventNotifyCallback<*mut T>>,
        notify_context: *mut T,
        event_group: &'static efi::Guid,
    ) -> Result<efi::Event, efi::Status>;

    /// Close an event.
    ///
    /// [UEFI Spec Documentation: 7.1.3. EFI_BOOT_SERVICES.CloseEvent()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-closeevent)
    ///
    /// [^note]: It is safe to call *close_event* in the notify function.
    fn close_event(&self, event: efi::Event) -> Result<(), efi::Status>;

    /// Signals an event.
    ///
    /// [UEFI Spec Documentation: 7.1.4. EFI_BOOT_SERVICES.SignalEvent()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-signalevent)
    fn signal_event(&self, event: efi::Event) -> Result<(), efi::Status>;

    /// Stops execution until an event is signaled.
    ///
    /// [UEFI Spec Documentation: 7.1.5. EFI_BOOT_SERVICES.WaitForEvent()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-waitforevent)
    fn wait_for_event(&self, events: &mut [efi::Event]) -> Result<usize, efi::Status>;

    /// Checks whether an event is in the signaled state.
    ///
    /// [UEFI Spec Documentation: 7.1.6. EFI_BOOT_SERVICES.CheckEvent()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-checkevent)
    fn check_event(&self, event: efi::Event) -> Result<(), efi::Status>;

    /// Sets the type of timer and the trigger time for a timer event.
    ///
    /// [UEFI Spec Documentation: 7.1.7. EFI_BOOT_SERVICES.SetTimer()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-settimer)
    fn set_timer(&self, event: efi::Event, timer_type: EventTimerType, trigger_time: u64) -> Result<(), efi::Status>;

    /// Raises a task's priority level and returns a [`TplGuard`] that will restore the tpl when dropped.
    ///
    /// See [`BootServices::raise_tpl`] and [`BootServices::restore_tpl`] for more details.
    fn raise_tpl_guarded<'a>(&'a self, tpl: Tpl) -> TplGuard<'a, Self> {
        TplGuard { boot_services: self, retore_tpl: self.raise_tpl(tpl) }
    }

    /// Raises a task’s priority level and returns its previous level.
    ///
    /// [UEFI Spec Documentation: 7.1.8. EFI_BOOT_SERVICES.RaiseTPL()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-raisetpl)
    fn raise_tpl(&self, tpl: Tpl) -> Tpl;

    /// Restores a task’s priority level to its previous value.
    ///
    /// [UEFI Spec Documentation: 7.1.9. EFI_BOOT_SERVICES.RestoreTPL()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-restoretpl)
    fn restore_tpl(&self, tpl: Tpl);

    /// Allocates memory pages from the system.
    ///
    /// [UEFI Spec Documentation: 7.2.1. EFI_BOOT_SERVICES.AllocatePages()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-allocatepages)
    fn allocate_pages(
        &self,
        alloc_type: AllocType,
        memory_type: EfiMemoryType,
        nb_pages: usize,
    ) -> Result<usize, efi::Status>;

    /// Frees memory pages.
    ///
    /// [UEFI Spec Documentation: 7.2.2. EFI_BOOT_SERVICES.FreePages()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-freepages)
    fn free_pages(&self, address: usize, nb_pages: usize) -> Result<(), efi::Status>;

    /// Returns the current memory map.
    ///
    /// [UEFI Spec Documentation: 7.2.3. EFI_BOOT_SERVICES.GetMemoryMap()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-getmemorymap)
    fn get_memory_map<'a>(&'a self) -> Result<MemoryMap<'a, Self>, (efi::Status, usize)>;

    /// Allocates pool memory.
    ///
    /// [UEFI Spec Documentation: 7.2.4. EFI_BOOT_SERVICES.AllocatePool()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-allocatepool)
    fn allocate_pool(&self, pool_type: EfiMemoryType, size: usize) -> Result<*mut u8, efi::Status>;

    /// Allocates pool memory casted as given type.
    fn allocate_pool_for_type<T: 'static + Sized>(&self, pool_type: EfiMemoryType) -> Result<*mut T, efi::Status> {
        let ptr = self.allocate_pool(pool_type, mem::size_of::<T>())?;
        Ok(ptr as *mut T)
    }

    /// Returns pool memory to the system.
    ///
    /// [UEFI Spec Documentation: 7.2.5. EFI_BOOT_SERVICES.FreePool()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-freepool)
    fn free_pool(&self, buffer: *mut u8) -> Result<(), efi::Status>;

    /// Installs a protocol interface on a device handle.
    /// If the handle does not exist, it is created and added to the list of handles in the system.
    ///
    /// [UEFI Spec Documentation: 7.3.2. EFI_BOOT_SERVICES.InstallProtocolInterface()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-installprotocolinterface)
    ///
    /// ## Example
    /// ```rust ignore
    /// let key = match static_boot_services().install_protocol_interface(
    ///     Some(handle),
    ///     Box::new(protocol_interface),
    /// ) {
    ///     Ok((_handle, key)) => key,
    ///     Err((protocol_interface_box, status)) => return Err(status),
    /// };
    /// Ok(key)
    /// ```
    ///
    fn install_protocol_interface<T, R>(
        &self,
        handle: Option<efi::Handle>,
        protocol_interface: R,
    ) -> Result<(efi::Handle, PtrMetadata<'static, R>), efi::Status>
    where
        R: CMutRef<'static, Type = T> + 'static,
        T: ProtocolInterface + 'static,
    {
        let key = protocol_interface.metadata();

        let protocol_interface_ptr = match mem::size_of::<T>() {
            0 => ptr::null_mut(),
            _ => protocol_interface.into_mut_ptr() as *mut c_void,
        };

        // SAFETY: This is safe because ProtocolInterface provide the right guid for the interface.
        unsafe {
            match self.install_protocol_interface_unchecked(handle, &T::PROTOCOL_GUID, protocol_interface_ptr) {
                Ok(handle) => Ok((handle, key)),
                Err(status) => {
                    _ = key.try_into_original_ptr();
                    Err(status)
                }
            }
        }
    }

    /// Use [`BootServices::install_protocol_interface`] when possible.
    ///
    /// # Safety
    ///
    /// When calling this method, you have to make sure that if *interface* pointer is non-null, it is adhereing to
    /// the structure associated with the protocol.
    unsafe fn install_protocol_interface_unchecked(
        &self,
        handle: Option<efi::Handle>,
        protocol: &'static efi::Guid,
        interface: *mut c_void,
    ) -> Result<efi::Handle, efi::Status>;

    /// Removes a protocol interface from a device handle.
    ///
    /// [UEFI Spec Documentation: 7.3.3. EFI_BOOT_SERVICES.UninstallProtocolInterface()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-uninstallprotocolinterface)
    #[allow(clippy::not_unsafe_ptr_arg_deref)] //this is triggered by the fact that efi::Handle aliases to c_void, but they are opaque to the caller.
    fn uninstall_protocol_interface<T, R>(
        &self,
        handle: efi::Handle,
        key: PtrMetadata<'static, R>,
    ) -> Result<R, efi::Status>
    where
        R: CMutRef<'static, Type = T> + 'static,
        T: ProtocolInterface + 'static,
    {
        let interface_ptr = match mem::size_of::<T>() {
            0 => ptr::null_mut(),
            _ => key.ptr_value as *mut c_void,
        };

        // SAFETY: This is safe because ProtocolInterface provide the right guid for the interface.
        unsafe { self.uninstall_protocol_interface_unchecked(handle, &T::PROTOCOL_GUID, interface_ptr) }?;

        // SAFETY: Pointer is leak when installed and kept unchanged.
        unsafe { key.try_into_original_ptr() }.ok_or(efi::Status::INVALID_PARAMETER)
    }

    /// Use [`BootServices::uninstall_protocol_interface`] when possible.
    ///
    /// # Safety
    ///
    /// interface must be a valid pointer and be of the type expected by to protocol.
    unsafe fn uninstall_protocol_interface_unchecked(
        &self,
        handle: efi::Handle,
        protocol: &'static efi::Guid,
        interface: *mut c_void,
    ) -> Result<(), efi::Status>;

    /// Reinstalls a protocol interface on a device handle.
    ///
    /// [UEFI Spec Documentation: 7.3.4. EFI_BOOT_SERVICES.ReinstallProtocolInterface()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-reinstallprotocolinterface)
    #[allow(clippy::not_unsafe_ptr_arg_deref)] //this is triggered by the fact that efi::Handle aliases to c_void, but they are opaque to the caller.
    fn reinstall_protocol_interface<T, K, R>(
        &self,
        handle: efi::Handle,
        old_protocol_interface_key: PtrMetadata<'static, K>,
        new_protocol_interface: R,
    ) -> Result<(PtrMetadata<'static, R>, K), efi::Status>
    where
        K: CMutRef<'static, Type = T> + 'static,
        R: CMutRef<'static, Type = T> + 'static,
        T: ProtocolInterface + 'static,
    {
        let new_key = new_protocol_interface.metadata();

        let mut old_protocol_interface_ptr = old_protocol_interface_key.ptr_value as *mut c_void;
        let mut new_protocol_interface_ptr = new_protocol_interface.into_mut_ptr() as *mut c_void;

        if mem::size_of::<T>() == 0 {
            old_protocol_interface_ptr = ptr::null_mut();
            new_protocol_interface_ptr = ptr::null_mut();
        };

        // SAFETY: This is safe because ProtocolInterface provide the right guid for the interface.
        unsafe {
            self.reinstall_protocol_interface_unchecked(
                handle,
                &T::PROTOCOL_GUID,
                old_protocol_interface_ptr,
                new_protocol_interface_ptr,
            )?;
        }
        // SAFETY: Pointer is leak when installed and kept unchanged.
        let old_interface =
            unsafe { old_protocol_interface_key.try_into_original_ptr() }.ok_or(efi::Status::INVALID_PARAMETER)?;
        Ok((new_key, old_interface))
    }

    /// Use [`BootServices::reinstall_protocol_interface`] when possible.
    ///
    /// # Safety
    /// When calling this method, you have to make sure that if *new_protocol_interface* pointer is non-null, it is adhereing to
    /// the structure associated with the protocol.
    unsafe fn reinstall_protocol_interface_unchecked(
        &self,
        handle: efi::Handle,
        protocol: &'static efi::Guid,
        old_protocol_interface: *mut c_void,
        new_protocol_interface: *mut c_void,
    ) -> Result<(), efi::Status>;

    /// Creates an event that is to be signaled whenever an interface is installed for a specified protocol.
    ///
    /// [UEFI Spec Documentation: 7.3.5. EFI_BOOT_SERVICES.RegisterProtocolNotify()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-registerprotocolnotify)
    fn register_protocol_notify(
        &self,
        protocol: &'static efi::Guid,
        event: efi::Event,
    ) -> Result<Registration, efi::Status>;

    /// Returns an array of handles that support a specified protocol.
    ///
    /// [UEFI Spec Documentation: 7.3.6. EFI_BOOT_SERVICES.LocateHandle()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-locatehandle)
    fn locate_handle<'a>(
        &'a self,
        search_type: HandleSearchType,
    ) -> Result<BootServicesBox<'a, [efi::Handle], Self>, efi::Status>;

    /// Queries a handle to determine if it supports a specified protocol and return a mutable reference to the interface.
    ///
    /// [UEFI Spec Documentation: 7.3.7. EFI_BOOT_SERVICES.HandleProtocol()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-handleprotocol)
    ///
    /// # Safety
    /// Make sure to not create multiple mutable reference of interface.
    unsafe fn handle_protocol<T>(&self, handle: efi::Handle) -> Result<&'static mut T, efi::Status>
    where
        T: Sized + ProtocolInterface + 'static,
    {
        // SAFETY: Caller guarantees handle is valid. handle_protocol_maybe_empty performs the FFI call
        // and returns a properly typed pointer or None based on the protocol interface.
        match unsafe { self.handle_protocol_maybe_empty(handle)? } {
            Some(_) if mem::size_of::<T>() == 0 => {
                debug_assert!(false, "Expect null interface. Type {} need to have a size of 0.", any::type_name::<T>());
                Err(efi::Status::INVALID_PARAMETER)
            }
            None if mem::size_of::<T>() > 0 => {
                debug_assert!(
                    false,
                    "Expect non null interface. Type {} need to have a size greater than 0.",
                    any::type_name::<T>()
                );
                Err(efi::Status::INVALID_PARAMETER)
            }
            Some(i) => Ok(i),
            None => {
                // SAFETY: T is a ZST (size == 0). NonNull::dangling() returns a well-aligned,
                // non-null pointer. For ZSTs, reads/writes are zero-sized accesses. Each call
                // produces its own reference, avoiding aliasing violations.
                Ok(unsafe { NonNull::<T>::dangling().as_mut() })
            }
        }
    }

    /// Queries a handle to determine if it supports a specified protocol and return a mutable reference to the interface or None if the interface was null.
    ///
    /// [UEFI Spec Documentation: 7.3.7. EFI_BOOT_SERVICES.HandleProtocol()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-handleprotocol)
    ///
    /// # Safety
    /// Make sure to not create multiple mutable reference of interface.
    unsafe fn handle_protocol_maybe_empty<T>(&self, handle: efi::Handle) -> Result<Option<&'static mut T>, efi::Status>
    where
        T: Sized + ProtocolInterface + 'static,
    {
        // SAFETY: handle_protocol_unchecked returns a raw pointer. Converting to *mut T is considered
        // safe based on T::PROTOCOL_GUID ensuring type correctness. as_mut() may return None if the
        // firmware returns null for zero-sized protocols.
        Ok(unsafe { (self.handle_protocol_unchecked(handle, &T::PROTOCOL_GUID)? as *mut T).as_mut() })
    }

    /// Use [`BootServices::handle_protocol`] when possible.
    ///
    /// # Safety
    ///
    /// caller must handle conversion of the output c_void to proper type appropriately.
    unsafe fn handle_protocol_unchecked(
        &self,
        handle: efi::Handle,
        protocol: &efi::Guid,
    ) -> Result<*mut c_void, efi::Status>;

    /// Locates the handle to a device on the device path that supports the specified protocol.
    ///
    /// [UEFI Spec Documentation: 7.3.8. EFI_BOOT_SERVICES.LocateDevicePath()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-locatedevicepath)
    ///
    /// # Safety
    ///
    /// device path mut be valid pointers.
    unsafe fn locate_device_path(
        &self,
        protocol: &efi::Guid,
        device_path: *mut *mut efi::protocols::device_path::Protocol,
    ) -> Result<efi::Handle, efi::Status>;

    /// Queries a handle to determine if it supports a specified protocol.
    /// If the protocol is supported by the handle, it opens the protocol on behalf of the calling agent.
    ///
    /// [UEFI Spec Documentation: 7.3.9. EFI_BOOT_SERVICES.OpenProtocol()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-openprotocol)
    ///
    /// # Safety
    ///
    /// Do not create more than one mutable reference to the interface.
    unsafe fn open_protocol<T>(
        &self,
        handle: efi::Handle,
        agent_handle: efi::Handle,
        controller_handle: efi::Handle,
        attribute: u32,
    ) -> Result<&'static mut T, efi::Status>
    where
        T: Sized + ProtocolInterface + 'static,
    {
        // SAFETY: Caller guarantees handle is valid. open_protocol_maybe_empty performs the FFI call
        // and returns a properly typed pointer or None based on the protocol interface.
        match unsafe { self.open_protocol_maybe_empty::<T>(handle, agent_handle, controller_handle, attribute)? } {
            Some(_) if mem::size_of::<T>() == 0 => {
                debug_assert!(false, "Expect null interface. Type {} need to have a size of 0.", any::type_name::<T>());
                Err(efi::Status::INVALID_PARAMETER)
            }
            None if mem::size_of::<T>() > 0 => {
                debug_assert!(
                    false,
                    "Expect non null interface. Type {} need to have a size greater than 0.",
                    any::type_name::<T>()
                );
                Err(efi::Status::INVALID_PARAMETER)
            }
            Some(i) => Ok(i),
            None => {
                // SAFETY: T is a ZST (size == 0). NonNull::dangling() returns a well-aligned,
                // non-null pointer. For ZSTs, reads/writes are zero-sized accesses. Each call
                // produces its own reference, avoiding aliasing violations.
                Ok(unsafe { NonNull::<T>::dangling().as_mut() })
            }
        }
    }

    /// Queries a handle to determine if it supports a specified protocol.
    /// If the protocol is supported by the handle, it opens the protocol on behalf of the calling agent.
    /// Return a mutable reference to the interface or None if the interface was null.
    ///
    /// [UEFI Spec Documentation: 7.3.9. EFI_BOOT_SERVICES.OpenProtocol()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-openprotocol)
    ///
    /// # Safety
    ///
    /// Do not create more than one mutable reference to the interface.
    unsafe fn open_protocol_maybe_empty<T>(
        &self,
        handle: efi::Handle,
        agent_handle: efi::Handle,
        controller_handle: efi::Handle,
        attribute: u32,
    ) -> Result<Option<&'static mut T>, efi::Status>
    where
        T: Sized + ProtocolInterface + 'static,
    {
        // SAFETY: open_protocol_unchecked returns a raw pointer. Converting to *mut T is considered
        // safe based on T::PROTOCOL_GUID ensuring type correctness. as_mut() may return None if the
        // firmware returns null for zero-sized protocols.
        Ok(unsafe {
            (self.open_protocol_unchecked(handle, &T::PROTOCOL_GUID, agent_handle, controller_handle, attribute)?
                as *mut T)
                .as_mut()
        })
    }

    /// Use [`BootServices::open_protocol`] when possible.
    ///
    /// # Safety
    ///
    /// When calling this method, you have to make sure that if *agent_handle* pointer is non-null.
    unsafe fn open_protocol_unchecked(
        &self,
        handle: efi::Handle,
        protocol: &efi::Guid,
        agent_handle: efi::Handle,
        controller_handle: efi::Handle,
        attribute: u32,
    ) -> Result<*mut c_void, efi::Status>;

    /// Closes a protocol on a handle that was previously opened.
    ///
    /// [UEFI Spec Documentation: 7.3.10. EFI_BOOT_SERVICES.CloseProtocol()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-closeprotocol)
    fn close_protocol(
        &self,
        handle: efi::Handle,
        protocol: &efi::Guid,
        agent_handle: efi::Handle,
        controller_handle: efi::Handle,
    ) -> Result<(), efi::Status>;

    /// Retrieves the list of agents that currently have a protocol interface opened.
    ///
    /// [UEFI Spec Documentation: 7.3.11. EFI_BOOT_SERVICES.OpenProtocolInformation()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-openprotocolinformation)
    fn open_protocol_information<'a>(
        &'a self,
        handle: efi::Handle,
        protocol: &efi::Guid,
    ) -> Result<BootServicesBox<'a, [efi::OpenProtocolInformationEntry], Self>, efi::Status>;

    /// Connects one or more drivers to a controller.
    ///
    /// # Safety
    ///
    /// When calling this method, you have to make sure that *driver_image_handle*'s last entry is null per UEFI specification.
    ///
    /// [UEFI Spec Documentation: 7.3.12. EFI_BOOT_SERVICES.ConnectController()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-connectcontroller)
    unsafe fn connect_controller(
        &self,
        controller_handle: efi::Handle,
        driver_image_handles: Vec<efi::Handle>,
        remaining_device_path: *mut efi::protocols::device_path::Protocol,
        recursive: bool,
    ) -> Result<(), efi::Status>;

    /// Disconnects one or more drivers from a controller.
    ///
    /// [UEFI Spec Documentation: 7.3.13. EFI_BOOT_SERVICES.DisconnectController()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-disconnectcontroller)
    fn disconnect_controller(
        &self,
        controller_handle: efi::Handle,
        driver_image_handle: Option<efi::Handle>,
        child_handle: Option<efi::Handle>,
    ) -> Result<(), efi::Status>;

    /// Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated from pool.
    ///
    /// [UEFI Spec Documentation: 7.3.14. EFI_BOOT_SERVICES.ProtocolsPerHandle()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-protocolsperhandle)
    fn protocols_per_handle<'a>(
        &'a self,
        handle: efi::Handle,
    ) -> Result<BootServicesBox<'a, [&'static efi::Guid], Self>, efi::Status>;

    /// Returns an array of handles that support the requested protocol in a buffer allocated from pool.
    ///
    /// [UEFI Spec Documentation: 7.3.15. EFI_BOOT_SERVICES.LocateHandleBuffer()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-locatehandlebuffer)
    fn locate_handle_buffer<'a>(
        &'a self,
        search_type: HandleSearchType,
    ) -> Result<BootServicesBox<'a, [efi::Handle], Self>, efi::Status>;

    /// Returns the first protocol instance that matches the given protocol.
    ///
    /// [UEFI Spec Documentation: 7.3.16. EFI_BOOT_SERVICES.LocateProtocol()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-locateprotocol)
    ///
    /// # Safety
    ///
    /// Make sure to not create multiple mutable reference when using this api.
    unsafe fn locate_protocol<T>(&self, registration: Option<Registration>) -> Result<&'static mut T, efi::Status>
    where
        T: Sized + ProtocolInterface + 'static,
    {
        // SAFETY: Caller guarantees no aliasing. locate_protocol_maybe_empty performs the FFI call
        // and returns a properly typed pointer or None based on the protocol interface.
        match unsafe { self.locate_protocol_maybe_empty(registration)? } {
            Some(_) if mem::size_of::<T>() == 0 => {
                debug_assert!(false, "Expect null interface. Type {} need to have a size of 0.", any::type_name::<T>());
                Err(efi::Status::INVALID_PARAMETER)
            }
            None if mem::size_of::<T>() > 0 => {
                debug_assert!(
                    false,
                    "Expect non null interface. Type {} need to have a size greater than 0.",
                    any::type_name::<T>()
                );
                Err(efi::Status::INVALID_PARAMETER)
            }
            Some(i) => Ok(i),
            None => {
                // SAFETY: T is a ZST (size == 0). NonNull::dangling() returns a well-aligned,
                // non-null pointer. For ZSTs, reads/writes are zero-sized accesses. Each call
                // produces its own reference, avoiding aliasing violations.
                Ok(unsafe { NonNull::<T>::dangling().as_mut() })
            }
        }
    }

    /// Returns the first protocol instance that matches the given protocol or None if the found interface is null.
    ///
    /// [UEFI Spec Documentation: 7.3.16. EFI_BOOT_SERVICES.LocateProtocol()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-locateprotocol)
    ///
    /// # Safety
    ///
    /// Make sure to not create multiple mutable reference when using this api.
    unsafe fn locate_protocol_maybe_empty<T>(
        &self,
        registration: Option<Registration>,
    ) -> Result<Option<&'static mut T>, efi::Status>
    where
        T: Sized + ProtocolInterface + 'static,
    {
        //SAFETY: The generic ProtocolInterface ensure that the interfaces is the right type for the specified protocol.
        Ok(unsafe {
            (self.locate_protocol_unchecked(&T::PROTOCOL_GUID, registration.map_or(ptr::null_mut(), NonNull::as_ptr))?
                as *mut T)
                .as_mut()
        })
    }

    /// Returns the first protocol instance that matches the given marker protocol.
    ///
    /// [UEFI Spec Documentation: 7.3.16. EFI_BOOT_SERVICES.LocateProtocol()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-locateprotocol)
    fn locate_protocol_marker(
        &self,
        protocol_guid: &'static efi::Guid,
        registration: Option<Registration>,
    ) -> Result<(), efi::Status> {
        //SAFETY: The generic Protocol ensure that the interfaces is the right type for the specified protocol.
        let interface_ptr = unsafe {
            self.locate_protocol_unchecked(protocol_guid, registration.map_or(ptr::null_mut(), |r| r.as_ptr()))?
        };
        if !interface_ptr.is_null() {
            log_debug_assert!("Marker protocol has no data; interface should be null {:?}", protocol_guid);
            Err(efi::Status::INVALID_PARAMETER)
        } else {
            Ok(())
        }
    }

    /// Use [`BootServices::locate_protocol`] when possible.
    ///
    /// # Safety
    ///
    /// Make sure to deref the pointer with the expected Interface and not create multiple mutable references.
    ///
    unsafe fn locate_protocol_unchecked(
        &self,
        protocol: &'static efi::Guid,
        registration: *mut c_void,
    ) -> Result<*mut c_void, efi::Status>;

    /// Load an EFI image from a memory buffer.
    ///
    /// This uses [`Self::load_image`] behind the scene. This function assume that the request is not originating from the boot manager.
    ///
    fn load_image_from_source(
        &self,
        parent_image_handle: efi::Handle,
        device_path: *mut efi::protocols::device_path::Protocol,
        source_buffer: &[u8],
    ) -> Result<efi::Handle, efi::Status> {
        self.load_image(false, parent_image_handle, device_path, Some(source_buffer))
    }

    /// Load an EFI image from a file.
    ///
    /// This uses [`Self::load_image`] behind the scene. This function assume that the request is not originating from the boot manager.
    ///
    fn load_image_from_file(
        &self,
        parent_image_handle: efi::Handle,
        file_device_path: NonNull<efi::protocols::device_path::Protocol>,
    ) -> Result<efi::Handle, efi::Status> {
        self.load_image(false, parent_image_handle, file_device_path.as_ptr(), None)
    }

    /// Loads an EFI image into memory.
    ///
    /// [UEFI Spec Documentation: 7.4.1. EFI_BOOT_SERVICES.LoadImage()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-loadimage)
    ///
    fn load_image<'a>(
        &self,
        boot_policy: bool,
        parent_image_handle: efi::Handle,
        device_path: *mut efi::protocols::device_path::Protocol,
        source_buffer: Option<&'a [u8]>,
    ) -> Result<efi::Handle, efi::Status>;

    /// Transfers control to a loaded image’s entry point.
    ///
    ///
    ///  [UEFI Spec Documentation: 7.4.2. EFI_BOOT_SERVICES.StartImage()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-startimage)
    ///
    #[allow(clippy::type_complexity)]
    fn start_image<'a>(
        &'a self,
        image_handle: efi::Handle,
    ) -> Result<(), (efi::Status, Option<BootServicesBox<'a, [u8], Self>>)>;

    /// Unloads an image.
    ///
    /// [UEFI Spec Documentation: 7.4.3. EFI_BOOT_SERVICES.UnloadImage()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-unloadimage)
    ///
    fn unload_image(&self, image_handle: efi::Handle) -> Result<(), efi::Status>;

    /// Terminates a loaded EFI image and returns control to boot services.
    ///
    /// [UEFI Spec Documentation: 7.4.5. EFI_BOOT_SERVICES.Exit()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-exit)
    ///
    fn exit<'a>(
        &'a self,
        image_handle: efi::Handle,
        exit_status: efi::Status,
        exit_data: Option<BootServicesBox<'a, [u8], Self>>,
    ) -> Result<(), efi::Status>;

    /// Terminates all boot services.
    ///
    /// [UEFI Spec Documentation: EFI_BOOT_SERVICES.ExitBootServices()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-exitbootservices)
    ///
    fn exit_boot_services(&self, image_handle: efi::Handle, map_key: usize) -> Result<(), efi::Status>;

    /// Sets the system’s watchdog timer.
    ///
    /// Note:
    /// We deliberately choose to ignore the watchdog code and data parameters because we are not using them.
    /// Feel free to add those if needed.
    ///
    /// [UEFI Spec Documentation: 7.5.1. EFI_BOOT_SERVICES.SetWatchdogTimer()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-setwatchdogtimer)
    fn set_watchdog_timer(&self, timeout: usize) -> Result<(), efi::Status>;

    /// Induces a fine-grained stall
    ///
    /// [UEFI Spec Documentation: 7.5.2. EFI_BOOT_SERVICES.Stall()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-stall)
    fn stall(&self, microseconds: usize) -> Result<(), efi::Status>;

    /// Copies the contents of one buffer to another buffer.
    ///
    /// [UEFI Spec Documentation: 7.5.3. EFI_BOOT_SERVICES.CopyMem()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-copymem)
    fn copy_mem<T: 'static>(&self, dest: &mut T, src: &T) {
        // SAFETY: This is safe because refs are valid pointers and the size is trusted from mem size of.
        unsafe { self.copy_mem_unchecked(dest as *mut T as _, src as *const T as _, mem::size_of::<T>()) }
    }

    /// Use of [`Self::copy_mem`] is preferable if the context allows it.
    ///
    /// # Safety
    ///
    /// Dest and src must be valid pointer to a continuous chunk of memory of size length.
    unsafe fn copy_mem_unchecked(&self, dest: *mut c_void, src: *const c_void, length: usize);

    /// Fills a buffer with a specified value.
    ///
    /// [UEFI Spec Documentation: 7.5.4. EFI_BOOT_SERVICES.SetMem()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-setmem)
    fn set_mem(&self, buffer: &mut [u8], value: u8);

    /// Returns a monotonically increasing count for the platform.
    ///
    /// [UEFI Spec Documentation: 7.5.5. EFI_BOOT_SERVICES.GetNextMonotonicCount()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-getnextmonotoniccount)
    fn get_next_monotonic_count(&self) -> Result<u64, efi::Status>;

    /// Adds, updates, or removes a configuration table entry from the EFI System Table.
    ///
    /// [UEFI Spec Documentation: 7.5.6. EFI_BOOT_SERVICES.InstallConfigurationTable()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-installconfigurationtable)
    ///
    /// # Safety
    ///
    /// The configuration table value must match the expected type for the guid.
    unsafe fn install_configuration_table<T: CMutPtr<'static> + 'static>(
        &self,
        guid: &efi::Guid,
        table: T,
    ) -> Result<(), efi::Status> {
        // SAFETY: Caller guarantees table type matches guid. into_mut_ptr() provides a valid pointer
        // that remains valid for the lifetime of boot services as constrained by the trait bound.
        unsafe { self.install_configuration_table_unchecked(guid, table.into_mut_ptr() as *mut c_void) }
    }

    /// Use [`BootServices::install_configuration_table`] when possible.
    ///
    /// # Safety
    ///
    /// The table pointer must be the right type associated with the guid, and boot services must not outlive the ptr.
    unsafe fn install_configuration_table_unchecked(
        &self,
        guid: &efi::Guid,
        table: *mut c_void,
    ) -> Result<(), efi::Status>;

    /// Computes and returns a 32-bit CRC for a data buffer.
    ///
    /// [UEFI Spec Documentation: 7.5.7. EFI_BOOT_SERVICES.CalculateCrc32()](https://uefi.org/specs/UEFI/2.10/07_Services_Boot_Services.html#efi-boot-services-calculatecrc32)
    fn calculate_crc_32<T: 'static>(&self, data: &T) -> Result<u32, efi::Status> {
        // SAFETY: The reference guarantees that the pointer is valid and properly aligned.
        // size_of::<T>() provides the exact size of the data being pointed to.
        unsafe { self.calculate_crc_32_unchecked(data as *const T as _, mem::size_of::<T>()) }
    }

    /// Use [`BootServices::calculate_crc_32`] when possible.
    ///
    /// # Safety
    ///
    /// data pointer and size must be correct.
    unsafe fn calculate_crc_32_unchecked(&self, data: *const c_void, data_size: usize) -> Result<u32, efi::Status>;
}

/// Clone implementation for MockBootServices that creates a new mock with default expectations.
/// TplMutex owns its BootServices instance, so this Clone impl is needed when passing mocks.
/// Sets up default expectations for raise_tpl and restore_tpl which are commonly used by TplMutex.
#[cfg(any(test, feature = "mockall"))]
impl Clone for MockBootServices {
    fn clone(&self) -> Self {
        let mut mock = Self::new();
        // Set up default expectations for TPL methods used by TplMutex
        mock.expect_raise_tpl().returning(|_| tpl::Tpl::APPLICATION);
        mock.expect_restore_tpl().returning(|_| ());
        mock
    }
}

macro_rules! efi_boot_services_fn {
    ($efi_boot_services:expr, $fn_name:ident) => {{
        match $efi_boot_services.$fn_name {
            f if f as usize == 0 => panic!("Boot services function {} is not initialized.", stringify!($fn_name)),
            f => f,
        }
    }};
}

impl BootServices for StandardBootServices {
    unsafe fn create_event_unchecked<T: Sized + 'static>(
        &self,
        event_type: EventType,
        notify_tpl: Tpl,
        notify_function: Option<EventNotifyCallback<*mut T>>,
        notify_context: *mut T,
    ) -> Result<efi::Event, efi::Status> {
        let mut event = MaybeUninit::zeroed();
        // SAFETY: If this function pointer is modified in an event callback/interrupt while the read is in progress
        // or if this function is invoked in a callback/interrupt that interrupts an external agent that is modifying
        // the boot services struct, then an incorrect function pointer might be returned that is composed of parts
        // of the pointer from before and after the interrupt. Function pointer read/write operations could consist of
        // several instructions - not necessarily a single atomic operation. The safety of this code therefore relies on
        // the assumption that the boot services struct is not being modified in such a manner, which is true for all
        // known external modifiers of the struct in EDK2. If this code requires stronger guarantees in the future, then
        // synchronization with external modifications may be needed, or the table could be copied to local storage and
        // verified (via CRC) before use with an error returned on mismatch. Present use cases for external modification
        // of boot services don't merit such complexity at this time.
        let create_event = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), create_event) };
        let status = create_event(
            event_type.into(),
            notify_tpl.into(),
            // Safety: Transmuting function pointer types with matching ABIs and compatible signatures.
            // Both are extern "efiapi" callbacks taking a context pointer - the generic parameter T
            // is erased to c_void for the UEFI FFI interface.
            unsafe {
                mem::transmute::<
                    Option<extern "efiapi" fn(*mut c_void, *mut T)>,
                    Option<extern "efiapi" fn(*mut c_void, *mut c_void)>,
                >(notify_function)
            },
            notify_context as *mut c_void,
            event.as_mut_ptr(),
        );
        // SAFETY: If the UEFI call succeeded, event has been initialized by the firmware.
        if status.is_error() { Err(status) } else { Ok(unsafe { event.assume_init() }) }
    }

    unsafe fn create_event_ex_unchecked<T: Sized + 'static>(
        &self,
        event_type: EventType,
        notify_tpl: Tpl,
        notify_function: Option<EventNotifyCallback<*mut T>>,
        notify_context: *mut T,
        event_group: &'static efi::Guid,
    ) -> Result<efi::Event, efi::Status> {
        let mut event = MaybeUninit::zeroed();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let create_event_ex = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), create_event_ex) };
        let status = create_event_ex(
            event_type.into(),
            notify_tpl.into(),
            // Safety: Transmuting function pointer types with matching ABIs and compatible signatures.
            // Both are extern "efiapi" callbacks - the generic parameter T is erased to c_void for FFI.
            unsafe {
                mem::transmute::<
                    Option<extern "efiapi" fn(*mut c_void, *mut T)>,
                    Option<extern "efiapi" fn(*mut c_void, *mut c_void)>,
                >(notify_function)
            },
            notify_context as *mut c_void,
            event_group as *const _,
            event.as_mut_ptr(),
        );
        // SAFETY: If the call succeeded, it is considered initialized.
        if status.is_error() { Err(status) } else { Ok(unsafe { event.assume_init() }) }
    }

    fn close_event(&self, event: efi::Event) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let close_event = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), close_event) };
        match close_event(event) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn signal_event(&self, event: efi::Event) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let signal_event = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), signal_event) };
        match signal_event(event) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn wait_for_event(&self, events: &mut [efi::Event]) -> Result<usize, efi::Status> {
        let mut index = MaybeUninit::zeroed();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let wait_for_event = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), wait_for_event) };
        let status = wait_for_event(events.len(), events.as_mut_ptr(), index.as_mut_ptr());
        // SAFETY: If the call succeeded, index has been initialized with the event index.
        if status.is_error() { Err(status) } else { Ok(unsafe { index.assume_init() }) }
    }

    fn check_event(&self, event: efi::Event) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let check_event = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), check_event) };
        match check_event(event) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn set_timer(&self, event: efi::Event, timer_type: EventTimerType, trigger_time: u64) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let set_timer = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), set_timer) };
        match set_timer(event, timer_type.into(), trigger_time) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn raise_tpl(&self, new_tpl: Tpl) -> Tpl {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let raise_tpl = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), raise_tpl) };
        raise_tpl(new_tpl.into()).into()
    }

    fn restore_tpl(&self, old_tpl: Tpl) {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let restore_tpl = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), restore_tpl) };
        restore_tpl(old_tpl.into())
    }

    fn allocate_pages(
        &self,
        alloc_type: AllocType,
        memory_type: EfiMemoryType,
        nb_pages: usize,
    ) -> Result<usize, efi::Status> {
        let mut memory_address = match alloc_type {
            AllocType::Address(address) => address,
            AllocType::MaxAddress(address) => address,
            _ => 0,
        };
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let allocate_pages = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), allocate_pages) };
        match allocate_pages(
            alloc_type.into(),
            memory_type.into(),
            nb_pages,
            ptr::addr_of_mut!(memory_address) as *mut u64,
        ) {
            s if s.is_error() => Err(s),
            _ => Ok(memory_address),
        }
    }

    fn free_pages(&self, address: usize, nb_pages: usize) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let free_pages = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), free_pages) };
        match free_pages(address as u64, nb_pages) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn get_memory_map(&self) -> Result<MemoryMap<'_, Self>, (efi::Status, usize)> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let get_memory_map = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), get_memory_map) };

        let mut memory_map_size = 0;
        let mut map_key = 0;
        let mut descriptor_size = 0;
        let mut descriptor_version = 0;

        match get_memory_map(
            ptr::addr_of_mut!(memory_map_size),
            ptr::null_mut(),
            ptr::addr_of_mut!(map_key),
            ptr::addr_of_mut!(descriptor_size),
            ptr::addr_of_mut!(descriptor_version),
        ) {
            s if s == efi::Status::BUFFER_TOO_SMALL => memory_map_size += 0x400, // add more space in case allocation makes the memory map bigger.
            _ => (),
        };

        let buffer = self.allocate_pool(EfiMemoryType::BootServicesData, memory_map_size).map_err(|s| (s, 0))?;

        match get_memory_map(
            ptr::addr_of_mut!(memory_map_size),
            buffer as *mut _,
            ptr::addr_of_mut!(map_key),
            ptr::addr_of_mut!(descriptor_size),
            ptr::addr_of_mut!(descriptor_version),
        ) {
            s if s == efi::Status::BUFFER_TOO_SMALL => return Err((s, memory_map_size)),
            s if s.is_error() => return Err((s, 0)),
            _ => (),
        }
        Ok(MemoryMap {
            // SAFETY: buffer was allocated with allocate_pool and size is descriptor_size.
            // The buffer is properly sized and aligned for the memory map descriptors.
            descriptors: unsafe { BootServicesBox::from_raw_parts_mut(buffer as *mut _, descriptor_size, self) },
            map_key,
            descriptor_version,
        })
    }

    fn allocate_pool(&self, memory_type: EfiMemoryType, size: usize) -> Result<*mut u8, efi::Status> {
        let mut buffer = ptr::null_mut();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let allocate_pool = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), allocate_pool) };
        match allocate_pool(memory_type.into(), size, ptr::addr_of_mut!(buffer)) {
            s if s.is_error() => Err(s),
            _ => Ok(buffer as *mut u8),
        }
    }

    fn free_pool(&self, buffer: *mut u8) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let free_pool = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), free_pool) };
        match free_pool(buffer as *mut c_void) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    unsafe fn install_protocol_interface_unchecked(
        &self,
        handle: Option<efi::Handle>,
        protocol: &'static efi::Guid,
        interface: *mut c_void,
    ) -> Result<efi::Handle, efi::Status> {
        let mut handle = handle.unwrap_or_default();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let install_protocol_interface =
            unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), install_protocol_interface) };
        match install_protocol_interface(
            ptr::addr_of_mut!(handle),
            protocol as *const _ as *mut _,
            efi::NATIVE_INTERFACE,
            interface,
        ) {
            s if s.is_error() => Err(s),
            _ => Ok(handle),
        }
    }

    unsafe fn uninstall_protocol_interface_unchecked(
        &self,
        handle: efi::Handle,
        protocol: &'static efi::Guid,
        interface: *mut c_void,
    ) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let uninstall_protocol_interface =
            unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), uninstall_protocol_interface) };
        match uninstall_protocol_interface(handle, protocol as *const _ as *mut _, interface) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    unsafe fn reinstall_protocol_interface_unchecked(
        &self,
        handle: efi::Handle,
        protocol: &'static efi::Guid,
        old_protocol_interface: *mut c_void,
        new_protocol_interface: *mut c_void,
    ) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let reinstall_protocol_interface =
            unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), reinstall_protocol_interface) };
        match reinstall_protocol_interface(
            handle,
            protocol as *const _ as *mut _,
            old_protocol_interface,
            new_protocol_interface,
        ) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn register_protocol_notify(&self, protocol: &efi::Guid, event: efi::Event) -> Result<Registration, efi::Status> {
        let mut registration = MaybeUninit::uninit();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let register_protocol_notify = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), register_protocol_notify) };
        match register_protocol_notify(protocol as *const _ as *mut _, event, registration.as_mut_ptr() as *mut _) {
            s if s.is_error() => Err(s),
            // SAFETY: If the call succeeded, registration has been initialized.
            _ => Ok(unsafe { registration.assume_init() }),
        }
    }

    fn locate_handle(
        &self,
        search_type: HandleSearchType,
    ) -> Result<BootServicesBox<'_, [efi::Handle], Self>, efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let locate_handle = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), locate_handle) };

        let protocol = match search_type {
            HandleSearchType::ByProtocol(p) => p as *const _ as *mut _,
            _ => ptr::null_mut(),
        };
        let search_key = match search_type {
            HandleSearchType::ByRegisterNotify(r) => r.as_ptr(),
            _ => ptr::null_mut(),
        };

        // Expect locate_handle to return BUFFER_TOO_SMALL along with the proper buffer_size
        let mut buffer_size = 0;
        match locate_handle(search_type.into(), protocol, search_key, ptr::addr_of_mut!(buffer_size), ptr::null_mut()) {
            s if s == efi::Status::BUFFER_TOO_SMALL => (),
            s if s.is_error() => return Err(s),
            _ => (),
        }

        let buffer = self.allocate_pool(EfiMemoryType::BootServicesData, buffer_size)?;

        match locate_handle(
            search_type.into(),
            protocol,
            search_key,
            ptr::addr_of_mut!(buffer_size),
            buffer as *mut efi::Handle,
        ) {
            s if s.is_error() => Err(s),
            // SAFETY: buffer was allocated with allocate_pool to hold buffer_size bytes.
            // The number of handles is buffer_size divided by the size of each handle.
            _ => Ok(unsafe {
                BootServicesBox::from_raw_parts_mut(buffer as *mut _, buffer_size / mem::size_of::<efi::Handle>(), self)
            }),
        }
    }

    unsafe fn handle_protocol_unchecked(
        &self,
        handle: efi::Handle,
        protocol: &efi::Guid,
    ) -> Result<*mut c_void, efi::Status> {
        let mut interface = ptr::null_mut();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let handle_protocol = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), handle_protocol) };
        match handle_protocol(handle, protocol as *const _ as *mut _, ptr::addr_of_mut!(interface)) {
            s if s.is_error() => Err(s),
            _ => Ok(interface),
        }
    }

    unsafe fn locate_device_path(
        &self,
        protocol: &efi::Guid,
        device_path: *mut *mut efi::protocols::device_path::Protocol,
    ) -> Result<efi::Handle, efi::Status> {
        let mut device = ptr::null_mut();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let locate_device_path = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), locate_device_path) };
        match locate_device_path(protocol as *const _ as *mut _, device_path, ptr::addr_of_mut!(device)) {
            s if s.is_error() => Err(s),
            _ => Ok(device),
        }
    }

    unsafe fn open_protocol_unchecked(
        &self,
        handle: efi::Handle,
        protocol: &efi::Guid,
        agent_handle: efi::Handle,
        controller_handle: efi::Handle,
        attribute: u32,
    ) -> Result<*mut c_void, efi::Status> {
        let mut interface = ptr::null_mut();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let open_protocol = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), open_protocol) };
        match open_protocol(
            handle,
            protocol as *const _ as *mut _,
            ptr::addr_of_mut!(interface),
            agent_handle,
            controller_handle,
            attribute,
        ) {
            s if s.is_error() => Err(s),
            _ => Ok(interface),
        }
    }

    fn close_protocol(
        &self,
        handle: efi::Handle,
        protocol: &efi::Guid,
        agent_handle: efi::Handle,
        controller_handle: efi::Handle,
    ) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let close_protocol = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), close_protocol) };
        match close_protocol(handle, protocol as *const _ as *mut _, agent_handle, controller_handle) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn open_protocol_information(
        &self,
        handle: efi::Handle,
        protocol: &efi::Guid,
    ) -> Result<BootServicesBox<'_, [efi::OpenProtocolInformationEntry], Self>, efi::Status>
    where
        Self: Sized,
    {
        let mut entry_buffer = ptr::null_mut();
        let mut entry_count = 0;
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let open_protocol_information = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), open_protocol_information) };
        match open_protocol_information(
            handle,
            protocol as *const _ as *mut _,
            ptr::addr_of_mut!(entry_buffer),
            ptr::addr_of_mut!(entry_count),
        ) {
            s if s.is_error() => Err(s),
            // SAFETY: The firmware allocates entry_buffer and sets entry_count.
            // from_raw_parts_mut creates a slice with the proper length as specified by the firmware.
            _ => Ok(unsafe { BootServicesBox::from_raw_parts_mut(entry_buffer, entry_count, self) }),
        }
    }

    unsafe fn connect_controller(
        &self,
        controller_handle: efi::Handle,
        mut driver_image_handles: Vec<efi::Handle>,
        remaining_device_path: *mut efi::protocols::device_path::Protocol,
        recursive: bool,
    ) -> Result<(), efi::Status> {
        let driver_image_handles = if driver_image_handles.is_empty() {
            ptr::null_mut()
        } else {
            driver_image_handles.push(ptr::null_mut());
            driver_image_handles.as_mut_ptr()
        };
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let connect_controller = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), connect_controller) };
        match connect_controller(controller_handle, driver_image_handles, remaining_device_path, recursive.into()) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn disconnect_controller(
        &self,
        controller_handle: efi::Handle,
        driver_image_handle: Option<efi::Handle>,
        child_handle: Option<efi::Handle>,
    ) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let disconnect_controller = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), disconnect_controller) };
        match disconnect_controller(
            controller_handle,
            driver_image_handle.unwrap_or_default(),
            child_handle.unwrap_or_default(),
        ) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn protocols_per_handle(
        &self,
        handle: efi::Handle,
    ) -> Result<BootServicesBox<'_, [&'static efi::Guid], Self>, efi::Status> {
        let mut protocol_buffer = ptr::null_mut();
        let mut protocol_buffer_count = 0;
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let protocols_per_handle = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), protocols_per_handle) };
        match protocols_per_handle(handle, ptr::addr_of_mut!(protocol_buffer), ptr::addr_of_mut!(protocol_buffer_count))
        {
            s if s.is_error() => Err(s),
            // SAFETY: The firmware allocates protocol_buffer and sets protocol_buffer_count.
            // from_raw_parts_mut creates a slice with the proper length as specified.
            _ => Ok(unsafe {
                BootServicesBox::<[_], _>::from_raw_parts_mut(protocol_buffer as *mut _, protocol_buffer_count, self)
            }),
        }
    }

    fn locate_handle_buffer(
        &self,
        search_type: HandleSearchType,
    ) -> Result<BootServicesBox<'_, [efi::Handle], Self>, efi::Status>
    where
        Self: Sized,
    {
        let mut buffer = ptr::null_mut();
        let mut buffer_count = 0;
        let protocol = match search_type {
            HandleSearchType::ByProtocol(p) => p as *const _ as *mut _,
            _ => ptr::null_mut(),
        };
        let search_key = match search_type {
            HandleSearchType::ByRegisterNotify(r) => r.as_ptr(),
            _ => ptr::null_mut(),
        };
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let locate_handle_buffer = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), locate_handle_buffer) };
        match locate_handle_buffer(
            search_type.into(),
            protocol,
            search_key,
            ptr::addr_of_mut!(buffer_count),
            ptr::addr_of_mut!(buffer),
        ) {
            s if s.is_error() => Err(s),
            // SAFETY: The firmware allocates buffer and sets buffer_count.
            // from_raw_parts_mut creates a slice with the proper length as specified.
            _ => Ok(unsafe {
                BootServicesBox::<[_], _>::from_raw_parts_mut(buffer as *mut efi::Handle, buffer_count, self)
            }),
        }
    }

    unsafe fn locate_protocol_unchecked(
        &self,
        protocol: &'static efi::Guid,
        registration: *mut c_void,
    ) -> Result<*mut c_void, efi::Status> {
        let mut interface = ptr::null_mut();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let locate_protocol = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), locate_protocol) };
        match locate_protocol(protocol as *const _ as *mut _, registration, ptr::addr_of_mut!(interface)) {
            s if s.is_error() => Err(s),
            _ => Ok(interface),
        }
    }

    fn load_image(
        &self,
        boot_policy: bool,
        parent_image_handle: efi::Handle,
        device_path: *mut efi::protocols::device_path::Protocol,
        source_buffer: Option<&[u8]>,
    ) -> Result<efi::Handle, efi::Status> {
        let source_buffer_ptr =
            source_buffer.map_or(ptr::null_mut(), |buffer| buffer.as_ptr() as *const _ as *mut c_void);
        let source_buffer_size = source_buffer.map_or(0, |buffer| buffer.len());
        let mut image_handle = MaybeUninit::uninit();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let load_image = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), load_image) };
        match load_image(
            boot_policy.into(),
            parent_image_handle,
            device_path,
            source_buffer_ptr,
            source_buffer_size,
            image_handle.as_mut_ptr(),
        ) {
            s if s.is_error() => Err(s),
            // SAFETY: If the call succeeded, image_handle has been initialized.
            _ => Ok(unsafe { image_handle.assume_init() }),
        }
    }

    fn start_image(
        &self,
        image_handle: efi::Handle,
    ) -> Result<(), (efi::Status, Option<BootServicesBox<'_, [u8], Self>>)> {
        let mut exit_data_size = MaybeUninit::uninit();
        let mut exit_data = MaybeUninit::uninit();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let start_image = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), start_image) };
        match start_image(image_handle, exit_data_size.as_mut_ptr(), exit_data.as_mut_ptr()) {
            s if s.is_error() => {
                // SAFETY: If exit_data pointer is not null, it points to valid memory.
                // exit_data_size contains the size of the allocated data. from_raw_parts_mut creates a proper slice.
                let data = (!exit_data.as_ptr().is_null()).then(|| unsafe {
                    BootServicesBox::from_raw_parts_mut(
                        exit_data.as_mut_ptr() as *mut u8,
                        exit_data_size.assume_init(),
                        self,
                    )
                });
                Err((s, data))
            }
            _ => Ok(()),
        }
    }

    fn unload_image(&self, image_handle: efi::Handle) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let unload_image = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), unload_image) };
        match unload_image(image_handle) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn exit<'a>(
        &'a self,
        image_handle: efi::Handle,
        exit_status: efi::Status,
        exit_data: Option<BootServicesBox<'a, [u8], Self>>,
    ) -> Result<(), efi::Status> {
        let exit_data_ptr = exit_data.as_ref().map_or(ptr::null_mut(), |data| data.as_ptr() as *mut u16);
        let exit_data_size = exit_data.as_ref().map_or(0, |data| data.len());
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let exit = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), exit) };
        match exit(image_handle, exit_status, exit_data_size, exit_data_ptr) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn exit_boot_services(&self, image_handle: efi::Handle, map_key: usize) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let exit_boot_services = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), exit_boot_services) };
        match exit_boot_services(image_handle, map_key) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn set_watchdog_timer(&self, timeout: usize) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let set_watchdog_timer = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), set_watchdog_timer) };
        match set_watchdog_timer(timeout, 0, 0, ptr::null_mut()) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    fn stall(&self, microseconds: usize) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let stall = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), stall) };
        match stall(microseconds) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    unsafe fn copy_mem_unchecked(&self, dest: *mut c_void, src: *const c_void, length: usize) {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let copy_mem = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), copy_mem) };
        copy_mem(dest, src as *mut _, length);
    }

    fn set_mem(&self, buffer: &mut [u8], value: u8) {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let set_mem = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), set_mem) };
        set_mem(buffer.as_mut_ptr() as *mut c_void, buffer.len(), value);
    }

    fn get_next_monotonic_count(&self) -> Result<u64, efi::Status> {
        let mut count = MaybeUninit::uninit();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let get_next_monotonic_count = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), get_next_monotonic_count) };
        match get_next_monotonic_count(count.as_mut_ptr()) {
            s if s.is_error() => Err(s),
            // SAFETY: If the UEFI call succeeded, count has been initialized.
            _ => Ok(unsafe { count.assume_init() }),
        }
    }

    unsafe fn install_configuration_table_unchecked(
        &self,
        guid: &efi::Guid,
        table: *mut c_void,
    ) -> Result<(), efi::Status> {
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let install_configuration_table =
            unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), install_configuration_table) };
        match install_configuration_table(guid as *const _ as *mut _, table) {
            s if s.is_error() => Err(s),
            _ => Ok(()),
        }
    }

    unsafe fn calculate_crc_32_unchecked(&self, data: *const c_void, data_size: usize) -> Result<u32, efi::Status> {
        let mut crc32 = MaybeUninit::uninit();
        // SAFETY: See safety comment in create_event_unchecked for details on corner cases around external modifications.
        let calculate_crc32 = unsafe { efi_boot_services_fn!(*self.as_mut_ptr(), calculate_crc32) };
        match calculate_crc32(data as *mut _, data_size, crc32.as_mut_ptr()) {
            s if s.is_error() => Err(s),
            // SAFETY: If the call succeeded, crc32 has been initialized.
            _ => Ok(unsafe { crc32.assume_init() }),
        }
    }
}

#[cfg(test)]
#[coverage(off)]
mod tests {
    use crate::BinaryGuid;
    use c_ptr::CPtr;
    use efi::{Boolean, Char16, OpenProtocolInformationEntry, protocols::device_path};

    use super::*;
    use core::{
        mem::MaybeUninit,
        slice,
        sync::atomic::{AtomicUsize, Ordering},
    };
    use std::os::raw::c_void;

    macro_rules! boot_services {
        ($($efi_services:ident = $efi_service_fn:ident),*) => {{
            // SAFETY: This is only used in tests. A zero sized BootServices struct is created
            // and only the specified function pointers are initialized with valid function
            // implementations. The StandardBootServices wrapper will handle uninitialized fields.
            let efi_boot_services = Box::leak(Box::new(unsafe {
                #[allow(unused_mut)]
                let mut bs = MaybeUninit::<efi::BootServices>::zeroed();
                $(
                bs.assume_init_mut().$efi_services = $efi_service_fn;
                )*
                bs.assume_init()
            }));
            StandardBootServices::new(efi_boot_services)
        }};
    }

    #[derive(Debug)]
    struct TestProtocol(u32);

    // Safety: TestProtocol provides a test protocol interface with a unique GUID for unit tests.
    // The GUID constant meets the requirements of the ProtocolInterface trait.
    unsafe impl ProtocolInterface for TestProtocol {
        const PROTOCOL_GUID: BinaryGuid =
            BinaryGuid::from_bytes(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
    }

    #[derive(Debug)]
    struct TestProtocolEmpty;

    // Safety: TestProtocolEmpty provides a test protocol interface with a unique GUID for unit tests.
    // The GUID constant meets the requirements of the ProtocolInterface trait. Zero-sized type is valid.
    unsafe impl ProtocolInterface for TestProtocolEmpty {
        const PROTOCOL_GUID: BinaryGuid =
            BinaryGuid::from_bytes(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
    }

    extern "efiapi" fn efi_allocate_pool_use_box(
        _mem_type: efi::MemoryType,
        size: usize,
        buffer: *mut *mut c_void,
    ) -> efi::Status {
        // Use u64 for ptr alignment.
        let allocation = vec![0_u64; size.div_ceil(mem::size_of::<u64>())].into_boxed_slice();
        // Safety: Test code - buffer pointer is valid for write, allocation is properly aligned.
        unsafe {
            *buffer = Box::into_raw(allocation) as *mut c_void;
        }
        efi::Status::SUCCESS
    }

    extern "efiapi" fn efi_free_pool_use_box(buffer: *mut c_void) -> efi::Status {
        if buffer.is_null() {
            return efi::Status::INVALID_PARAMETER;
        }

        // Safety: Test code - buffer was allocated by efi_allocate_pool_use_box as a Box<[u64]>.
        unsafe {
            let _ = Box::from_raw(buffer as *mut u8);
        }

        efi::Status::SUCCESS
    }

    #[test]
    #[should_panic(expected = "Standard Boot Services is not initialized!")]
    fn test_that_accessing_uninit_boot_services_should_panic() {
        let bs = StandardBootServices::new_uninit();
        // SAFETY: test code - accessing uninitialized boot services should panic.
        bs.as_mut_ptr();
    }

    #[test]
    fn test_debug_print_works_before_init() {
        let bs = StandardBootServices::new_uninit();
        let output = format!("{bs:?}");
        assert!(output.contains("Not Initialized"));
    }

    #[test]
    #[should_panic = "Boot services function create_event is not initialized."]
    fn test_create_event_not_init() {
        let boot_services = boot_services!();
        let _ = boot_services.create_event(EventType::RUNTIME, Tpl::APPLICATION, None, ());
    }

    #[test]
    fn test_create_event() {
        let boot_services = boot_services!(create_event = efi_create_event);

        extern "efiapi" fn notify_callback(_e: efi::Event, ctx: Box<i32>) {
            assert_eq!(10, *ctx)
        }

        extern "efiapi" fn efi_create_event(
            event_type: u32,
            notify_tpl: efi::Tpl,
            notify_function: Option<efi::EventNotify>,
            notify_context: *mut c_void,
            event: *mut efi::Event,
        ) -> efi::Status {
            assert_eq!(efi::EVT_RUNTIME | efi::EVT_NOTIFY_SIGNAL, event_type);
            assert_eq!(efi::TPL_APPLICATION, notify_tpl);
            // Safety: Test code - transmute from Option<EventNotify> function pointer to raw pointer for comparison.
            assert_eq!(notify_callback as *const fn(), unsafe {
                mem::transmute::<Option<extern "efiapi" fn(*mut c_void, *mut c_void)>, *const fn()>(notify_function)
            });
            assert_ne!(ptr::null_mut(), notify_context);
            assert_ne!(ptr::null_mut(), event);

            if let Some(notify_function) = notify_function {
                notify_function(ptr::null_mut(), notify_context);
            }
            efi::Status::SUCCESS
        }

        let ctx = Box::new(10);
        let status = boot_services.create_event(
            EventType::RUNTIME | EventType::NOTIFY_SIGNAL,
            Tpl::APPLICATION,
            Some(notify_callback),
            ctx,
        );

        assert!(status.is_ok());
    }

    #[test]
    fn test_create_event_no_notify() {
        let boot_services = boot_services!(create_event = efi_create_event);

        extern "efiapi" fn efi_create_event(
            event_type: u32,
            notify_tpl: efi::Tpl,
            notify_function: Option<efi::EventNotify>,
            notify_context: *mut c_void,
            event: *mut efi::Event,
        ) -> efi::Status {
            assert_eq!(efi::EVT_RUNTIME | efi::EVT_NOTIFY_SIGNAL, event_type);
            assert_eq!(efi::TPL_APPLICATION, notify_tpl);
            assert!(notify_function.is_none());
            assert_eq!(ptr::null_mut(), notify_context);
            assert_ne!(ptr::null_mut(), event);
            efi::Status::SUCCESS
        }

        let status =
            boot_services.create_event(EventType::RUNTIME | EventType::NOTIFY_SIGNAL, Tpl::APPLICATION, None, ());

        assert!(status.is_ok());
    }

    #[test]
    #[should_panic = "Boot services function create_event_ex is not initialized."]
    fn test_create_event_ex_not_init() {
        static GUID: efi::Guid = efi::Guid::from_fields(0, 0, 0, 0, 0, &[0; 6]);
        let boot_services = boot_services!();
        let _ = boot_services.create_event_ex(EventType::RUNTIME, Tpl::APPLICATION, None, (), &GUID);
    }

    #[test]
    fn test_create_event_ex() {
        let boot_services = boot_services!(create_event_ex = efi_create_event_ex);

        extern "efiapi" fn notify_callback(_e: efi::Event, ctx: Box<i32>) {
            assert_eq!(10, *ctx)
        }

        extern "efiapi" fn efi_create_event_ex(
            event_type: u32,
            notify_tpl: efi::Tpl,
            notify_function: Option<efi::EventNotify>,
            notify_context: *const c_void,
            event_group: *const efi::Guid,
            event: *mut efi::Event,
        ) -> efi::Status {
            assert_eq!(efi::EVT_RUNTIME | efi::EVT_NOTIFY_SIGNAL, event_type);
            assert_eq!(efi::TPL_APPLICATION, notify_tpl);
            // Safety: Test code - transmute from Option<EventNotify> function pointer to raw pointer for comparison.
            assert_eq!(notify_callback as *const fn(), unsafe {
                mem::transmute::<Option<extern "efiapi" fn(*mut c_void, *mut c_void)>, *const fn()>(notify_function)
            });
            assert_ne!(ptr::null(), notify_context);
            assert_eq!(ptr::addr_of!(GUID), event_group);
            assert_ne!(ptr::null_mut(), event);

            if let Some(notify_function) = notify_function {
                notify_function(ptr::null_mut(), notify_context as *mut _);
            }
            efi::Status::SUCCESS
        }
        static GUID: efi::Guid = efi::Guid::from_fields(0, 0, 0, 0, 0, &[0; 6]);
        let ctx = Box::new(10);
        let status = boot_services.create_event_ex(
            EventType::RUNTIME | EventType::NOTIFY_SIGNAL,
            Tpl::APPLICATION,
            Some(notify_callback),
            ctx,
            &GUID,
        );

        assert!(status.is_ok());
    }

    #[test]
    fn test_create_event_ex_no_notify() {
        let boot_services = boot_services!(create_event_ex = efi_create_event_ex);

        extern "efiapi" fn efi_create_event_ex(
            event_type: u32,
            notify_tpl: efi::Tpl,
            notify_function: Option<efi::EventNotify>,
            notify_context: *const c_void,
            event_group: *const efi::Guid,
            event: *mut efi::Event,
        ) -> efi::Status {
            assert_eq!(efi::EVT_RUNTIME | efi::EVT_NOTIFY_SIGNAL, event_type);
            assert_eq!(efi::TPL_APPLICATION, notify_tpl);
            assert!(notify_function.is_none());
            assert_eq!(ptr::null(), notify_context);
            assert_eq!(ptr::addr_of!(GUID), event_group);
            assert_ne!(ptr::null_mut(), event);
            efi::Status::SUCCESS
        }
        static GUID: efi::Guid = efi::Guid::from_fields(0, 0, 0, 0, 0, &[0; 6]);
        let status = boot_services.create_event_ex(
            EventType::RUNTIME | EventType::NOTIFY_SIGNAL,
            Tpl::APPLICATION,
            None,
            (),
            &GUID,
        );

        assert!(status.is_ok());
    }

    #[test]
    #[should_panic = "Boot services function close_event is not initialized."]
    fn test_close_event_not_init() {
        let boot_services = boot_services!();
        let _ = boot_services.close_event(ptr::null_mut());
    }

    #[test]
    fn test_close_event() {
        let boot_services = boot_services!(close_event = efi_close_event);

        extern "efiapi" fn efi_close_event(event: efi::Event) -> efi::Status {
            assert_eq!(1, event as usize);
            efi::Status::SUCCESS
        }

        let event = 1_usize as efi::Event;
        let status = boot_services.close_event(event);
        assert!(status.is_ok());
    }

    #[test]
    #[should_panic = "Boot services function signal_event is not initialized."]
    fn test_signal_event_not_init() {
        let boot_services = boot_services!();
        let _ = boot_services.signal_event(ptr::null_mut());
    }

    #[test]
    fn test_signal_event() {
        let boot_services = boot_services!(signal_event = efi_signal_event);

        extern "efiapi" fn efi_signal_event(event: efi::Event) -> efi::Status {
            assert_eq!(1, event as usize);
            efi::Status::SUCCESS
        }

        let event = 1_usize as efi::Event;
        let status = boot_services.signal_event(event);
        assert!(status.is_ok());
    }

    #[test]
    #[should_panic = "Boot services function wait_for_event is not initialized."]
    fn test_wait_for_event_not_init() {
        let boot_services = boot_services!();
        let mut events = vec![];
        let _ = boot_services.wait_for_event(&mut events);
    }

    #[test]
    fn test_wait_for_event() {
        let boot_services = boot_services!(wait_for_event = efi_wait_for_event);

        extern "efiapi" fn efi_wait_for_event(
            number_of_event: usize,
            events: *mut efi::Event,
            index: *mut usize,
        ) -> efi::Status {
            assert_eq!(2, number_of_event);
            assert_ne!(ptr::null_mut(), events);

            // Safety: Test code - index is valid for write.
            unsafe { ptr::write(index, 1) }
            efi::Status::SUCCESS
        }

        let mut events = [1_usize as efi::Event, 2_usize as efi::Event];
        let status = boot_services.wait_for_event(&mut events);
        assert!(matches!(status, Ok(1)));
    }

    #[test]
    #[should_panic = "Boot services function check_event is not initialized."]
    fn test_check_event_not_init() {
        let boot_services = boot_services!();
        let _ = boot_services.check_event(ptr::null_mut());
    }

    #[test]
    fn test_check_event() {
        let boot_services = boot_services!(check_event = efi_check_event);

        extern "efiapi" fn efi_check_event(event: efi::Event) -> efi::Status {
            assert_eq!(1, event as usize);
            efi::Status::SUCCESS
        }

        let event = 1_usize as efi::Event;
        let status = boot_services.check_event(event);
        assert!(status.is_ok());
    }

    #[test]
    #[should_panic = "Boot services function set_timer is not initialized."]
    fn test_set_timer_not_init() {
        let boot_services = boot_services!();
        let _ = boot_services.set_timer(ptr::null_mut(), EventTimerType::Relative, 0);
    }

    #[test]
    fn test_set_timer() {
        let boot_services = boot_services!(set_timer = efi_set_timer);

        extern "efiapi" fn efi_set_timer(event: efi::Event, r#type: efi::TimerDelay, trigger_time: u64) -> efi::Status {
            assert_eq!(1, event as usize);
            assert_eq!(efi::TIMER_PERIODIC, r#type);
            assert_eq!(200, trigger_time);
            efi::Status::SUCCESS
        }

        let event = 1_usize as efi::Event;
        let status = boot_services.set_timer(event, EventTimerType::Periodic, 200);
        assert!(status.is_ok());
    }

    #[test]
    fn test_raise_tpl_guarded() {
        let boot_services = boot_services!(raise_tpl = efi_raise_tpl, restore_tpl = efi_restore_tpl);

        static CURRENT_TPL: AtomicUsize = AtomicUsize::new(efi::TPL_APPLICATION);

        extern "efiapi" fn efi_raise_tpl(tpl: efi::Tpl) -> efi::Tpl {
            assert_eq!(efi::TPL_NOTIFY, tpl);
            CURRENT_TPL.swap(tpl, Ordering::Relaxed)
        }

        extern "efiapi" fn efi_restore_tpl(tpl: efi::Tpl) {
            assert_eq!(efi::TPL_APPLICATION, tpl);
            CURRENT_TPL.swap(tpl, Ordering::Relaxed);
        }

        let guard = boot_services.raise_tpl_guarded(Tpl::NOTIFY);
        assert_eq!(Tpl::APPLICATION, guard.retore_tpl);
        assert_eq!(efi::TPL_NOTIFY, CURRENT_TPL.load(Ordering::Relaxed));
        drop(guard);
        assert_eq!(efi::TPL_APPLICATION, CURRENT_TPL.load(Ordering::Relaxed));
    }

    #[test]
    #[should_panic = "Boot services function raise_tpl is not initialized."]
    fn test_raise_tpl_not_init() {
        let boot_services = boot_services!();
        let _ = boot_services.raise_tpl(Tpl::CALLBACK);
    }

    #[test]
    fn test_raise_tpl() {
        let boot_services = boot_services!(raise_tpl = efi_raise_tpl);

        extern "efiapi" fn efi_raise_tpl(tpl: efi::Tpl) -> efi::Tpl {
            assert_eq!(efi::TPL_NOTIFY, tpl);
            efi::TPL_APPLICATION
        }

        let status = boot_services.raise_tpl(Tpl::NOTIFY);
        assert_eq!(Tpl::APPLICATION, status);
    }

    #[test]
    #[should_panic = "Boot services function restore_tpl is not initialized."]
    fn test_restore_tpl_not_init() {
        let boot_services = boot_services!();
        boot_services.restore_tpl(Tpl::APPLICATION);
    }

    #[test]
    fn test_restore_tpl() {
        let boot_services = boot_services!(restore_tpl = efi_restore_tpl);

        extern "efiapi" fn efi_restore_tpl(tpl: efi::Tpl) {
            assert_eq!(efi::TPL_APPLICATION, tpl);
        }

        boot_services.restore_tpl(Tpl::APPLICATION);
    }

    #[test]
    #[should_panic = "Boot services function allocate_pages is not initialized."]
    fn test_allocate_pages_not_init() {
        let boot_services = boot_services!();
        let _ = boot_services.allocate_pages(AllocType::AnyPage, EfiMemoryType::ACPIMemoryNVS, 0);
    }

    #[test]
    fn test_allocate_pages() {
        let boot_services = boot_services!(allocate_pages = efi_allocate_pages);

        extern "efiapi" fn efi_allocate_pages(
            alloc_type: u32,
            mem_type: u32,
            nb_pages: usize,
            memory: *mut u64,
        ) -> efi::Status {
            let expected_alloc_type: efi::AllocateType = AllocType::AnyPage.into();
            assert_eq!(expected_alloc_type, alloc_type);
            let expected_mem_type: efi::MemoryType = EfiMemoryType::MemoryMappedIO.into();
            assert_eq!(expected_mem_type, mem_type);
            assert_eq!(4, nb_pages);
            assert_ne!(ptr::null_mut(), memory);
            // Safety: Test code - memory is valid for read.
            assert_eq!(0, unsafe { *memory });
            // Safety: Test code - memory is valid for write.
            unsafe { ptr::write(memory, 17) }
            efi::Status::SUCCESS
        }

        let status = boot_services.allocate_pages(AllocType::AnyPage, EfiMemoryType::MemoryMappedIO, 4);

        assert!(matches!(status, Ok(17)));
    }

    #[test]
    fn test_allocate_pages_at_specific_address() {
        let boot_services = boot_services!(allocate_pages = efi_allocate_pages);

        extern "efiapi" fn efi_allocate_pages(
            alloc_type: u32,
            mem_type: u32,
            nb_pages: usize,
            memory: *mut u64,
        ) -> efi::Status {
            let expected_alloc_type: efi::AllocateType = AllocType::Address(17).into();
            assert_eq!(expected_alloc_type, alloc_type);
            let expected_mem_type: efi::MemoryType = EfiMemoryType::MemoryMappedIO.into();
            assert_eq!(expected_mem_type, mem_type);
            assert_eq!(4, nb_pages);
            assert_ne!(ptr::null_mut(), memory);
            // Safety: Test code - memory is valid for read.
            assert_eq!(17, unsafe { *memory });
            efi::Status::SUCCESS
        }

        let status = boot_services.allocate_pages(AllocType::Address(17), EfiMemoryType::MemoryMappedIO, 4);
        assert!(matches!(status, Ok(17)));
    }

    #[test]
    #[should_panic = "Boot services function free_pages is not initialized."]
    fn test_free_pages_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.free_pages(0, 0);
    }

    #[test]
    fn test_free_pages() {
        let boot_services = boot_services!(free_pages = efi_free_pages);

        extern "efiapi" fn efi_free_pages(address: efi::PhysicalAddress, nb_pages: usize) -> efi::Status {
            assert_eq!(address, 0x100000);
            assert_eq!(nb_pages, 10);

            efi::Status::SUCCESS
        }

        let status = boot_services.free_pages(0x100000, 10);
        assert!(status.is_ok());
    }

    #[test]
    #[should_panic = "Boot services function allocate_pool is not initialized."]
    fn test_allocate_pool_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.allocate_pool(EfiMemoryType::ReservedMemoryType, 0);
    }

    #[test]
    fn test_allocate_pool() {
        let boot_services = boot_services!(allocate_pool = efi_allocate_pool);

        extern "efiapi" fn efi_allocate_pool(
            mem_type: efi::MemoryType,
            size: usize,
            buffer: *mut *mut c_void,
        ) -> efi::Status {
            let expected_mem_type: efi::MemoryType = EfiMemoryType::MemoryMappedIO.into();
            assert_eq!(mem_type, expected_mem_type);
            assert_eq!(size, 10);
            // SAFETY: Test mock - writing a test value to the output parameter.
            unsafe { ptr::write(buffer, 0x55AA as *mut c_void) };
            efi::Status::SUCCESS
        }

        let status = boot_services.allocate_pool(EfiMemoryType::MemoryMappedIO, 10);
        assert_eq!(status, Ok(0x55AA as *mut u8));
    }

    #[test]
    fn test_allocate_pool_for_type() {
        let boot_services = boot_services!(allocate_pool = efi_allocate_pool);

        extern "efiapi" fn efi_allocate_pool(
            mem_type: efi::MemoryType,
            _size: usize,
            buffer: *mut *mut c_void,
        ) -> efi::Status {
            let expected_mem_type: efi::MemoryType = EfiMemoryType::MemoryMappedIO.into();
            assert_eq!(mem_type, expected_mem_type);
            // SAFETY: Test mock - writing a test value to the output parameter.
            unsafe { ptr::write(buffer, 0x55AA as *mut c_void) };
            efi::Status::SUCCESS
        }

        let status = boot_services.allocate_pool_for_type(EfiMemoryType::MemoryMappedIO);
        assert_eq!(status, Ok(0x55AA as *mut u8));
    }

    #[test]
    fn test_free_pool() {
        let boot_services = boot_services!(free_pool = efi_free_pool);

        extern "efiapi" fn efi_free_pool(buffer: *mut c_void) -> efi::Status {
            if buffer.is_null() {
                efi::Status::INVALID_PARAMETER
            } else {
                assert_eq!(buffer, 0xffff0000 as *mut u8 as *mut c_void);
                efi::Status::SUCCESS
            }
        }

        // positive test
        let status = boot_services.free_pool(0xffff0000 as *mut u8);
        assert_eq!(status, Ok(()));

        // negative test
        let status = boot_services.free_pool(ptr::null_mut());
        assert_eq!(status, Err(efi::Status::INVALID_PARAMETER));
    }

    #[test]
    #[should_panic = "Boot services function install_protocol_interface is not initialized."]
    fn test_install_protocol_interface_not_init() {
        let boot_services = boot_services!();
        let _ = boot_services.install_protocol_interface(None, Box::new(TestProtocol(10)));
    }

    #[test]
    fn test_install_protocol_interface() {
        let boot_services = boot_services!(install_protocol_interface = efi_install_protocol_interface);

        extern "efiapi" fn efi_install_protocol_interface(
            handle: *mut efi::Handle,
            guid: *mut efi::Guid,
            interface_type: u32,
            interface: *mut c_void,
        ) -> efi::Status {
            assert_ne!(ptr::null_mut(), handle);
            // SAFETY: Test mock - reading input parameter to verify it's null.
            assert_eq!(ptr::null_mut(), unsafe { ptr::read(handle) });
            // SAFETY: Test mock - reading input parameters to verify correctness.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(guid) });
            assert_eq!(efi::NATIVE_INTERFACE, interface_type);
            // SAFETY: Test mock - reading test protocol value.
            assert_eq!(42, unsafe { ptr::read(interface as *mut u32) });

            // SAFETY: Test mock - writing output parameter.
            unsafe {
                ptr::write(handle, 17_usize as _);
            }

            efi::Status::SUCCESS
        }

        let (handle, _) = boot_services.install_protocol_interface(None, Box::new(TestProtocol(42))).unwrap();

        assert_eq!(17, handle as usize);
    }

    #[test]
    fn test_install_protocol_interface_err() {
        let boot_services = boot_services!(install_protocol_interface = efi_install_protocol_interface);

        extern "efiapi" fn efi_install_protocol_interface(
            handle: *mut efi::Handle,
            guid: *mut efi::Guid,
            interface_type: u32,
            interface: *mut c_void,
        ) -> efi::Status {
            assert_ne!(ptr::null_mut(), handle);
            // SAFETY: Test mock - reading input parameter to verify it's null.
            assert_eq!(ptr::null_mut(), unsafe { ptr::read(handle) });
            // SAFETY: Test mock - reading input parameters to verify correctness.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(guid) });
            assert_eq!(efi::NATIVE_INTERFACE, interface_type);
            // SAFETY: Test mock - reading test protocol value.
            assert_eq!(42, unsafe { ptr::read(interface as *mut u32) });

            // SAFETY: Test mock - writing output parameter.
            unsafe {
                ptr::write(handle, 17_usize as _);
            }

            efi::Status::ALREADY_STARTED
        }

        let status = boot_services.install_protocol_interface(None, Box::new(TestProtocol(42))).err().unwrap();

        assert_eq!(efi::Status::ALREADY_STARTED, status);
    }

    #[test]
    fn test_install_protocol_empty() {
        let boot_services = boot_services!(install_protocol_interface = efi_install_protocol_interface);

        extern "efiapi" fn efi_install_protocol_interface(
            handle: *mut efi::Handle,
            guid: *mut efi::Guid,
            interface_type: u32,
            interface: *mut c_void,
        ) -> efi::Status {
            assert_ne!(ptr::null_mut(), handle);
            // SAFETY: Test mock - reading test handle value to verify.
            assert_eq!(17, unsafe { ptr::read::<efi::Handle>(handle) } as usize);
            // SAFETY: Test mock - reading GUID parameter to verify correctness.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(guid) });
            assert_eq!(efi::NATIVE_INTERFACE, interface_type);
            assert_eq!(ptr::null_mut(), interface);

            efi::Status::SUCCESS
        }

        let (handle, _) = boot_services
            .install_protocol_interface(Some(17_usize as efi::Handle), Box::new(TestProtocolEmpty))
            .unwrap();

        assert_eq!(17, handle as usize);
    }

    #[test]
    #[should_panic = "Boot services function uninstall_protocol_interface is not initialized."]
    fn test_uninstall_protocol_interface_not_init() {
        let boot_services = boot_services!();
        let b = Box::new(TestProtocol(10));
        let key = CPtr::metadata(&b);
        _ = boot_services.uninstall_protocol_interface(ptr::null_mut(), key);
    }

    #[test]
    fn test_uninstall_protocol_interface() {
        let boot_services = boot_services!(uninstall_protocol_interface = efi_uninstall_protocol_interface);

        static ADDR: AtomicUsize = AtomicUsize::new(0);

        extern "efiapi" fn efi_uninstall_protocol_interface(
            handle: efi::Handle,
            protocol: *mut efi::Guid,
            interface: *mut c_void,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            // SAFETY: Test mock - reading protocol GUID parameter to verify correctness.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_eq!(ADDR.load(Ordering::Relaxed), interface as usize);
            efi::Status::SUCCESS
        }
        let b = Box::new(TestProtocol(10));
        let key = b.metadata();
        ADDR.store(key.ptr_value, Ordering::Relaxed);
        let ptr = b.into_ptr();
        let interface = boot_services.uninstall_protocol_interface(1_usize as _, key).unwrap();
        assert_eq!(ptr, interface.as_ptr());
    }

    #[test]
    fn test_uninstall_protocol_empty() {
        let boot_services = boot_services!(uninstall_protocol_interface = efi_uninstall_protocol_interface);

        extern "efiapi" fn efi_uninstall_protocol_interface(
            handle: efi::Handle,
            protocol: *mut efi::Guid,
            interface: *mut c_void,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            // SAFETY: Test mock - reading protocol GUID from test infrastructure to verify it matches TestProtocolEmpty.
            assert_eq!(TestProtocolEmpty::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_eq!(ptr::null_mut(), interface);
            efi::Status::SUCCESS
        }
        let b = Box::new(TestProtocolEmpty);
        let key = b.metadata();
        boot_services.uninstall_protocol_interface(1_usize as _, key).unwrap();
    }

    #[test]
    #[should_panic = "Boot services function reinstall_protocol_interface is not initialized."]
    fn test_reinstall_protocol_interface_not_init() {
        let boot_services = boot_services!();
        let b = Box::new(TestProtocol(10));
        let key = CPtr::metadata(&b);
        _ = boot_services.reinstall_protocol_interface(ptr::null_mut(), key, Box::new(TestProtocol(20)));
    }

    #[test]
    fn test_reinstall_protocol_interface() {
        let boot_services = boot_services!(reinstall_protocol_interface = efi_reinstall_protocol_interface);

        extern "efiapi" fn efi_reinstall_protocol_interface(
            handle: efi::Handle,
            protocol: *mut efi::Guid,
            old_interface: *mut c_void,
            new_interface: *mut c_void,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            // SAFETY: Test mock - reading protocol GUID from reinstall operation to verify correct protocol.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_ne!(ptr::null_mut(), old_interface);
            assert_ne!(ptr::null_mut(), new_interface);
            efi::Status::SUCCESS
        }

        let old_interface = Box::new(TestProtocol(10));
        let old_key = CPtr::metadata(&old_interface);
        let old_ptr = old_interface.into_ptr();

        let new_interface = Box::new(TestProtocol(20));
        let new_ptr = new_interface.as_ptr();

        let (new_key, old_interface) =
            boot_services.reinstall_protocol_interface(1_usize as _, old_key, new_interface).unwrap();

        assert_eq!(new_key.ptr_value, new_ptr as usize);
        assert_eq!(old_ptr, old_interface.into_ptr());
    }

    #[test]
    #[should_panic = "Boot services function register_protocol_notify is not initialized."]
    fn test_register_protocol_notify_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.register_protocol_notify(&TestProtocol::PROTOCOL_GUID, ptr::null_mut());
    }

    #[test]
    fn test_register_protocol_notify() {
        let boot_services = boot_services!(register_protocol_notify = efi_register_protocol_notify);

        extern "efiapi" fn efi_register_protocol_notify(
            protocol: *mut efi::Guid,
            event: *mut c_void,
            registration: *mut *mut c_void,
        ) -> efi::Status {
            // SAFETY: Test mock - reading protocol GUID to verify notification registration for correct protocol.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_eq!(1, event as usize);
            assert_ne!(ptr::null_mut(), registration);
            // SAFETY: Test mock - writing registration token output parameter.
            unsafe { ptr::write(registration, 10_usize as _) };
            efi::Status::SUCCESS
        }

        let registration = boot_services.register_protocol_notify(&TestProtocol::PROTOCOL_GUID, 1_usize as _).unwrap();
        assert_eq!(10, registration.as_ptr() as usize);
    }

    #[test]
    #[should_panic = "Boot services function locate_handle is not initialized."]
    fn test_locate_handle_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.locate_handle(HandleSearchType::AllHandle);
    }

    #[test]
    fn test_locate_handle_all_handles() {
        let boot_services = boot_services!(
            locate_handle = efi_locate_handle,
            allocate_pool = efi_allocate_pool_use_box,
            free_pool = efi_free_pool_use_box
        );

        extern "efiapi" fn efi_locate_handle(
            search_type: efi::LocateSearchType,
            protocol: *mut efi::Guid,
            search_key: *mut c_void,
            buffer_size: *mut usize,
            buffer: *mut efi::Handle,
        ) -> efi::Status {
            assert_eq!(efi::ALL_HANDLES, search_type);
            assert_eq!(ptr::null_mut(), protocol);
            assert_eq!(ptr::null_mut(), search_key);
            assert_ne!(ptr::null_mut(), buffer_size);

            match buffer {
                buffer if buffer.is_null() => {
                    // SAFETY: Test mock - reading buffer_size to verify it's initially zero for size query.
                    assert_eq!(0, unsafe { ptr::read(buffer_size) });
                    // SAFETY: Test mock - writing required buffer size back to caller.
                    unsafe { ptr::write(buffer_size, mem::size_of::<usize>()) };
                }
                _ => {
                    // SAFETY: Test mock - writing test handle value to output buffer.
                    unsafe { ptr::write(buffer, 10_usize as _) };
                }
            }

            efi::Status::SUCCESS
        }

        let handles = boot_services.locate_handle(HandleSearchType::AllHandle).unwrap();
        assert_eq!(1, handles.len());
        assert_eq!(10, handles[0] as usize);
    }

    #[test]
    fn test_locate_handle_by_protocol() {
        let boot_services = boot_services!(
            locate_handle = efi_locate_handle,
            allocate_pool = efi_allocate_pool_use_box,
            free_pool = efi_free_pool_use_box
        );

        extern "efiapi" fn efi_locate_handle(
            search_type: efi::LocateSearchType,
            protocol: *mut efi::Guid,
            search_key: *mut c_void,
            buffer_size: *mut usize,
            buffer: *mut efi::Handle,
        ) -> efi::Status {
            assert_eq!(efi::BY_PROTOCOL, search_type);
            // SAFETY: Test mock - reading protocol GUID to verify locate by protocol search.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_eq!(ptr::null_mut(), search_key);
            assert_ne!(ptr::null_mut(), buffer_size);

            match buffer {
                buffer if buffer.is_null() => {
                    // SAFETY: Test mock - reading buffer_size to verify size query phase.
                    assert_eq!(0, unsafe { ptr::read(buffer_size) });
                    // SAFETY: Test mock - writing required buffer size for handle array.
                    unsafe { ptr::write(buffer_size, mem::size_of::<usize>()) };
                }
                _ => {
                    // SAFETY: Test mock - writing test handle to output buffer.
                    unsafe { ptr::write(buffer, 10_usize as _) };
                }
            }

            efi::Status::SUCCESS
        }

        let handles = boot_services.locate_handle(HandleSearchType::ByProtocol(&TestProtocol::PROTOCOL_GUID)).unwrap();
        assert_eq!(1, handles.len());
        assert_eq!(10, handles[0] as usize);
    }

    #[test]
    fn test_locate_handle_by_registry_notify() {
        let boot_services = boot_services!(
            locate_handle = efi_locate_handle,
            allocate_pool = efi_allocate_pool_use_box,
            free_pool = efi_free_pool_use_box
        );

        extern "efiapi" fn efi_locate_handle(
            search_type: efi::LocateSearchType,
            protocol: *mut efi::Guid,
            search_key: *mut c_void,
            buffer_size: *mut usize,
            buffer: *mut efi::Handle,
        ) -> efi::Status {
            assert_eq!(efi::BY_REGISTER_NOTIFY, search_type);
            assert_eq!(ptr::null_mut(), protocol);
            assert_eq!(10, search_key as usize);
            assert_ne!(ptr::null_mut(), buffer_size);

            match buffer {
                buffer if buffer.is_null() => {
                    // SAFETY: Test mock - reading buffer_size to verify size query for register notify search.
                    assert_eq!(0, unsafe { ptr::read(buffer_size) });
                    // SAFETY: Test mock - writing required buffer size for notification handles.
                    unsafe { ptr::write(buffer_size, mem::size_of::<usize>()) };
                }
                _ => {
                    // SAFETY: Test mock - writing test handle to notification output buffer.
                    unsafe { ptr::write(buffer, 10_usize as _) };
                }
            }

            efi::Status::SUCCESS
        }

        let handles = boot_services
            .locate_handle(HandleSearchType::ByRegisterNotify(
                // SAFETY: Test code - creating non-null pointer from test registration value (10).
                unsafe { NonNull::new_unchecked(10_usize as _) },
            ))
            .unwrap();
        assert_eq!(1, handles.len());
        assert_eq!(10, handles[0] as usize);
    }

    #[test]
    #[should_panic = "Boot services function handle_protocol is not initialized."]
    fn test_handle_protocol_not_init() {
        let boot_services = boot_services!();
        // SAFETY: Test code - intentionally calling uninitialized function to verify panic.
        _ = unsafe { boot_services.handle_protocol::<TestProtocol>(ptr::null_mut()) };
    }

    #[test]
    fn test_handle_protocol() {
        let boot_services = boot_services!(handle_protocol = efi_handle_protocol);

        extern "efiapi" fn efi_handle_protocol(
            handle: *mut c_void,
            protocol: *mut efi::Guid,
            interface: *mut *mut c_void,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            // SAFETY: Test mock - reading protocol GUID to verify handle_protocol request.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_ne!(ptr::null_mut(), interface);
            let b = Box::new(12);
            // SAFETY: Test mock - writing test protocol interface pointer to output parameter.
            unsafe { ptr::write(interface, b.into_mut_ptr() as *mut _) };
            efi::Status::SUCCESS
        }

        // SAFETY: Test code - calling handle_protocol with test handle (1) to retrieve protocol interface.
        let interface = unsafe { boot_services.handle_protocol::<TestProtocol>(1_usize as _) }.unwrap();
        assert_eq!(12, interface.0);
    }

    #[test]
    fn test_handle_protocol_empty() {
        let boot_services = boot_services!(handle_protocol = efi_handle_protocol);

        extern "efiapi" fn efi_handle_protocol(
            handle: *mut c_void,
            protocol: *mut efi::Guid,
            interface: *mut *mut c_void,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            // SAFETY: Test mock - reading protocol GUID to verify zero-sized protocol request.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_ne!(ptr::null_mut(), interface);
            efi::Status::SUCCESS
        }

        // SAFETY: Test code - calling handle_protocol for zero-sized TestProtocolEmpty.
        _ = unsafe { boot_services.handle_protocol::<TestProtocolEmpty>(1_usize as _) }.unwrap();
    }

    #[test]
    #[should_panic = "Boot services function locate_device_path is not initialized."]
    fn test_locate_device_path_not_init() {
        let boot_services = boot_services!();
        // SAFETY: Test code - intentionally calling uninitialized function to verify panic.
        _ = unsafe { boot_services.locate_device_path(&TestProtocol::PROTOCOL_GUID, ptr::null_mut()) };
    }

    #[test]
    fn test_locate_device_path() {
        let boot_services = boot_services!(locate_device_path = efi_locate_device_path);

        extern "efiapi" fn efi_locate_device_path(
            protocol: *mut efi::Guid,
            device_path: *mut *mut device_path::Protocol,
            device: *mut efi::Handle,
        ) -> efi::Status {
            // SAFETY: Test mock - reading protocol GUID to verify device path location request.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_eq!(1, device_path as usize);
            assert_ne!(ptr::null_mut(), device);
            // SAFETY: Test mock - writing test device handle to output parameter.
            unsafe { ptr::write(device, 12_usize as _) };
            efi::Status::SUCCESS
        }

        // SAFETY: Test code - calling locate_device_path with test device path pointer (1).
        let handle = unsafe { boot_services.locate_device_path(&TestProtocol::PROTOCOL_GUID, 1_usize as _) }.unwrap();
        assert_eq!(12, handle as usize);
    }

    #[test]
    #[should_panic = "Boot services function open_protocol is not initialized."]
    fn test_open_protocol_not_init() {
        let boot_services = boot_services!();
        // SAFETY: Test code - intentionally calling uninitialized function to verify panic.
        _ = unsafe {
            boot_services.open_protocol::<TestProtocol>(ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), 0)
        };
    }

    #[test]
    fn test_open_protocol() {
        let boot_services = boot_services!(open_protocol = efi_open_protocol);

        extern "efiapi" fn efi_open_protocol(
            handle: efi::Handle,
            protocol: *mut efi::Guid,
            interface: *mut *mut c_void,
            agent_handle: efi::Handle,
            controller_handle: efi::Handle,
            attributes: u32,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            // SAFETY: Test mock - reading protocol GUID to verify open_protocol request.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_ne!(ptr::null_mut(), interface);
            assert_eq!(2, agent_handle as usize);
            assert_eq!(3, controller_handle as usize);
            assert_eq!(4, attributes);

            let b = Box::new(12);
            // SAFETY: Test mock - writing protocol interface pointer to output parameter.
            unsafe { ptr::write(interface, b.into_mut_ptr() as _) };

            efi::Status::SUCCESS
        }

        // SAFETY: Test code - calling open_protocol with test handles to retrieve protocol interface.
        let interface = unsafe {
            boot_services.open_protocol::<TestProtocol>(1_usize as _, 2_usize as _, 3_usize as _, 4).unwrap()
        };

        assert_eq!(12, interface.0)
    }

    #[test]
    fn test_open_protocol_empty() {
        let boot_services = boot_services!(open_protocol = efi_open_protocol);

        extern "efiapi" fn efi_open_protocol(
            handle: efi::Handle,
            protocol: *mut efi::Guid,
            interface: *mut *mut c_void,
            agent_handle: efi::Handle,
            controller_handle: efi::Handle,
            attributes: u32,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            // SAFETY: Test mock - reading protocol GUID to verify zero-sized protocol open request.
            assert_eq!(TestProtocolEmpty::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_ne!(ptr::null_mut(), interface);
            assert_eq!(2, agent_handle as usize);
            assert_eq!(3, controller_handle as usize);
            assert_eq!(4, attributes);
            efi::Status::SUCCESS
        }

        // SAFETY: Test code - calling open_protocol for zero-sized TestProtocolEmpty.
        _ = unsafe { boot_services.open_protocol::<TestProtocolEmpty>(1_usize as _, 2_usize as _, 3_usize as _, 4) }
            .unwrap()
    }

    #[test]
    #[should_panic = "Boot services function close_protocol is not initialized."]
    fn test_close_protocol_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.close_protocol(
            ptr::null_mut(),
            &TestProtocol::PROTOCOL_GUID,
            ptr::null_mut(),
            ptr::null_mut(),
        );
    }

    #[test]
    fn test_close_protocol() {
        let boot_services = boot_services!(close_protocol = efi_close_protocol);

        extern "efiapi" fn efi_close_protocol(
            handle: efi::Handle,
            protocol: *mut efi::Guid,
            agent_handle: efi::Handle,
            controller_handle: efi::Handle,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            // SAFETY: Test mock - reading protocol GUID to verify close_protocol request.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_eq!(2, agent_handle as usize);
            assert_eq!(3, controller_handle as usize);

            efi::Status::SUCCESS
        }

        boot_services.close_protocol(1_usize as _, &TestProtocol::PROTOCOL_GUID, 2_usize as _, 3_usize as _).unwrap();
    }

    #[test]
    #[should_panic = "Boot services function open_protocol_information is not initialized."]
    fn test_open_protocol_information_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.open_protocol_information(ptr::null_mut(), &TestProtocol::PROTOCOL_GUID);
    }

    #[test]
    fn test_open_protocol_information() {
        let boot_services = boot_services!(
            open_protocol_information = efi_open_protocol_information,
            free_pool = efi_free_pool_use_box
        );

        extern "efiapi" fn efi_open_protocol_information(
            handle: efi::Handle,
            protocol: *mut efi::Guid,
            entry_buffer: *mut *mut efi::OpenProtocolInformationEntry,
            entry_count: *mut usize,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            // SAFETY: Test mock - reading protocol GUID to verify open_protocol_information request.
            assert_eq!(TestProtocol::PROTOCOL_GUID, unsafe { ptr::read(protocol) });
            assert_ne!(ptr::null_mut(), entry_buffer);
            assert_ne!(ptr::null_mut(), entry_count);

            let buff = Box::new([efi::OpenProtocolInformationEntry {
                agent_handle: ptr::null_mut(),
                controller_handle: ptr::null_mut(),
                attributes: 10,
                open_count: 0,
            }])
            .into_mut_ptr() as *mut OpenProtocolInformationEntry;

            // SAFETY: Test mock - writing entry buffer pointer and count to output parameters.
            unsafe {
                ptr::write(entry_buffer, buff);
                ptr::write(entry_count, 1)
            };

            efi::Status::SUCCESS
        }

        let info = boot_services.open_protocol_information(1_usize as _, &TestProtocol::PROTOCOL_GUID).unwrap();
        assert_eq!(1, info.len());
        assert_eq!(10, info[0].attributes);
    }

    #[test]
    #[should_panic = "Boot services function connect_controller is not initialized."]
    fn test_connect_controller_not_init() {
        let boot_services = boot_services!();
        // SAFETY: Test code - calling uninitialized connect_controller to verify panic behavior.
        _ = unsafe { boot_services.connect_controller(ptr::null_mut(), vec![], ptr::null_mut(), false) };
    }

    #[test]
    fn test_connect_controller() {
        let boot_services = boot_services!(connect_controller = efi_connect_controller);

        extern "efiapi" fn efi_connect_controller(
            controller_handle: efi::Handle,
            driver_image_handles: *mut efi::Handle,
            remaining_device_path: *mut device_path::Protocol,
            recursive: Boolean,
        ) -> efi::Status {
            assert_eq!(1, controller_handle as usize);
            assert_eq!(ptr::null_mut(), driver_image_handles);
            assert_eq!(2, remaining_device_path as usize);
            assert!(!bool::from(recursive));
            efi::Status::SUCCESS
        }

        // SAFETY: Test code - calling connect_controller with valid test parameters.
        unsafe { boot_services.connect_controller(1_usize as _, vec![], 2_usize as _, false) }.unwrap();
    }

    #[test]
    fn test_connect_controller_with_image_handles() {
        let boot_services = boot_services!(connect_controller = efi_connect_controller);

        extern "efiapi" fn efi_connect_controller(
            controller_handle: efi::Handle,
            driver_image_handles: *mut efi::Handle,
            remaining_device_path: *mut device_path::Protocol,
            recursive: Boolean,
        ) -> efi::Status {
            assert_eq!(1, controller_handle as usize);
            assert_ne!(ptr::null_mut(), driver_image_handles);
            // SAFETY: Test mock - reading image handles array to verify correct driver handles provided.
            let image_handles = unsafe { slice::from_raw_parts(driver_image_handles as *const usize, 3) };
            assert_eq!([1, 2, 0], image_handles);
            assert_eq!(2, remaining_device_path as usize);
            assert!(!bool::from(recursive));
            efi::Status::SUCCESS
        }

        // SAFETY: Test code - calling connect_controller with image handles vector.
        unsafe {
            boot_services.connect_controller(1_usize as _, vec![1_usize as _, 2_usize as _], 2_usize as _, false)
        }
        .unwrap();
    }

    #[test]
    #[should_panic = "Boot services function disconnect_controller is not initialized."]
    fn test_disconnect_controller_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.disconnect_controller(ptr::null_mut(), None, None);
    }

    #[test]
    fn test_disconnect_controller() {
        let boot_services = boot_services!(disconnect_controller = efi_disconnect_controller);

        extern "efiapi" fn efi_disconnect_controller(
            controller_handle: efi::Handle,
            driver_image_handle: efi::Handle,
            child_handle: efi::Handle,
        ) -> efi::Status {
            assert_eq!(1, controller_handle as usize);
            assert_eq!(ptr::null_mut(), driver_image_handle);
            assert_eq!(ptr::null_mut(), child_handle);
            efi::Status::SUCCESS
        }
        boot_services.disconnect_controller(1_usize as _, None, None).unwrap();
    }

    #[test]
    fn test_disconnect_controller_with_handles() {
        let boot_services = boot_services!(disconnect_controller = efi_disconnect_controller);

        extern "efiapi" fn efi_disconnect_controller(
            controller_handle: efi::Handle,
            driver_image_handle: efi::Handle,
            child_handle: efi::Handle,
        ) -> efi::Status {
            assert_eq!(1, controller_handle as usize);
            assert_eq!(2, driver_image_handle as usize);
            assert_eq!(3, child_handle as usize);
            efi::Status::SUCCESS
        }
        boot_services.disconnect_controller(1_usize as _, Some(2_usize as _), Some(3_usize as _)).unwrap();
    }

    #[test]
    #[should_panic = "Boot services function protocols_per_handle is not initialized."]
    fn test_protocol_per_handle_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.protocols_per_handle(ptr::null_mut());
    }

    #[test]
    fn test_protocol_per_handle() {
        let boot_services =
            boot_services!(protocols_per_handle = efi_protocol_per_handle, free_pool = efi_free_pool_use_box);

        extern "efiapi" fn efi_protocol_per_handle(
            handle: efi::Handle,
            protocol_buffer: *mut *mut *mut efi::Guid,
            protocol_buffer_count: *mut usize,
        ) -> efi::Status {
            assert_eq!(1, handle as usize);
            assert_ne!(ptr::null_mut(), protocol_buffer);
            assert_ne!(ptr::null_mut(), protocol_buffer_count);

            static PROTOCOL_GUID: BinaryGuid = TestProtocol::PROTOCOL_GUID;
            #[allow(unused_allocation)]
            let buff = Box::new(PROTOCOL_GUID.as_efi_guid() as *const efi::Guid as *mut efi::Guid).into_mut_ptr();

            // SAFETY: Test mock - writing protocol GUID buffer pointer and count to output parameters.
            unsafe {
                ptr::write(protocol_buffer, buff);
                ptr::write(protocol_buffer_count, 1);
            }

            efi::Status::SUCCESS
        }

        let protocols = boot_services.protocols_per_handle(1_usize as _).unwrap();
        assert_eq!(1, protocols.len());
        assert_eq!(TestProtocol::PROTOCOL_GUID, *protocols[0]);
    }

    #[test]
    #[should_panic = "Boot services function locate_protocol is not initialized."]
    fn test_locate_protocol_not_init() {
        let boot_services = boot_services!();
        // SAFETY: Test code - calling uninitialized locate_protocol to verify panic behavior.
        _ = unsafe { boot_services.locate_protocol::<TestProtocol>(None) };
    }

    #[test]
    fn test_locate_protocol() {
        let boot_services = boot_services!(locate_protocol = efi_locate_protocol);

        static PROTOCOL_INTERFACE: u32 = 10;

        extern "efiapi" fn efi_locate_protocol(
            protocol_guid: *mut efi::Guid,
            registration: *mut c_void,
            interface: *mut *mut c_void,
        ) -> efi::Status {
            assert!(!protocol_guid.is_null());
            assert!(registration.is_null());
            assert!(!interface.is_null());
            // SAFETY: Test mock - reading protocol GUID to verify locate_protocol request for TestProtocol.
            assert_eq!(unsafe { ptr::read(protocol_guid) }, TestProtocol::PROTOCOL_GUID);
            // SAFETY: Test mock - writing protocol interface pointer to output parameter.
            unsafe { ptr::write(interface, &PROTOCOL_INTERFACE as *const u32 as *mut u32 as *mut c_void) };
            efi::Status::SUCCESS
        }

        // SAFETY: Test code - calling locate_protocol for TestProtocol with no registration.
        let protocol = unsafe { boot_services.locate_protocol::<TestProtocol>(None) }.unwrap();

        assert_eq!(PROTOCOL_INTERFACE, protocol.0);
    }

    #[test]
    fn test_locate_protocol_empty() {
        let boot_services = boot_services!(locate_protocol = efi_locate_protocol);

        extern "efiapi" fn efi_locate_protocol(
            protocol_guid: *mut efi::Guid,
            registration: *mut c_void,
            interface: *mut *mut c_void,
        ) -> efi::Status {
            assert!(!protocol_guid.is_null());
            assert!(registration.is_null());
            assert!(!interface.is_null());
            // SAFETY: Test mock - reading protocol GUID to verify locate_protocol request for zero-sized protocol.
            assert_eq!(unsafe { ptr::read(protocol_guid) }, TestProtocolEmpty::PROTOCOL_GUID);
            efi::Status::SUCCESS
        }

        // SAFETY: Test code - calling locate_protocol for zero-sized TestProtocolEmpty.
        unsafe { boot_services.locate_protocol::<TestProtocolEmpty>(None) }.unwrap();
    }

    #[test]
    #[should_panic = "Boot services function load_image is not initialized."]
    fn test_load_image_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.load_image(false, ptr::null_mut(), ptr::null_mut(), None);
    }

    #[test]
    fn test_load_image() {
        let boot_services = boot_services!(load_image = efi_load_image);

        extern "efiapi" fn efi_load_image(
            boot_policy: Boolean,
            parent_image_handler: *mut c_void,
            device_path: *mut device_path::Protocol,
            source_buffer: *mut c_void,
            source_size: usize,
            image_handler: *mut *mut c_void,
        ) -> efi::Status {
            assert!(bool::from(boot_policy));
            assert_eq!(1, parent_image_handler as usize);
            assert_eq!(2, device_path as usize);
            assert_eq!(5, source_size);
            // SAFETY: Test mock - reading source buffer to verify image data provided to load_image.
            let source = unsafe { slice::from_raw_parts(source_buffer as *mut u8, source_size) };
            assert_eq!(&[1_u8, 2, 3, 4, 5], source);
            // SAFETY: Test mock - writing image handle to output parameter.
            unsafe {
                ptr::write(image_handler, 3_usize as _);
            }
            efi::Status::SUCCESS
        }

        let image_handle = boot_services
            .load_image(
                true,
                std::ptr::dangling_mut::<c_void>(),
                2_usize as *mut device_path::Protocol,
                Some(&[1_u8, 2, 3, 4, 5]),
            )
            .unwrap();

        assert_eq!(3, image_handle as usize);
    }

    #[test]
    fn test_load_image_from_source() {
        let boot_services = boot_services!(load_image = efi_load_image);

        extern "efiapi" fn efi_load_image(
            boot_policy: Boolean,
            parent_image_handler: *mut c_void,
            device_path: *mut device_path::Protocol,
            source_buffer: *mut c_void,
            source_size: usize,
            _image_handler: *mut *mut c_void,
        ) -> efi::Status {
            assert!(!bool::from(boot_policy));
            assert_eq!(1, parent_image_handler as usize);
            assert_eq!(2, device_path as usize);
            assert_eq!(5, source_size);
            // SAFETY: Test mock - reading source buffer to verify image data for load_image_from_source.
            let source = unsafe { slice::from_raw_parts(source_buffer as *mut u8, source_size) };
            assert_eq!(&[1_u8, 2, 3, 4, 5], source);
            efi::Status::SUCCESS
        }

        _ = boot_services.load_image_from_source(1_usize as _, 2_usize as _, &[1_u8, 2, 3, 4, 5])
    }

    #[test]
    fn test_load_image_from_file() {
        let boot_services = boot_services!(load_image = efi_load_image);

        extern "efiapi" fn efi_load_image(
            boot_policy: Boolean,
            parent_image_handler: *mut c_void,
            device_path: *mut device_path::Protocol,
            source_buffer: *mut c_void,
            source_size: usize,
            _image_handler: *mut *mut c_void,
        ) -> efi::Status {
            assert!(!bool::from(boot_policy));
            assert_eq!(1, parent_image_handler as usize);
            assert_eq!(2, device_path as usize);
            assert_eq!(ptr::null_mut(), source_buffer);
            assert_eq!(0, source_size);
            efi::Status::SUCCESS
        }

        _ = boot_services.load_image_from_file(1_usize as _, NonNull::new(2_usize as _).unwrap());
    }

    #[test]
    #[should_panic = "Boot services function start_image is not initialized."]
    fn test_start_image_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.start_image(ptr::null_mut());
    }

    #[test]
    fn test_start_image() {
        let boot_services = boot_services!(start_image = efi_start_image);

        extern "efiapi" fn efi_start_image(
            image_handle: efi::Handle,
            exit_data_size: *mut usize,
            exit_data: *mut *mut Char16,
        ) -> efi::Status {
            assert_eq!(1, image_handle as usize);
            assert_ne!(ptr::null_mut(), exit_data_size);
            assert_ne!(ptr::null_mut(), exit_data);
            efi::Status::SUCCESS
        }

        boot_services.start_image(1_usize as _).unwrap();
    }

    #[test]
    #[should_panic = "Boot services function unload_image is not initialized."]
    fn test_unload_image_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.unload_image(ptr::null_mut());
    }

    #[test]
    fn test_unload_image() {
        let boot_services = boot_services!(unload_image = efi_unload_image);

        extern "efiapi" fn efi_unload_image(image_handle: efi::Handle) -> efi::Status {
            assert_eq!(1, image_handle as usize);
            efi::Status::SUCCESS
        }

        _ = boot_services.unload_image(1_usize as _);
    }

    #[test]
    #[should_panic = "Boot services function exit is not initialized."]
    fn test_exit_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.exit(ptr::null_mut(), efi::Status::SUCCESS, None);
    }

    #[test]
    fn test_exit() {
        let boot_services = boot_services!(exit = efi_exit);

        extern "efiapi" fn efi_exit(
            image_handle: efi::Handle,
            exit_status: efi::Status,
            exit_data_size: usize,
            exit_data: *mut u16,
        ) -> efi::Status {
            assert_eq!(1, image_handle as usize);
            assert_eq!(efi::Status::SUCCESS, exit_status);
            assert_eq!(0, exit_data_size);
            assert_eq!(ptr::null_mut(), exit_data);
            efi::Status::SUCCESS
        }

        boot_services.exit(1_usize as _, efi::Status::SUCCESS, None).unwrap();
    }

    #[test]
    #[should_panic = "Boot services function exit_boot_services is not initialized."]
    fn test_exit_boot_services_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.exit_boot_services(ptr::null_mut(), 0);
    }

    #[test]
    fn test_exit_boot_services() {
        let boot_services = boot_services!(exit_boot_services = efi_exit_boot_services);

        extern "efiapi" fn efi_exit_boot_services(image_handle: efi::Handle, map_key: usize) -> efi::Status {
            assert_eq!(1, image_handle as usize);
            assert_eq!(2, map_key);
            efi::Status::SUCCESS
        }

        boot_services.exit_boot_services(1_usize as _, 2).unwrap();
    }

    #[test]
    fn test_get_memory_map() {
        let boot_services = boot_services!(
            get_memory_map = efi_get_memory_map,
            allocate_pool = efi_allocate_pool_use_box,
            free_pool = efi_free_pool_use_box
        );

        extern "efiapi" fn efi_get_memory_map(
            memory_map_size: *mut usize,
            memory_map: *mut efi::MemoryDescriptor,
            _map_key: *mut usize,
            descriptor_size: *mut usize,
            descriptor_version: *mut u32,
        ) -> efi::Status {
            if memory_map_size.is_null() {
                return efi::Status::INVALID_PARAMETER;
            }

            // SAFETY: Test mock - reading memory_map_size to check if buffer allocation is needed.
            let memory_map_size_value = unsafe { *memory_map_size };
            if memory_map_size_value == 0 {
                // SAFETY: Test mock - writing required buffer size to simulate a BUFFER_TOO_SMALL response.
                unsafe { ptr::write(memory_map_size, 0x400) };
                return efi::Status::BUFFER_TOO_SMALL;
            }

            // SAFETY: Test mock - writing memory map descriptor data to output parameters.
            unsafe {
                (*memory_map).physical_start = 0xffffffffaaaabbbb;
                *descriptor_size = mem::size_of::<efi::MemoryDescriptor>();
                *descriptor_version = 1;
            }
            efi::Status::SUCCESS
        }

        let status = boot_services.get_memory_map();

        match status {
            Ok(memory_map) => {
                assert_eq!(memory_map.map_key, 0);
                assert_eq!(memory_map.descriptor_version, 1);
                assert_eq!(memory_map.descriptors[0].physical_start, 0xffffffffaaaabbbb);
            }
            Err((status, _)) => {
                panic!("Error: {status:?}");
            }
        }
    }

    #[test]
    #[should_panic = "Boot services function set_watchdog_timer is not initialized."]
    fn test_set_watchdog_timer_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.set_watchdog_timer(0)
    }

    #[test]
    fn test_set_watchdog_timer() {
        let boot_services = boot_services!(set_watchdog_timer = efi_set_watchdog_timer);

        extern "efiapi" fn efi_set_watchdog_timer(
            timeout: usize,
            watchdog_code: u64,
            data_size: usize,
            watchdog_data: *mut u16,
        ) -> efi::Status {
            assert_eq!(10, timeout);
            assert_eq!(0, watchdog_code);
            assert_eq!(0, data_size);
            assert_eq!(ptr::null_mut(), watchdog_data);
            efi::Status::SUCCESS
        }

        boot_services.set_watchdog_timer(10).unwrap();
    }

    #[test]
    #[should_panic = "Boot services function stall is not initialized."]
    fn test_stall_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.stall(0);
    }

    #[test]
    fn test_stall() {
        let boot_services = boot_services!(stall = efi_stall);
        extern "efiapi" fn efi_stall(microsecondes: usize) -> efi::Status {
            assert_eq!(10, microsecondes);
            efi::Status::SUCCESS
        }
        let status = boot_services.stall(10);
        assert_eq!(Ok(()), status);
    }

    #[test]
    #[should_panic = "Boot services function copy_mem is not initialized."]
    fn test_copy_mem_not_init() {
        let boot_services = boot_services!();
        let mut dest = 0;
        let src = 0;
        boot_services.copy_mem(&mut dest, &src);
    }

    #[test]
    fn test_copy_mem() {
        let boot_services = boot_services!(copy_mem = efi_copy_mem);

        static A: [i32; 5] = [1, 2, 3, 4, 5];
        static mut B: [i32; 5] = [0; 5];

        extern "efiapi" fn efi_copy_mem(dest: *mut c_void, src: *mut c_void, length: usize) {
            assert_eq!(ptr::addr_of!(B) as usize, dest as usize);
            assert_eq!(ptr::addr_of!(A) as usize, src as usize);
            assert_eq!(5 * mem::size_of::<i32>(), length);
        }
        // SAFETY: Test code - B is a mutable static that we're taking a reference to for the test.
        boot_services.copy_mem(unsafe { &mut B }, &A);
    }

    #[test]
    #[should_panic = "Boot services function set_mem is not initialized."]
    fn test_set_mem_not_init() {
        let boot_services = boot_services!();
        boot_services.set_mem(&mut [0], 0);
    }

    #[test]
    fn test_set_mem() {
        let boot_services = boot_services!(set_mem = efi_set_mem);

        static mut BUFFER: [u8; 16] = [0; 16];

        extern "efiapi" fn efi_set_mem(buffer: *mut c_void, size: usize, value: u8) {
            assert_eq!(ptr::addr_of!(BUFFER) as usize, buffer as usize);
            assert_eq!(16, size);
            assert_eq!(8, value);
        }
        // SAFETY: Test code - BUFFER is a mutable static that we're taking a reference to for the test.
        boot_services.set_mem(unsafe { &mut BUFFER }, 8);
    }

    #[test]
    #[should_panic = "Boot services function get_next_monotonic_count is not initialized."]
    fn test_get_next_monotonic_count_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.get_next_monotonic_count();
    }

    #[test]
    fn test_get_next_monotonic_count() {
        let boot_services = boot_services!(get_next_monotonic_count = efi_get_next_monotonic_count);
        extern "efiapi" fn efi_get_next_monotonic_count(count: *mut u64) -> efi::Status {
            // SAFETY: Test code - writing a known value to the output parameter passed by the caller.
            unsafe { ptr::write(count, 89) };
            efi::Status::SUCCESS
        }
        let status = boot_services.get_next_monotonic_count().unwrap();
        assert_eq!(89, status);
    }

    #[test]
    #[should_panic = "Boot services function install_configuration_table is not initialized."]
    fn test_install_configuration_table_not_init() {
        let boot_services = boot_services!();
        let table = Box::new(());
        // SAFETY: Test code - intentionally testing that the function panics when not initialized.
        _ = unsafe { boot_services.install_configuration_table(&efi::Guid::from_bytes(&[0; 16]), table) };
    }

    #[test]
    fn test_install_configuration_table() {
        let boot_services = boot_services!(install_configuration_table = efi_install_configuration_table);

        static GUID: efi::Guid = efi::Guid::from_bytes(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
        static mut TABLE: i32 = 10;

        extern "efiapi" fn efi_install_configuration_table(guid: *mut efi::Guid, table: *mut c_void) -> efi::Status {
            assert_eq!(ptr::addr_of!(GUID) as usize, guid as usize);
            assert_eq!(ptr::addr_of!(TABLE) as usize, table as usize);
            // SAFETY: Test code - reading static data for assertion verification.
            assert_eq!(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], unsafe { ptr::read(guid) }.as_bytes());
            // SAFETY: Test code - reading static data for assertion verification.
            assert_eq!(10, unsafe { ptr::read(table as *mut i32) });
            efi::Status::SUCCESS
        }

        // SAFETY: Test code - TABLE is a mutable static that we're taking a reference to for the test.
        unsafe { boot_services.install_configuration_table(&GUID, &mut TABLE) }.unwrap();
    }

    #[test]
    #[should_panic = "Boot services function calculate_crc32 is not initialized."]
    fn test_calculate_crc32_not_init() {
        let boot_services = boot_services!();
        _ = boot_services.calculate_crc_32(&[0]);
    }

    #[test]
    fn test_calculate_crc32() {
        let boot_services = boot_services!(calculate_crc32 = efi_calculate_crc32);

        static BUFFER: [u8; 16] = [0; 16];

        extern "efiapi" fn efi_calculate_crc32(
            buffer_ptr: *mut c_void,
            buffer_size: usize,
            crc: *mut u32,
        ) -> efi::Status {
            // SAFETY: Test code - verifying and writing data for testing CRC calculation.
            unsafe {
                assert_eq!(ptr::addr_of!(BUFFER) as usize, buffer_ptr as usize);
                assert_eq!(BUFFER.len(), buffer_size);
                ptr::write(crc, 10)
            }
            efi::Status::SUCCESS
        }

        let crc = boot_services.calculate_crc_32(&BUFFER).unwrap();
        assert_eq!(10, crc);
    }

    #[test]
    fn test_debug_output_should_not_crash() {
        let boot_services = boot_services!();
        let debug_str = format!("{:?}", boot_services);
        assert!(!debug_str.is_empty());
        assert!(debug_str.contains("StandardBootServices"));
    }
}