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
//! DXE Core Driver Services
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!
use alloc::{
collections::{BTreeMap, BTreeSet},
vec::Vec,
};
use core::ptr::NonNull;
use patina::{
device_path::walker::{concat_device_path_to_boxed_slice, copy_device_path_to_boxed_slice},
error::EfiError,
performance::{
logging::{
perf_driver_binding_start_begin, perf_driver_binding_start_end, perf_driver_binding_support_begin,
perf_driver_binding_support_end,
},
measurement::create_performance_measurement,
},
};
use r_efi::efi;
use crate::{protocols::PROTOCOL_DB, systemtables::EfiSystemTable};
fn get_bindings_for_handles(handles: Vec<efi::Handle>) -> Vec<*mut efi::protocols::driver_binding::Protocol> {
handles
.iter()
.filter_map(|x| {
match PROTOCOL_DB.get_interface_for_handle(*x, efi::protocols::driver_binding::PROTOCOL_GUID) {
Ok(interface) => Some(interface as *mut efi::protocols::driver_binding::Protocol),
Err(_) => None, //ignore handles without driver bindings
}
})
.collect()
}
fn get_platform_driver_override_bindings(
controller_handle: efi::Handle,
) -> Vec<*mut efi::protocols::driver_binding::Protocol> {
let driver_override_protocol = match PROTOCOL_DB
.locate_protocol(efi::protocols::platform_driver_override::PROTOCOL_GUID)
{
Err(_) => return Vec::new(),
Ok(protocol) => unsafe {
// SAFETY: locate_protocol guarantees that if `Ok` is returned, a valid pointer is encapsulated in it.
(protocol as *mut efi::protocols::platform_driver_override::Protocol).as_mut().expect("bad protocol ptr")
},
};
let mut driver_overrides = Vec::new();
let mut driver_image_handle: efi::Handle = core::ptr::null_mut();
loop {
let status = (driver_override_protocol.get_driver)(
driver_override_protocol,
controller_handle,
core::ptr::addr_of_mut!(driver_image_handle),
);
if status != efi::Status::SUCCESS {
break;
}
driver_overrides.push(driver_image_handle);
}
get_bindings_for_handles(driver_overrides)
}
fn get_family_override_bindings() -> Vec<*mut efi::protocols::driver_binding::Protocol> {
let driver_binding_handles = match PROTOCOL_DB.locate_handles(Some(efi::protocols::driver_binding::PROTOCOL_GUID)) {
Err(_) => return Vec::new(),
Ok(handles) => handles,
};
let mut driver_override_map: BTreeMap<u32, efi::Handle> = BTreeMap::new();
// insert all the handles that have DRIVER_FAMILY_OVERRIDE_PROTOCOL on them into a sorted map
for handle in driver_binding_handles {
match PROTOCOL_DB.get_interface_for_handle(handle, efi::protocols::driver_family_override::PROTOCOL_GUID) {
Ok(protocol) => {
// SAFETY: get_interface_for_handle guarantees that if `Ok` is returned, a valid pointer is encapsulated in it.
let driver_override_protocol = unsafe {
(protocol as *mut efi::protocols::driver_family_override::Protocol)
.as_mut()
.expect("bad protocol ptr")
};
let version = (driver_override_protocol.get_version)(driver_override_protocol);
driver_override_map.insert(version, handle);
}
Err(_) => continue,
}
}
//return the driver bindings for the values from the map in reverse order (highest versions first)
get_bindings_for_handles(driver_override_map.into_values().rev().collect())
}
fn get_bus_specific_override_bindings(
controller_handle: efi::Handle,
) -> Vec<*mut efi::protocols::driver_binding::Protocol> {
let bus_specific_override_protocol = match PROTOCOL_DB
.get_interface_for_handle(controller_handle, efi::protocols::bus_specific_driver_override::PROTOCOL_GUID)
{
Err(_) => return Vec::new(),
// SAFETY: get_interface_for_handle guarantees that if `Ok` is returned, a valid pointer is encapsulated in it.
Ok(protocol) => unsafe {
(protocol as *mut efi::protocols::bus_specific_driver_override::Protocol)
.as_mut()
.expect("bad protocol ptr")
},
};
let mut bus_overrides = Vec::new();
let mut driver_image_handle: efi::Handle = core::ptr::null_mut();
loop {
let status = (bus_specific_override_protocol.get_driver)(
bus_specific_override_protocol,
core::ptr::addr_of_mut!(driver_image_handle),
);
if status != efi::Status::SUCCESS {
break;
}
bus_overrides.push(driver_image_handle);
}
get_bindings_for_handles(bus_overrides)
}
fn get_all_driver_bindings() -> Vec<*mut efi::protocols::driver_binding::Protocol> {
let mut driver_bindings = match PROTOCOL_DB.locate_handles(Some(efi::protocols::driver_binding::PROTOCOL_GUID)) {
Err(_) => return Vec::new(),
Ok(handles) if handles.is_empty() => return Vec::new(),
Ok(handles) => get_bindings_for_handles(handles),
};
// SAFETY: driver_bindings must contain valid pointers/handles (a & b as well as *a & *b)
// when sort_unstable_by() is called. If .locate_handles() returns 'Ok' and handles is
// not empty, we rely on get_bindings_for_handles to return a valid Vec.
driver_bindings.sort_unstable_by(|a, b| unsafe { (*(*b)).version.cmp(&(*(*a)).version) });
driver_bindings
}
// authenticate a connect call through the security2 arch protocol
fn authenticate_connect(
controller_handle: efi::Handle,
remaining_device_path: Option<*mut efi::protocols::device_path::Protocol>,
recursive: bool,
) -> Result<(), EfiError> {
if let Ok(device_path) =
PROTOCOL_DB.get_interface_for_handle(controller_handle, efi::protocols::device_path::PROTOCOL_GUID)
{
let device_path = device_path as *mut efi::protocols::device_path::Protocol;
if let Ok(security2_ptr) = PROTOCOL_DB.locate_protocol(patina::pi::protocols::security2::PROTOCOL_GUID) {
let file_path = {
if !recursive {
if let Some(remaining_path) = remaining_device_path {
concat_device_path_to_boxed_slice(device_path, remaining_path)
} else {
copy_device_path_to_boxed_slice(device_path)
}
} else {
copy_device_path_to_boxed_slice(device_path)
}
};
if let Ok(mut file_path) = file_path {
// SAFETY: Pointer is validated using .expect(), will panic if .as_ref() returns a NULL pointer
let security2 = unsafe {
(security2_ptr as *mut patina::pi::protocols::security2::Protocol)
.as_ref()
.expect("security2 should not be null")
};
let security_status = (security2.file_authentication)(
security2_ptr as *mut _,
file_path.as_mut_ptr() as *mut _,
core::ptr::null_mut(),
0,
false,
);
EfiError::status_to_result(security_status)?;
}
}
}
//if there is no device path on the controller handle,
//or if there is no security2 protocol instance,
//or any of the device paths are malformed,
//then above will fall through to here, and no authentication is performed.
Ok(())
}
fn core_connect_single_controller(
controller_handle: efi::Handle,
driver_handles: Vec<efi::Handle>,
remaining_device_path: Option<*mut efi::protocols::device_path::Protocol>,
) -> Result<(), EfiError> {
PROTOCOL_DB.validate_handle(controller_handle)?;
//The following sources for driver instances are considered per UEFI Spec 2.10 section 7.3.12:
//1. Context Override
let mut driver_candidates = Vec::new();
driver_candidates.extend(get_bindings_for_handles(driver_handles));
//2. Platform Driver Override
let mut platform_override_drivers = get_platform_driver_override_bindings(controller_handle);
platform_override_drivers.retain(|x| !driver_candidates.contains(x));
driver_candidates.append(&mut platform_override_drivers);
//3. Driver Family Override Search
let mut family_override_drivers = get_family_override_bindings();
family_override_drivers.retain(|x| !driver_candidates.contains(x));
driver_candidates.append(&mut family_override_drivers);
//4. Bus Specific Driver Override
let mut bus_override_drivers = get_bus_specific_override_bindings(controller_handle);
bus_override_drivers.retain(|x| !driver_candidates.contains(x));
driver_candidates.append(&mut bus_override_drivers);
//5. Driver Binding Search
let mut driver_bindings = get_all_driver_bindings();
driver_bindings.retain(|x| !driver_candidates.contains(x));
driver_candidates.append(&mut driver_bindings);
//loop until no more drivers can be started on handle.
let mut one_started = false;
loop {
let mut started_drivers = Vec::new();
for driver_binding_interface in driver_candidates.clone() {
// SAFETY: driver_binding_interface is a clone of driver_candidates which is created above.
// The pointer should be valid as long as driver_candidates is successfully allocated.
let driver_binding = unsafe { &mut *(driver_binding_interface) };
let device_path = remaining_device_path.or(Some(core::ptr::null_mut())).expect("must be some");
perf_driver_binding_support_begin(
driver_binding.driver_binding_handle,
controller_handle,
create_performance_measurement,
);
//driver claims support; attempt to start it.
match (driver_binding.supported)(driver_binding_interface, controller_handle, device_path) {
efi::Status::SUCCESS => {
perf_driver_binding_support_end(
driver_binding.driver_binding_handle,
controller_handle,
create_performance_measurement,
);
started_drivers.push(driver_binding_interface);
perf_driver_binding_start_begin(
driver_binding.driver_binding_handle,
controller_handle,
create_performance_measurement,
);
if (driver_binding.start)(driver_binding_interface, controller_handle, device_path)
== efi::Status::SUCCESS
{
one_started = true;
}
perf_driver_binding_start_end(
driver_binding.driver_binding_handle,
controller_handle,
create_performance_measurement,
);
}
_ => {
perf_driver_binding_support_end(
driver_binding.driver_binding_handle,
controller_handle,
create_performance_measurement,
);
continue;
}
}
}
if started_drivers.is_empty() {
break;
}
driver_candidates.retain(|x| !started_drivers.contains(x));
}
if one_started {
return Ok(());
}
// SAFETY: caller must ensure that the pointer contained in remaining_device_path is valid if it is Some(_).
if let Some(device_path) = remaining_device_path
&& unsafe { (device_path.read_unaligned()).r#type == efi::protocols::device_path::TYPE_END }
{
return Ok(());
}
Err(EfiError::NotFound)
}
/// Connects a controller to drivers
///
/// This function matches the behavior of EFI_BOOT_SERVICES.ConnectController() API in the UEFI spec 2.10 section
/// 7.3.12. Refer to the UEFI spec description for details on input parameters, behavior, and error return codes.
///
/// # Safety
/// This routine cannot hold the protocol db lock while executing DriverBinding->Supported()/Start() since
/// they need to access protocol db services. That means this routine can't guarantee that driver bindings remain
/// valid for the duration of its execution. For example, if a driver were be unloaded in a timer callback after
/// returning true from Supported() before Start() is called, then the driver binding instance would be uninstalled or
/// invalid and Start() would be an invalid function pointer when invoked. In general, the spec implicitly assumes
/// that driver binding instances that are valid at the start of he call to ConnectController() must remain valid for
/// the duration of the ConnectController() call. If this is not true, then behavior is undefined. This function is
/// marked unsafe for this reason.
///
/// ## Example
///
/// ```ignore
/// let result = core_connect_controller(controller_handle, Vec::new(), None, false);
/// ```
///
pub unsafe fn core_connect_controller(
handle: efi::Handle,
driver_handles: Vec<efi::Handle>,
remaining_device_path: Option<*mut efi::protocols::device_path::Protocol>,
recursive: bool,
) -> Result<(), EfiError> {
authenticate_connect(handle, remaining_device_path, recursive)?;
let return_status = core_connect_single_controller(handle, driver_handles, remaining_device_path);
if recursive {
for child in PROTOCOL_DB.get_child_handles(handle) {
// ignore the return value to match behavior of edk2 reference.
// SAFETY: We do not remove any of these handles during this call, though it is
// possible for a different entity at another TPL to do so.
_ = unsafe { core_connect_controller(child, Vec::new(), None, true) };
}
}
return_status
}
extern "efiapi" fn connect_controller(
handle: efi::Handle,
driver_image_handle: *mut efi::Handle,
remaining_device_path: *mut efi::protocols::device_path::Protocol,
recursive: efi::Boolean,
) -> efi::Status {
let driver_handles = if driver_image_handle.is_null() {
Vec::new()
} else {
let mut current_ptr = driver_image_handle;
let mut handles: Vec<efi::Handle> = Vec::new();
loop {
// SAFETY: caller must ensure that driver_image_handle is a valid pointer to a null-terminated list of
// handles if it is not null.
let current_val = unsafe { current_ptr.read_unaligned() };
if current_val.is_null() {
break;
}
handles.push(current_val);
// SAFETY: caller guarantees a null-terminated list, so safe to advance to the next pointer as the null-terminator
// has just been checked above.
current_ptr = unsafe { current_ptr.add(1) };
}
handles
};
// remaining_device_path is passed in and may not have proper alignment.
let device_path = if remaining_device_path.is_null() { None } else { Some(remaining_device_path) };
// SAFETY: caller must ensure that device_path is a valid pointer to a device path structure if it is not null.
unsafe {
match core_connect_controller(handle, driver_handles, device_path, recursive.into()) {
Err(err) => err.into(),
_ => efi::Status::SUCCESS,
}
}
}
/// Disconnects drivers from a controller.
///
/// This function matches the behavior of EFI_BOOT_SERVICES.DisconnectController() API in the UEFI spec 2.10 section
/// 7.3.13. Refer to the UEFI spec description for details on input parameters, behavior, and error return codes.
///
/// # Safety
/// This routine cannot hold the protocol db lock while executing DriverBinding->Supported()/Start() since
/// they need to access protocol db services. That means this routine can't guarantee that driver bindings remain
/// valid for the duration of its execution. For example, if a driver were be unloaded in a timer callback after
/// returning true from Supported() before Start() is called, then the driver binding instance would be uninstalled or
/// invalid and Start() would be an invalid function pointer when invoked. In general, the spec implicitly assumes
/// that driver binding instances that are valid at the start of he call to ConnectController() must remain valid for
/// the duration of the ConnectController() call. If this is not true, then behavior is undefined. This function is
/// marked unsafe for this reason.
///
/// ## Example
///
/// ```ignore
/// let result = core_disconnect_controller(controller_handle, None, None);
/// ```
///
pub unsafe fn core_disconnect_controller(
controller_handle: efi::Handle,
driver_image_handle: Option<efi::Handle>,
child_handle: Option<efi::Handle>,
) -> Result<(), EfiError> {
PROTOCOL_DB.validate_handle(controller_handle)?;
if let Some(handle) = driver_image_handle {
PROTOCOL_DB.validate_handle(handle)?;
}
if let Some(handle) = child_handle {
PROTOCOL_DB.validate_handle(handle)?;
}
// determine which driver_handles should be stopped.
let mut drivers_managing_controller = {
match PROTOCOL_DB.get_open_protocol_information(controller_handle) {
Ok(info) => info
.iter()
.flat_map(|(_guid, open_info)| {
open_info.iter().filter_map(|x| {
if (x.attributes & efi::OPEN_PROTOCOL_BY_DRIVER) != 0 {
Some(x.agent_handle.expect("BY_DRIVER usage must have an agent handle"))
} else {
None
}
})
})
.collect(),
Err(_) => Vec::new(),
}
};
// remove duplicates but preserve ordering.
let mut driver_set = BTreeSet::new();
drivers_managing_controller.retain(|x| driver_set.insert(*x));
// if the driver image was specified, only disconnect that one (if it is actually managing it)
if let Some(driver) = driver_image_handle {
drivers_managing_controller.retain(|x| *x == driver);
}
let mut one_or_more_drivers_disconnected = false;
let no_drivers = drivers_managing_controller.is_empty();
for driver_handle in drivers_managing_controller {
let controller_info = match PROTOCOL_DB.get_open_protocol_information(controller_handle) {
Ok(info) => info,
Err(_) => continue,
};
// Determine whether this driver still has the controller open by driver, and what child handles it has open (if
// any).
let mut driver_valid = false;
let mut child_handles = Vec::new();
for (_guid, open_info) in controller_info.iter() {
for info in open_info.iter() {
if info.agent_handle == Some(driver_handle) {
if (info.attributes & efi::OPEN_PROTOCOL_BY_DRIVER) != 0 {
driver_valid = true;
}
if (info.attributes & efi::OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0
&& let Some(handle) = info.controller_handle
{
child_handles.push(handle);
}
}
}
}
// This driver no longer has the controller open by driver (may have been closed a side-effect of processing a
// previous driver in the list), so nothing to do.
if !driver_valid {
continue;
}
// remove duplicates but preserve ordering.
let mut child_set = BTreeSet::new();
child_handles.retain(|x| child_set.insert(*x));
let total_children = child_handles.len();
let mut is_only_child = false;
if let Some(handle) = child_handle {
//if the child was specified, but was the only child, then the driver should be disconnected.
//if the child was specified, but other children were present, then the driver should not be disconnected.
child_handles.retain(|x| x == &handle);
is_only_child = total_children == child_handles.len();
}
//resolve the handle to the driver_binding.
//N.B. Corner case: a driver could install a driver-binding instance; then be asked to manage a controller (and
//thus, become an agent_handle in the open protocol information), and then something uninstalls the driver binding
//from the agent_handle. This would mean that the agent_handle now no longer supports the driver binding but is
//marked in the protocol database as managing the controller. This code just returns INVALID_PARAMETER in this case
//(which effectively makes the controller "un-disconnect-able" since all subsequent disconnects will also fail for
//the same reason). This matches the reference C implementation. As an enhancement, the core could track driver
//bindings that are actively managing controllers and return an ACCESS_DENIED status if something attempts to
//uninstall a binding that is in use.
let driver_binding_interface = PROTOCOL_DB
.get_interface_for_handle(driver_handle, efi::protocols::driver_binding::PROTOCOL_GUID)
.or(Err(EfiError::InvalidParameter))?;
let driver_binding_interface = driver_binding_interface as *mut efi::protocols::driver_binding::Protocol;
// SAFETY: driver_binding_interface is validated above, would have been caught with the .or and ? above with
// the loop being terminated.
let driver_binding = unsafe { &mut *(driver_binding_interface) };
let mut status = efi::Status::SUCCESS;
if !child_handles.is_empty() {
//disconnect the child controller(s).
status = (driver_binding.stop)(
driver_binding_interface,
controller_handle,
child_handles.len(),
child_handles.as_mut_ptr(),
);
}
if status == efi::Status::SUCCESS && (child_handle.is_none() || is_only_child) {
status = (driver_binding.stop)(driver_binding_interface, controller_handle, 0, core::ptr::null_mut());
}
if status == efi::Status::SUCCESS {
one_or_more_drivers_disconnected = true;
}
}
if one_or_more_drivers_disconnected || no_drivers { Ok(()) } else { Err(EfiError::NotFound) }
}
extern "efiapi" fn disconnect_controller(
controller_handle: efi::Handle,
driver_image_handle: efi::Handle,
child_handle: efi::Handle,
) -> efi::Status {
if controller_handle.is_null() {
return efi::Status::INVALID_PARAMETER;
}
let driver_image_handle = NonNull::new(driver_image_handle).map(|x| x.as_ptr());
let child_handle = NonNull::new(child_handle).map(|x| x.as_ptr());
// SAFETY: Caller must ensure controller_handle is valid for the duration of the call.
// driver_image_handle and child_handle are both created above using NonNull which should
// guarantee they are non-null pointers. controller_handle is validated above. We do not
// remove any of these handles during this call, though it is possible for a different
// entity at another TPL to do so.
unsafe {
match core_disconnect_controller(controller_handle, driver_image_handle, child_handle) {
Err(err) => err.into(),
_ => efi::Status::SUCCESS,
}
}
}
pub fn init_driver_services(st: &mut EfiSystemTable) {
let mut bs = st.boot_services().get();
bs.connect_controller = connect_controller;
bs.disconnect_controller = disconnect_controller;
st.boot_services().set(bs);
}
#[cfg(test)]
#[coverage(off)]
mod tests {
use super::*;
use crate::{protocol_db::DXE_CORE_HANDLE, test_support};
use core::ffi::c_void;
use std::{
str::FromStr,
sync::atomic::{AtomicUsize, Ordering},
};
use uuid::Uuid;
// =================== TEST HELPER STATICS ===================
static SUPPORTED_CALL_COUNT: AtomicUsize = AtomicUsize::new(0);
static START_CALL_COUNT: AtomicUsize = AtomicUsize::new(0);
// =================== TEST HELPERS ===================
fn with_locked_state<F: Fn() + std::panic::RefUnwindSafe>(f: F) {
test_support::with_global_lock(|| {
test_support::init_test_logger();
// SAFETY: init_test_protocol_db modifies global state. It is being called within a
// lock to have exclusive mutable access to the protocol database.
unsafe {
test_support::init_test_protocol_db();
}
f();
})
.unwrap();
}
// =================== MOCK DRIVER BINDING FUNCTIONS ===================
// Supported functions
extern "efiapi" fn mock_supported_success(
_this: *mut efi::protocols::driver_binding::Protocol,
_controller_handle: efi::Handle,
_remaining_device_path: *mut efi::protocols::device_path::Protocol,
) -> efi::Status {
efi::Status::SUCCESS
}
extern "efiapi" fn mock_supported_failure(
_this: *mut efi::protocols::driver_binding::Protocol,
_controller_handle: efi::Handle,
_remaining_device_path: *mut efi::protocols::device_path::Protocol,
) -> efi::Status {
efi::Status::UNSUPPORTED
}
extern "efiapi" fn mock_supported_with_counter(
_this: *mut efi::protocols::driver_binding::Protocol,
_controller_handle: efi::Handle,
_remaining_device_path: *mut efi::protocols::device_path::Protocol,
) -> efi::Status {
SUPPORTED_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
efi::Status::SUCCESS
}
// Start functions
extern "efiapi" fn mock_start_success(
_this: *mut efi::protocols::driver_binding::Protocol,
_controller_handle: efi::Handle,
_remaining_device_path: *mut efi::protocols::device_path::Protocol,
) -> efi::Status {
efi::Status::SUCCESS
}
extern "efiapi" fn mock_start_failure(
_this: *mut efi::protocols::driver_binding::Protocol,
_controller_handle: efi::Handle,
_remaining_device_path: *mut efi::protocols::device_path::Protocol,
) -> efi::Status {
efi::Status::DEVICE_ERROR
}
extern "efiapi" fn mock_start_with_counter(
_this: *mut efi::protocols::driver_binding::Protocol,
_controller_handle: efi::Handle,
_remaining_device_path: *mut efi::protocols::device_path::Protocol,
) -> efi::Status {
START_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
efi::Status::SUCCESS
}
// Stop functions
extern "efiapi" fn mock_stop_success(
_this: *mut efi::protocols::driver_binding::Protocol,
_controller_handle: efi::Handle,
_num_children: usize,
_child_handle_buffer: *mut efi::Handle,
) -> efi::Status {
efi::Status::SUCCESS
}
// =================== MOCK PROTOCOL VERSION FUNCTIONS ===================
extern "efiapi" fn mock_get_version_100(_this: *mut efi::protocols::driver_family_override::Protocol) -> u32 {
100
}
extern "efiapi" fn mock_get_version_200(_this: *mut efi::protocols::driver_family_override::Protocol) -> u32 {
200
}
// =================== HELPER FUNCTIONS ===================
fn create_driver_binding(
version: u32,
handle: efi::Handle,
supported_fn: extern "efiapi" fn(
*mut efi::protocols::driver_binding::Protocol,
efi::Handle,
*mut efi::protocols::device_path::Protocol,
) -> efi::Status,
start_fn: extern "efiapi" fn(
*mut efi::protocols::driver_binding::Protocol,
efi::Handle,
*mut efi::protocols::device_path::Protocol,
) -> efi::Status,
stop_fn: extern "efiapi" fn(
*mut efi::protocols::driver_binding::Protocol,
efi::Handle,
usize,
*mut efi::Handle,
) -> efi::Status,
) -> Box<efi::protocols::driver_binding::Protocol> {
// Create a unique image handle by installing a protocol with arbitrary GUID
// This is safer than arithmetic that could overflow
let test_uuid = Uuid::from_str("12345678-1234-5678-9abc-def012345678").unwrap();
let test_guid = efi::Guid::from_bytes(test_uuid.as_bytes());
let image_handle = match PROTOCOL_DB.install_protocol_interface(
None,
test_guid,
core::ptr::null_mut(), // Dummy protocol data for test
) {
Ok((handle, _)) => handle,
Err(_) => DXE_CORE_HANDLE, // Fallback to DXE_CORE_HANDLE
};
Box::new(efi::protocols::driver_binding::Protocol {
version,
supported: supported_fn,
start: start_fn,
stop: stop_fn,
driver_binding_handle: handle,
image_handle,
})
}
fn create_default_driver_binding(
version: u32,
handle: efi::Handle,
) -> Box<efi::protocols::driver_binding::Protocol> {
create_driver_binding(version, handle, mock_supported_success, mock_start_success, mock_stop_success)
}
fn create_end_device_path() -> efi::protocols::device_path::Protocol {
efi::protocols::device_path::Protocol {
r#type: efi::protocols::device_path::TYPE_END,
sub_type: efi::protocols::device_path::End::SUBTYPE_ENTIRE,
length: [4, 0],
}
}
fn create_vendor_defined_device_path(_vendor_data: u32) -> efi::protocols::device_path::Protocol {
efi::protocols::device_path::Protocol {
r#type: efi::protocols::device_path::TYPE_HARDWARE,
sub_type: efi::protocols::device_path::Hardware::SUBTYPE_VENDOR,
length: [20, 0],
}
}
// =================== TESTS ===================
#[test]
fn test_get_bindings_for_handles_empty() {
with_locked_state(|| {
let handles = vec![0x1 as efi::Handle, 0x2 as efi::Handle];
let bindings = get_bindings_for_handles(handles);
assert_eq!(bindings.len(), 0);
});
}
#[test]
fn test_get_bindings_for_handles_with_results() {
with_locked_state(|| {
// Create binding protocols
let binding1 = create_default_driver_binding(10, 0x10 as efi::Handle);
let binding1_ptr = Box::into_raw(binding1) as *mut core::ffi::c_void;
let binding2 = create_default_driver_binding(20, 0x20 as efi::Handle);
let binding2_ptr = Box::into_raw(binding2) as *mut core::ffi::c_void;
// Create handles and install protocols
PROTOCOL_DB
.install_protocol_interface(
Some(0x1 as efi::Handle),
efi::protocols::device_path::PROTOCOL_GUID,
0x1111 as *mut core::ffi::c_void,
)
.unwrap();
PROTOCOL_DB
.install_protocol_interface(
Some(0x2 as efi::Handle),
efi::protocols::device_path::PROTOCOL_GUID,
0x2222 as *mut core::ffi::c_void,
)
.unwrap();
// Install driver binding protocols on the handles
PROTOCOL_DB
.install_protocol_interface(
Some(0x1 as efi::Handle),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding1_ptr,
)
.unwrap();
PROTOCOL_DB
.install_protocol_interface(
Some(0x2 as efi::Handle),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding2_ptr,
)
.unwrap();
// Test the function
let handles = vec![0x1 as efi::Handle, 0x2 as efi::Handle];
let bindings = get_bindings_for_handles(handles);
assert_eq!(bindings.len(), 2);
// Verify the binding versions
// SAFETY: The length of bindings is being verified above. This should guarantee
// bindings contains at least two valid elements which are checked below.
unsafe {
assert_eq!((*bindings[0]).version, 10);
assert_eq!((*bindings[1]).version, 20);
}
});
}
#[test]
fn test_get_platform_driver_override_bindings_no_drivers() {
with_locked_state(|| {
use std::sync::atomic::{AtomicUsize, Ordering};
static CALL_COUNT: AtomicUsize = AtomicUsize::new(0);
// Mock platform driver override protocol that returns no drivers
#[repr(C)]
struct MockPlatformDriverOverrideProtocol {
get_driver: fn(
this: *mut u8,
controller_handle: efi::Handle,
driver_image_handle: *mut efi::Handle,
) -> efi::Status,
}
let platform_override = Box::new(MockPlatformDriverOverrideProtocol {
get_driver: |_this, _controller_handle, _driver_image_handle| {
CALL_COUNT.fetch_add(1, Ordering::SeqCst);
// Always return failure - no override drivers
efi::Status::NOT_FOUND
},
});
let platform_override_ptr = Box::into_raw(platform_override) as *mut core::ffi::c_void;
// Install the platform driver override protocol
let (_, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::platform_driver_override::PROTOCOL_GUID,
platform_override_ptr,
)
.unwrap();
// Create controller handle
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x2000 as *mut core::ffi::c_void,
)
.unwrap();
// Reset call counter
CALL_COUNT.store(0, Ordering::SeqCst);
// Test the function
let bindings = get_platform_driver_override_bindings(controller_handle);
// Verify results
assert_eq!(CALL_COUNT.load(Ordering::SeqCst), 1, "Should call get_driver once and break on failure");
assert_eq!(bindings.len(), 0, "Should return empty vector when no drivers available");
});
}
#[test]
fn test_authenticate_connect_no_device_path() {
with_locked_state(|| {
// Create a controller handle without a device path protocol
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::simple_text_output::PROTOCOL_GUID, // Any protocol except device_path
0x1111 as *mut core::ffi::c_void,
)
.unwrap();
// Call authenticate_connect - should succeed gracefully since no device path exists
let result = authenticate_connect(controller_handle, None, false);
assert!(result.is_ok(), "authenticate_connect should succeed when no device path is present");
});
}
#[test]
fn test_authenticate_connect_with_security2_protocol() {
with_locked_state(|| {
use std::sync::atomic::{AtomicBool, Ordering};
// Track whether security2 was called
static SECURITY2_CALLED: AtomicBool = AtomicBool::new(false);
// Mock file_authentication function with proper UEFI calling convention
extern "efiapi" fn mock_file_authentication(
_this: *mut u8,
_device_path: *mut u8,
_file_buffer: *mut u8,
_file_size: usize,
_boot_policy: bool,
) -> efi::Status {
SECURITY2_CALLED.store(true, Ordering::SeqCst);
efi::Status::SUCCESS
}
// Create a mock Security2 protocol that uses the extern function
#[repr(C)]
struct MockSecurity2Protocol {
file_authentication: extern "efiapi" fn(
this: *mut u8,
device_path: *mut u8,
file_buffer: *mut u8,
file_size: usize,
boot_policy: bool,
) -> efi::Status,
}
let security2 = Box::new(MockSecurity2Protocol { file_authentication: mock_file_authentication });
let security2_ptr = Box::into_raw(security2) as *mut core::ffi::c_void;
// Install the security2 protocol in the protocol database
let (_, _) = PROTOCOL_DB
.install_protocol_interface(None, patina::pi::protocols::security2::PROTOCOL_GUID, security2_ptr)
.unwrap();
// Create a proper END device path that should be safe to process
let device_path = Box::new(efi::protocols::device_path::Protocol {
r#type: efi::protocols::device_path::TYPE_END,
sub_type: efi::protocols::device_path::End::SUBTYPE_ENTIRE,
length: [4, 0],
});
let device_path_ptr = Box::into_raw(device_path) as *mut core::ffi::c_void;
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(None, efi::protocols::device_path::PROTOCOL_GUID, device_path_ptr)
.unwrap();
// Reset the flag
SECURITY2_CALLED.store(false, Ordering::SeqCst);
// Call authenticate_connect
let result = authenticate_connect(controller_handle, None, false);
assert!(result.is_ok(), "authenticate_connect should succeed");
// Verify that security2.file_authentication was actually called
assert!(SECURITY2_CALLED.load(Ordering::SeqCst), "security2.file_authentication should have been called");
});
}
#[test]
fn test_get_family_override_bindings() {
with_locked_state(|| {
// Create driver binding protocols
let binding1 = create_default_driver_binding(10, 0x10 as efi::Handle);
let binding1_ptr = Box::into_raw(binding1) as *mut core::ffi::c_void;
let binding2 = create_default_driver_binding(20, 0x20 as efi::Handle);
let binding2_ptr = Box::into_raw(binding2) as *mut core::ffi::c_void;
let binding3 = create_default_driver_binding(30, 0x30 as efi::Handle);
let binding3_ptr = Box::into_raw(binding3) as *mut core::ffi::c_void;
// Create handle objects and install driver binding protocols
let handle1 = 0x1 as efi::Handle;
let handle2 = 0x2 as efi::Handle;
let handle3 = 0x3 as efi::Handle;
PROTOCOL_DB
.install_protocol_interface(Some(handle1), efi::protocols::driver_binding::PROTOCOL_GUID, binding1_ptr)
.unwrap();
PROTOCOL_DB
.install_protocol_interface(Some(handle2), efi::protocols::driver_binding::PROTOCOL_GUID, binding2_ptr)
.unwrap();
PROTOCOL_DB
.install_protocol_interface(Some(handle3), efi::protocols::driver_binding::PROTOCOL_GUID, binding3_ptr)
.unwrap();
// Create family override protocols with different versions
let family_override1 =
Box::new(efi::protocols::driver_family_override::Protocol { get_version: mock_get_version_100 });
let family_override1_ptr = Box::into_raw(family_override1) as *mut core::ffi::c_void;
let family_override2 =
Box::new(efi::protocols::driver_family_override::Protocol { get_version: mock_get_version_200 });
let family_override2_ptr = Box::into_raw(family_override2) as *mut core::ffi::c_void;
// Only install family override protocol on handles 1 and 2
PROTOCOL_DB
.install_protocol_interface(
Some(handle1),
efi::protocols::driver_family_override::PROTOCOL_GUID,
family_override1_ptr,
)
.unwrap();
PROTOCOL_DB
.install_protocol_interface(
Some(handle2),
efi::protocols::driver_family_override::PROTOCOL_GUID,
family_override2_ptr,
)
.unwrap();
// Test the function
let bindings = get_family_override_bindings();
// Should return 2 bindings sorted by family override version (highest first)
assert_eq!(bindings.len(), 2);
// First binding should be from handle2 (version 200)
// Second binding should be from handle1 (version 100)
// SAFETY: The length of bindings is being verified above. This should guarantee
// bindings contains at least two valid elements which are checked below.
unsafe {
assert_eq!((*bindings[0]).version, 20); // handle2's binding version
assert_eq!((*bindings[1]).version, 10); // handle1's binding version
}
// Handle3 should not be included as it doesn't have the family override protocol
});
}
#[test]
fn test_get_all_driver_bindings() {
with_locked_state(|| {
// Create driver binding protocols with different versions
let binding1 = create_default_driver_binding(10, 0x10 as efi::Handle);
let binding1_ptr = Box::into_raw(binding1) as *mut core::ffi::c_void;
let binding2 = create_default_driver_binding(30, 0x20 as efi::Handle);
let binding2_ptr = Box::into_raw(binding2) as *mut core::ffi::c_void;
let binding3 = create_default_driver_binding(20, 0x30 as efi::Handle);
let binding3_ptr = Box::into_raw(binding3) as *mut core::ffi::c_void;
// Create handle objects
let handle1 = 0x1 as efi::Handle;
let handle2 = 0x2 as efi::Handle;
let handle3 = 0x3 as efi::Handle;
// Install driver binding protocols on the handles
PROTOCOL_DB
.install_protocol_interface(Some(handle1), efi::protocols::driver_binding::PROTOCOL_GUID, binding1_ptr)
.unwrap();
PROTOCOL_DB
.install_protocol_interface(Some(handle2), efi::protocols::driver_binding::PROTOCOL_GUID, binding2_ptr)
.unwrap();
PROTOCOL_DB
.install_protocol_interface(Some(handle3), efi::protocols::driver_binding::PROTOCOL_GUID, binding3_ptr)
.unwrap();
// Call the function we're testing
let bindings = get_all_driver_bindings();
// Should return all 3 bindings sorted by version (highest first)
assert_eq!(bindings.len(), 3);
// Verify the correct order by version (descending)
// SAFETY: The length of bindings is being verified above. This should guarantee
// bindings contains at least three valid elements which are checked below.
unsafe {
assert_eq!((*bindings[0]).version, 30); // handle2's binding - highest version
assert_eq!((*bindings[1]).version, 20); // handle3's binding - middle version
assert_eq!((*bindings[2]).version, 10); // handle1's binding - lowest version
}
// Test with no driver bindings installed
// First, uninstall all the protocols
PROTOCOL_DB
.uninstall_protocol_interface(handle1, efi::protocols::driver_binding::PROTOCOL_GUID, binding1_ptr)
.unwrap();
PROTOCOL_DB
.uninstall_protocol_interface(handle2, efi::protocols::driver_binding::PROTOCOL_GUID, binding2_ptr)
.unwrap();
PROTOCOL_DB
.uninstall_protocol_interface(handle3, efi::protocols::driver_binding::PROTOCOL_GUID, binding3_ptr)
.unwrap();
// Now test with empty DB
let empty_bindings = get_all_driver_bindings();
assert_eq!(empty_bindings.len(), 0);
});
}
#[test]
fn test_core_connect_single_controller() {
with_locked_state(|| {
// Reset counters
SUPPORTED_CALL_COUNT.store(0, Ordering::SeqCst);
START_CALL_COUNT.store(0, Ordering::SeqCst);
// Initialize the handles in the protocol database
// Controller protocol
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x1111 as *mut core::ffi::c_void,
)
.unwrap();
// Driver protocols
let (driver_handle1, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x1010 as *mut core::ffi::c_void,
)
.unwrap();
let (driver_handle2, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x2020 as *mut core::ffi::c_void,
)
.unwrap();
let (driver_handle3, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x3030 as *mut core::ffi::c_void,
)
.unwrap();
// Create three driver binding protocols with different behaviors
let binding1 = create_driver_binding(
10,
driver_handle1,
mock_supported_with_counter,
mock_start_with_counter,
mock_stop_success,
);
let binding1_ptr = Box::into_raw(binding1) as *mut core::ffi::c_void;
let binding2 = create_driver_binding(
20,
driver_handle2,
mock_supported_failure, // This one will fail Supported()
mock_start_success,
mock_stop_success,
);
let binding2_ptr = Box::into_raw(binding2) as *mut core::ffi::c_void;
let binding3 = create_driver_binding(
30,
driver_handle3,
mock_supported_success,
mock_start_failure, // This one will fail Start()
mock_stop_success,
);
let binding3_ptr = Box::into_raw(binding3) as *mut core::ffi::c_void;
// Install driver binding protocols on their handles
PROTOCOL_DB
.install_protocol_interface(
Some(driver_handle1),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding1_ptr,
)
.unwrap();
PROTOCOL_DB
.install_protocol_interface(
Some(driver_handle2),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding2_ptr,
)
.unwrap();
PROTOCOL_DB
.install_protocol_interface(
Some(driver_handle3),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding3_ptr,
)
.unwrap();
let result = core_connect_single_controller(
controller_handle,
vec![driver_handle1, driver_handle3], // Include only binding1 and binding3
None,
);
assert!(result.is_ok());
// Verify the right number of calls were made
assert_eq!(SUPPORTED_CALL_COUNT.load(Ordering::SeqCst), 1); // binding1 only
assert_eq!(START_CALL_COUNT.load(Ordering::SeqCst), 1); // binding1 only
// Reset counters for next test
SUPPORTED_CALL_COUNT.store(0, Ordering::SeqCst);
START_CALL_COUNT.store(0, Ordering::SeqCst);
// Test connection with an END device path
let end_path = create_end_device_path();
let end_path_ptr = Box::into_raw(Box::new(end_path));
let result = core_connect_single_controller(controller_handle, vec![driver_handle1], Some(end_path_ptr));
// Should succeed because this is an END device path
assert!(result.is_ok());
// Reset counters for next test
SUPPORTED_CALL_COUNT.store(0, Ordering::SeqCst);
START_CALL_COUNT.store(0, Ordering::SeqCst);
// Test connection where no drivers match
let _result = core_connect_single_controller(
controller_handle,
vec![driver_handle2], // Only the one that fails Supported()
None,
);
// Verify that support was checked but start was not called
assert_eq!(SUPPORTED_CALL_COUNT.load(Ordering::SeqCst), 1); // Since we're using mock_supported_failure
assert_eq!(START_CALL_COUNT.load(Ordering::SeqCst), 1); // Start should never be called
});
}
#[test]
fn test_core_connect_controller() {
with_locked_state(|| {
// Initialize test handles and protocols
// Controller handle
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x1111 as *mut core::ffi::c_void,
)
.unwrap();
// Driver handle
let (driver_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x2222 as *mut core::ffi::c_void,
)
.unwrap();
// Create and install a driver binding protocol
let binding = create_driver_binding(
10,
driver_handle,
mock_supported_with_counter,
mock_start_with_counter,
mock_stop_success,
);
let binding_ptr = Box::into_raw(binding) as *mut core::ffi::c_void;
PROTOCOL_DB
.install_protocol_interface(
Some(driver_handle),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding_ptr,
)
.unwrap();
// Reset counters
SUPPORTED_CALL_COUNT.store(0, Ordering::SeqCst);
START_CALL_COUNT.store(0, Ordering::SeqCst);
// Test 1: Basic connection (non-recursive)
// SAFETY: Both controller_handle and driver_handle are required to be valid. Both are
// set via an .unwrap() call from an .install_protocol_interface() call. These calls
// would panic if an error was returned.
unsafe {
let result = core_connect_controller(
controller_handle,
vec![driver_handle],
None,
false, // non-recursive
);
assert!(result.is_ok());
assert_eq!(SUPPORTED_CALL_COUNT.load(Ordering::SeqCst), 1);
assert_eq!(START_CALL_COUNT.load(Ordering::SeqCst), 1);
}
// Reset counters
SUPPORTED_CALL_COUNT.store(0, Ordering::SeqCst);
START_CALL_COUNT.store(0, Ordering::SeqCst);
// Test 2: Create a child handle to test recursive behavior
let (child_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x3333 as *mut core::ffi::c_void,
)
.unwrap();
// Make child_handle a child of controller_handle
PROTOCOL_DB
.add_protocol_usage(
controller_handle,
efi::protocols::device_path::PROTOCOL_GUID,
Some(driver_handle),
Some(child_handle),
efi::OPEN_PROTOCOL_BY_CHILD_CONTROLLER,
)
.unwrap();
// Test recursive connection
// SAFETY: Both controller_handle and driver_handle are required to be valid. Both are
// set via an .unwrap() call from an .install_protocol_interface() call. These calls
// would panic if an error was returned.
unsafe {
let result = core_connect_controller(
controller_handle,
vec![driver_handle],
None,
true, // recursive
);
assert!(result.is_ok());
// Should have at least two calls (one for parent, one for child)
assert!(SUPPORTED_CALL_COUNT.load(Ordering::SeqCst) >= 1);
assert!(START_CALL_COUNT.load(Ordering::SeqCst) >= 1);
}
// Test 3: Test with remaining device path
let end_path = create_end_device_path();
let end_path_ptr = Box::into_raw(Box::new(end_path));
// Reset counters
SUPPORTED_CALL_COUNT.store(0, Ordering::SeqCst);
START_CALL_COUNT.store(0, Ordering::SeqCst);
// SAFETY: controller_handle, driver_handle and end_path_ptr are required to be valid.
// controller_handle and driver_handle are set via an .unwrap() call from an
// .install_protocol_interface() call. These calls would panic if an error was returned.
// end_path_ptr was set via Box::into_raw which is guaranteed to return a non-null pointer.
unsafe {
let result = core_connect_controller(
controller_handle,
vec![driver_handle],
Some(end_path_ptr),
false, // non-recursive
);
assert!(result.is_ok());
}
});
}
#[test]
fn test_connect_controller() {
with_locked_state(|| {
// Initialize test handles and protocols
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x1111 as *mut core::ffi::c_void,
)
.unwrap();
let (driver_handle1, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x2222 as *mut core::ffi::c_void,
)
.unwrap();
// Create and install a driver binding protocol
let binding = create_driver_binding(
10,
driver_handle1,
mock_supported_with_counter,
mock_start_with_counter,
mock_stop_success,
);
let binding_ptr = Box::into_raw(binding) as *mut core::ffi::c_void;
PROTOCOL_DB
.install_protocol_interface(
Some(driver_handle1),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding_ptr,
)
.unwrap();
// Reset counters
SUPPORTED_CALL_COUNT.store(0, Ordering::SeqCst);
START_CALL_COUNT.store(0, Ordering::SeqCst);
// Test 1: Call with single driver handle
let mut driver_handles = vec![driver_handle1, core::ptr::null_mut()];
let status = connect_controller(
controller_handle,
driver_handles.as_mut_ptr(),
core::ptr::null_mut(), // No remaining device path
efi::Boolean::FALSE,
);
assert_eq!(status, efi::Status::SUCCESS);
assert_eq!(SUPPORTED_CALL_COUNT.load(Ordering::SeqCst), 1);
assert_eq!(START_CALL_COUNT.load(Ordering::SeqCst), 1);
// Test 2: Call with null driver handle (should use all drivers)
SUPPORTED_CALL_COUNT.store(0, Ordering::SeqCst);
START_CALL_COUNT.store(0, Ordering::SeqCst);
let status = connect_controller(
controller_handle,
core::ptr::null_mut(), // Null driver handle array
core::ptr::null_mut(), // No remaining device path
efi::Boolean::FALSE,
);
assert_eq!(status, efi::Status::SUCCESS);
// At least one support call should have happened
assert!(SUPPORTED_CALL_COUNT.load(Ordering::SeqCst) >= 1);
});
}
#[test]
fn test_core_disconnect_controller() {
with_locked_state(|| {
let uuid1 = Uuid::from_str("0e896c7a-57dc-4987-bc22-abc3a8263210").unwrap();
let guid1 = efi::Guid::from_bytes(uuid1.as_bytes());
let interface1: *mut c_void = 0x1234 as *mut c_void;
let (handle1, _) = PROTOCOL_DB.install_protocol_interface(None, guid1, interface1).unwrap();
// Test single driver managing controller
{
// Create controller handle with VendorDefined device path
let controller_device_path = Box::new(create_vendor_defined_device_path(0x1111));
let controller_device_path_ptr = Box::into_raw(controller_device_path) as *mut core::ffi::c_void;
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
controller_device_path_ptr,
)
.unwrap();
// Create driver handle with VendorDefined device path
let driver_device_path = Box::new(create_vendor_defined_device_path(0x2222));
let driver_device_path_ptr = Box::into_raw(driver_device_path) as *mut core::ffi::c_void;
let (driver_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
driver_device_path_ptr,
)
.unwrap();
// Create and install driver binding protocol
let binding = create_driver_binding(
10,
driver_handle,
mock_supported_success,
mock_start_success,
mock_stop_success,
);
let binding_ptr = Box::into_raw(binding) as *mut core::ffi::c_void;
PROTOCOL_DB
.install_protocol_interface(
Some(driver_handle),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding_ptr,
)
.unwrap();
// Simulate driver managing controller by adding protocol usage
PROTOCOL_DB
.add_protocol_usage(
controller_handle,
efi::protocols::device_path::PROTOCOL_GUID,
Some(driver_handle),
Some(handle1),
efi::OPEN_PROTOCOL_BY_DRIVER,
)
.unwrap();
// Test disconnect without specifying driver or child
// SAFETY: controller_handle is required to be valid. It was set via an .unwrap() call
// from an .install_protocol_interface() call. This call would panic if an error was returned.
unsafe {
let result = core_disconnect_controller(controller_handle, None, None);
assert!(result.is_ok(), "Should successfully disconnect all drivers");
}
}
});
}
#[test]
fn test_core_disconnect_controller_with_child_handles() {
with_locked_state(|| {
use std::sync::atomic::{AtomicUsize, Ordering};
// Track calls to the stop function and parameters
static STOP_CALL_COUNT: AtomicUsize = AtomicUsize::new(0);
static LAST_CHILD_COUNT: AtomicUsize = AtomicUsize::new(0);
let uuid1 = Uuid::from_str("0e896c7a-57dc-4987-bc22-abc3a8263210").unwrap();
let guid1 = efi::Guid::from_bytes(uuid1.as_bytes());
let interface1: *mut c_void = 0x1234 as *mut c_void;
let (handle1, _) = PROTOCOL_DB.install_protocol_interface(None, guid1, interface1).unwrap();
// Mock stop function that tracks calls and child count
extern "efiapi" fn mock_stop_with_tracking(
_this: *mut efi::protocols::driver_binding::Protocol,
_controller_handle: efi::Handle,
num_children: usize,
_child_handle_buffer: *mut efi::Handle,
) -> efi::Status {
STOP_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
LAST_CHILD_COUNT.store(num_children, Ordering::SeqCst);
efi::Status::SUCCESS
}
// Create controller handle with VendorDefined device path
let controller_device_path = Box::new(create_vendor_defined_device_path(0x1111));
let controller_device_path_ptr = Box::into_raw(controller_device_path) as *mut core::ffi::c_void;
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
controller_device_path_ptr,
)
.unwrap();
// Create driver handle with VendorDefined device path
let driver_device_path = Box::new(create_vendor_defined_device_path(0x2222));
let driver_device_path_ptr = Box::into_raw(driver_device_path) as *mut core::ffi::c_void;
let (driver_handle, _) = PROTOCOL_DB
.install_protocol_interface(None, efi::protocols::device_path::PROTOCOL_GUID, driver_device_path_ptr)
.unwrap();
// Create child handle with VendorDefined device path
let child_device_path = Box::new(create_vendor_defined_device_path(0x3333));
let child_device_path_ptr = Box::into_raw(child_device_path) as *mut core::ffi::c_void;
let (child_handle, _) = PROTOCOL_DB
.install_protocol_interface(None, efi::protocols::device_path::PROTOCOL_GUID, child_device_path_ptr)
.unwrap();
// Create driver binding protocol
let binding = Box::new(efi::protocols::driver_binding::Protocol {
version: 10,
supported: mock_supported_success,
start: mock_start_success,
stop: mock_stop_with_tracking,
driver_binding_handle: driver_handle,
image_handle: DXE_CORE_HANDLE,
});
let binding_ptr = Box::into_raw(binding) as *mut core::ffi::c_void;
// Install driver binding protocol
PROTOCOL_DB
.install_protocol_interface(
Some(driver_handle),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding_ptr,
)
.unwrap();
// Simulate driver managing controller - add BY_DRIVER usage
PROTOCOL_DB
.add_protocol_usage(
controller_handle,
efi::protocols::device_path::PROTOCOL_GUID,
Some(driver_handle),
Some(handle1),
efi::OPEN_PROTOCOL_BY_DRIVER,
)
.unwrap();
// Simulate child controller managed by this driver - add BY_CHILD_CONTROLLER usage
PROTOCOL_DB
.add_protocol_usage(
controller_handle,
efi::protocols::device_path::PROTOCOL_GUID,
Some(driver_handle),
Some(child_handle), // child handle for BY_CHILD_CONTROLLER
efi::OPEN_PROTOCOL_BY_CHILD_CONTROLLER,
)
.unwrap();
// Reset counters
STOP_CALL_COUNT.store(0, Ordering::SeqCst);
LAST_CHILD_COUNT.store(999, Ordering::SeqCst); // Set to invalid value to detect changes
// Test disconnect - should call stop function
// SAFETY: controller_handle is required to be valid. It was set via an .unwrap() call
// from an .install_protocol_interface() call. This call would panic if an error was returned.
unsafe {
let result = core_disconnect_controller(controller_handle, None, None);
assert!(result.is_ok(), "disconnect should succeed");
}
// Verify stop was called at least once
let call_count = STOP_CALL_COUNT.load(Ordering::SeqCst);
assert!(call_count > 0, "stop should be called at least once, but was called {call_count} times");
// Just verify that the function executed the child handling logic
// The exact behavior depends on the protocol database implementation
println!("Stop called {} times, last child count: {}", call_count, LAST_CHILD_COUNT.load(Ordering::SeqCst));
});
}
#[test]
fn test_core_disconnect_controller_specific_child_only_child() {
with_locked_state(|| {
use std::sync::atomic::{AtomicUsize, Ordering};
// Track calls to the stop function and parameters
static STOP_CALLS: AtomicUsize = AtomicUsize::new(0);
static DRIVER_STOP_CALLED: AtomicUsize = AtomicUsize::new(0); // Track full driver stops
let uuid1 = Uuid::from_str("0e896c7a-57dc-4987-bc22-abc3a8263210").unwrap();
let guid1 = efi::Guid::from_bytes(uuid1.as_bytes());
let interface1: *mut c_void = 0x1234 as *mut c_void;
let (handle1, _) = PROTOCOL_DB.install_protocol_interface(None, guid1, interface1).unwrap();
// Mock stop function that tracks different types of calls
extern "efiapi" fn mock_stop_tracking(
_this: *mut efi::protocols::driver_binding::Protocol,
_controller_handle: efi::Handle,
num_children: usize,
_child_handle_buffer: *mut efi::Handle,
) -> efi::Status {
STOP_CALLS.fetch_add(1, Ordering::SeqCst);
if num_children == 0 {
DRIVER_STOP_CALLED.fetch_add(1, Ordering::SeqCst);
}
efi::Status::SUCCESS
}
// Create controller handle
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x1111 as *mut core::ffi::c_void,
)
.unwrap();
// Create driver handle
let (driver_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x2222 as *mut core::ffi::c_void,
)
.unwrap();
// Create only one child handle
let (child_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x3333 as *mut core::ffi::c_void,
)
.unwrap();
// Create driver binding protocol
let binding = Box::new(efi::protocols::driver_binding::Protocol {
version: 10,
supported: mock_supported_success,
start: mock_start_success,
stop: mock_stop_tracking,
driver_binding_handle: driver_handle,
image_handle: DXE_CORE_HANDLE,
});
let binding_ptr = Box::into_raw(binding) as *mut core::ffi::c_void;
// Install driver binding protocol
PROTOCOL_DB
.install_protocol_interface(
Some(driver_handle),
efi::protocols::driver_binding::PROTOCOL_GUID,
binding_ptr,
)
.unwrap();
// Simulate driver managing controller
PROTOCOL_DB
.add_protocol_usage(
controller_handle,
efi::protocols::device_path::PROTOCOL_GUID,
Some(driver_handle),
Some(handle1),
efi::OPEN_PROTOCOL_BY_DRIVER,
)
.unwrap();
// Simulate only ONE child controller managed by this driver
PROTOCOL_DB
.add_protocol_usage(
controller_handle,
efi::protocols::device_path::PROTOCOL_GUID,
Some(driver_handle),
Some(child_handle),
efi::OPEN_PROTOCOL_BY_CHILD_CONTROLLER,
)
.unwrap();
// Reset counters
STOP_CALLS.store(0, Ordering::SeqCst);
DRIVER_STOP_CALLED.store(0, Ordering::SeqCst);
// Test disconnect with specific child handle (which is the ONLY child)
// This should trigger: is_only_child = total_children == child_handles.len() = true
// Because: total_children = 1, child_handles.retain() keeps 1 child, so 1 == 1
// SAFETY: Both controller_handle and child_handle are required to be valid. Both were set
// via an .unwrap() call from an .install_protocol_interface() call. These calls would panic
// if an error was returned.
unsafe {
let result = core_disconnect_controller(controller_handle, None, Some(child_handle));
assert!(result.is_ok(), "disconnect should succeed");
}
// When child was specified and it was the only child, driver should be fully disconnected
// This means stop should be called twice: once for children, once for driver
let total_calls = STOP_CALLS.load(Ordering::SeqCst);
let driver_stops = DRIVER_STOP_CALLED.load(Ordering::SeqCst);
println!("Total stop calls: {total_calls}, Driver stops (num_children=0): {driver_stops}");
// Since we specified the only child, the driver should be disconnected completely
assert!(driver_stops > 0, "Driver should be fully stopped when specified child is the only child");
});
}
#[test]
fn test_core_disconnect_controller_invalid_driver_handle() {
with_locked_state(|| {
// Create a valid controller handle
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x1111 as *mut core::ffi::c_void,
)
.unwrap();
// Use an invalid driver handle (not in protocol database)
let invalid_driver_handle = 0x9999 as efi::Handle;
// Test disconnect with invalid driver handle
// SAFETY: Both controller_handle and invalid_driver_handle are required to be valid.
// controller_handle is set via an .unwrap() call from an .install_protocol_interface()
// call. This call would panic if an error was returned. invalid_driver_handle is
// statically set to 0x9999 which guarantees it is non-null.
unsafe {
let result = core_disconnect_controller(
controller_handle,
Some(invalid_driver_handle), // Invalid driver handle
None,
);
// Should fail with InvalidParameter due to driver handle validation
assert!(result.is_err(), "Should fail with invalid driver handle");
if let Err(error) = result {
assert_eq!(
error,
EfiError::InvalidParameter,
"Should return InvalidParameter for invalid driver handle"
);
}
}
});
}
#[test]
fn test_core_disconnect_controller_invalid_child_handle() {
with_locked_state(|| {
// Create a valid controller handle
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x1111 as *mut core::ffi::c_void,
)
.unwrap();
// Use an invalid child handle (not in protocol database)
let invalid_child_handle = 0x8888 as efi::Handle;
// Test disconnect with invalid child handle
// SAFETY: Both controller_handle and invalid_child_handle are required to be valid.
// controller_handle is set via an .unwrap() call from an .install_protocol_interface()
// call. This call would panic if an error was returned. invalid_child_handle is
// statically set to 0x8888 which guarantees it is non-null.
unsafe {
let result = core_disconnect_controller(
controller_handle,
None,
Some(invalid_child_handle), // Invalid child handle
);
// Should fail with InvalidParameter due to child handle validation
assert!(result.is_err(), "Should fail with invalid child handle");
if let Err(error) = result {
assert_eq!(
error,
EfiError::InvalidParameter,
"Should return InvalidParameter for invalid child handle"
);
}
}
});
}
#[test]
fn test_disconnect_controller_extern_function() {
with_locked_state(|| {
// Create controller handle
let (controller_handle, _) = PROTOCOL_DB
.install_protocol_interface(
None,
efi::protocols::device_path::PROTOCOL_GUID,
0x1111 as *mut core::ffi::c_void,
)
.unwrap();
// Test the extern "efiapi" function with null handles (should succeed for empty controller)
let status = disconnect_controller(
controller_handle,
core::ptr::null_mut(), // No specific driver
core::ptr::null_mut(), // No child handle
);
assert_eq!(status, efi::Status::SUCCESS, "disconnect_controller should succeed with null handles");
// Test with invalid controller handle
let invalid_handle = 0x9999 as efi::Handle;
let status = disconnect_controller(invalid_handle, core::ptr::null_mut(), core::ptr::null_mut());
// Should return error status for invalid handle
assert_ne!(status, efi::Status::SUCCESS, "disconnect_controller should fail with invalid handle");
});
}
#[test]
fn test_init_driver_services() {
with_locked_state(|| {
let mut st = EfiSystemTable::allocate_new_table();
init_driver_services(&mut st);
let boot_services = st.boot_services().get();
assert!(boot_services.connect_controller as usize == connect_controller as *const () as usize);
assert!(boot_services.disconnect_controller as usize == disconnect_controller as *const () as usize);
})
}
}