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
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <efi.h>
#include <efigpt.h>
#include <efilib.h>
#include "bcd.h"
#include "bootspec-fundamental.h"
#include "console.h"
#include "devicetree.h"
#include "disk.h"
#include "drivers.h"
#include "efivars-fundamental.h"
#include "graphics.h"
#include "initrd.h"
#include "linux.h"
#include "measure.h"
#include "pe.h"
#include "vmm.h"
#include "random-seed.h"
#include "secure-boot.h"
#include "shim.h"
#include "ticks.h"
#include "util.h"
#include "xbootldr.h"
#ifndef GNU_EFI_USE_MS_ABI
/* We do not use uefi_call_wrapper() in systemd-boot. As such, we rely on the
* compiler to do the calling convention conversion for us. This is check is
* to make sure the -DGNU_EFI_USE_MS_ABI was passed to the comiler. */
#error systemd-boot requires compilation with GNU_EFI_USE_MS_ABI defined.
#endif
#define TEXT_ATTR_SWAP(c) EFI_TEXT_ATTR(((c) & 0b11110000) >> 4, (c) & 0b1111)
/* Magic string for recognizing our own binaries */
_used_ _section_(".sdmagic") static const char magic[] =
"#### LoaderInfo: systemd-boot " GIT_VERSION " ####";
/* Makes systemd-boot available from \EFI\Linux\ for testing purposes. */
_used_ _section_(".osrel") static const char osrel[] =
"ID=systemd-boot\n"
"VERSION=\"" GIT_VERSION "\"\n"
"NAME=\"systemd-boot " GIT_VERSION "\"\n";
enum loader_type {
LOADER_UNDEFINED,
LOADER_AUTO,
LOADER_EFI,
LOADER_LINUX, /* Boot loader spec type #1 entries */
LOADER_UNIFIED_LINUX, /* Boot loader spec type #2 entries */
LOADER_SECURE_BOOT_KEYS,
};
typedef struct {
char16_t *id; /* The unique identifier for this entry (typically the filename of the file defining the entry) */
char16_t *title_show; /* The string to actually display (this is made unique before showing) */
char16_t *title; /* The raw (human readable) title string of the entry (not necessarily unique) */
char16_t *sort_key; /* The string to use as primary sort key, usually ID= from os-release, possibly suffixed */
char16_t *version; /* The raw (human readable) version string of the entry */
char16_t *machine_id;
EFI_HANDLE *device;
enum loader_type type;
char16_t *loader;
char16_t *devicetree;
char16_t *options;
char16_t **initrd;
char16_t key;
EFI_STATUS (*call)(void);
int tries_done;
int tries_left;
char16_t *path;
char16_t *current_name;
char16_t *next_name;
} ConfigEntry;
typedef struct {
ConfigEntry **entries;
UINTN entry_count;
UINTN idx_default;
UINTN idx_default_efivar;
uint32_t timeout_sec; /* Actual timeout used (efi_main() override > efivar > config). */
uint32_t timeout_sec_config;
uint32_t timeout_sec_efivar;
char16_t *entry_default_config;
char16_t *entry_default_efivar;
char16_t *entry_oneshot;
char16_t *entry_saved;
bool editor;
bool auto_entries;
bool auto_firmware;
bool reboot_for_bitlocker;
secure_boot_enroll secure_boot_enroll;
bool force_menu;
bool use_saved_entry;
bool use_saved_entry_efivar;
bool beep;
int64_t console_mode;
int64_t console_mode_efivar;
RandomSeedMode random_seed_mode;
} Config;
/* These values have been chosen so that the transitions the user sees could
* employ unsigned over-/underflow like this:
* efivar unset ↔ force menu ↔ no timeout/skip menu ↔ 1 s ↔ 2 s ↔ … */
enum {
TIMEOUT_MIN = 1,
TIMEOUT_MAX = UINT32_MAX - 2U,
TIMEOUT_UNSET = UINT32_MAX - 1U,
TIMEOUT_MENU_FORCE = UINT32_MAX,
TIMEOUT_MENU_HIDDEN = 0,
TIMEOUT_TYPE_MAX = UINT32_MAX,
};
enum {
IDX_MAX = INT16_MAX,
IDX_INVALID,
};
static void cursor_left(UINTN *cursor, UINTN *first) {
assert(cursor);
assert(first);
if ((*cursor) > 0)
(*cursor)--;
else if ((*first) > 0)
(*first)--;
}
static void cursor_right(
UINTN *cursor,
UINTN *first,
UINTN x_max,
UINTN len) {
assert(cursor);
assert(first);
if ((*cursor)+1 < x_max)
(*cursor)++;
else if ((*first) + (*cursor) < len)
(*first)++;
}
static bool line_edit(
char16_t **line_in,
UINTN x_max,
UINTN y_pos) {
_cleanup_free_ char16_t *line = NULL, *print = NULL;
UINTN size, len, first = 0, cursor = 0, clear = 0;
assert(line_in);
len = strlen16(*line_in);
size = len + 1024;
line = xnew(char16_t, size);
print = xnew(char16_t, x_max + 1);
strcpy16(line, strempty(*line_in));
for (;;) {
EFI_STATUS err;
uint64_t key;
UINTN j;
UINTN cursor_color = TEXT_ATTR_SWAP(COLOR_EDIT);
j = MIN(len - first, x_max);
memcpy(print, line + first, j * sizeof(char16_t));
while (clear > 0 && j < x_max) {
clear--;
print[j++] = ' ';
}
print[j] = '\0';
/* See comment at edit_line() call site for why we start at 1. */
print_at(1, y_pos, COLOR_EDIT, print);
if (!print[cursor])
print[cursor] = ' ';
print[cursor+1] = '\0';
do {
print_at(cursor + 1, y_pos, cursor_color, print + cursor);
cursor_color = TEXT_ATTR_SWAP(cursor_color);
err = console_key_read(&key, 750 * 1000);
if (!IN_SET(err, EFI_SUCCESS, EFI_TIMEOUT, EFI_NOT_READY))
return false;
print_at(cursor + 1, y_pos, COLOR_EDIT, print + cursor);
} while (err != EFI_SUCCESS);
switch (key) {
case KEYPRESS(0, SCAN_ESC, 0):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'c'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'g'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('c')):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('g')):
return false;
case KEYPRESS(0, SCAN_HOME, 0):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'a'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('a')):
/* beginning-of-line */
cursor = 0;
first = 0;
continue;
case KEYPRESS(0, SCAN_END, 0):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'e'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('e')):
/* end-of-line */
cursor = len - first;
if (cursor+1 >= x_max) {
cursor = x_max-1;
first = len - (x_max-1);
}
continue;
case KEYPRESS(0, SCAN_DOWN, 0):
case KEYPRESS(EFI_ALT_PRESSED, 0, 'f'):
case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_RIGHT, 0):
/* forward-word */
while (line[first + cursor] == ' ')
cursor_right(&cursor, &first, x_max, len);
while (line[first + cursor] && line[first + cursor] != ' ')
cursor_right(&cursor, &first, x_max, len);
continue;
case KEYPRESS(0, SCAN_UP, 0):
case KEYPRESS(EFI_ALT_PRESSED, 0, 'b'):
case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_LEFT, 0):
/* backward-word */
if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
cursor_left(&cursor, &first);
while ((first + cursor) > 0 && line[first + cursor] == ' ')
cursor_left(&cursor, &first);
}
while ((first + cursor) > 0 && line[first + cursor-1] != ' ')
cursor_left(&cursor, &first);
continue;
case KEYPRESS(0, SCAN_RIGHT, 0):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'f'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('f')):
/* forward-char */
if (first + cursor == len)
continue;
cursor_right(&cursor, &first, x_max, len);
continue;
case KEYPRESS(0, SCAN_LEFT, 0):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'b'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('b')):
/* backward-char */
cursor_left(&cursor, &first);
continue;
case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_DELETE, 0):
case KEYPRESS(EFI_ALT_PRESSED, 0, 'd'):
/* kill-word */
clear = 0;
UINTN k;
for (k = first + cursor; k < len && line[k] == ' '; k++)
clear++;
for (; k < len && line[k] != ' '; k++)
clear++;
for (UINTN i = first + cursor; i + clear < len; i++)
line[i] = line[i + clear];
len -= clear;
line[len] = '\0';
continue;
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'w'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('w')):
case KEYPRESS(EFI_ALT_PRESSED, 0, CHAR_BACKSPACE):
/* backward-kill-word */
clear = 0;
if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
cursor_left(&cursor, &first);
clear++;
while ((first + cursor) > 0 && line[first + cursor] == ' ') {
cursor_left(&cursor, &first);
clear++;
}
}
while ((first + cursor) > 0 && line[first + cursor-1] != ' ') {
cursor_left(&cursor, &first);
clear++;
}
for (UINTN i = first + cursor; i + clear < len; i++)
line[i] = line[i + clear];
len -= clear;
line[len] = '\0';
continue;
case KEYPRESS(0, SCAN_DELETE, 0):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'd'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('d')):
if (len == 0)
continue;
if (first + cursor == len)
continue;
for (UINTN i = first + cursor; i < len; i++)
line[i] = line[i+1];
clear = 1;
len--;
continue;
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'k'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('k')):
/* kill-line */
line[first + cursor] = '\0';
clear = len - (first + cursor);
len = first + cursor;
continue;
case KEYPRESS(0, 0, CHAR_LINEFEED):
case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
case KEYPRESS(0, SCAN_F3, 0): /* EZpad Mini 4s firmware sends malformed events */
case KEYPRESS(0, SCAN_F3, CHAR_CARRIAGE_RETURN): /* Teclast X98+ II firmware sends malformed events */
if (!streq16(line, *line_in)) {
free(*line_in);
*line_in = TAKE_PTR(line);
}
return true;
case KEYPRESS(0, 0, CHAR_BACKSPACE):
if (len == 0)
continue;
if (first == 0 && cursor == 0)
continue;
for (UINTN i = first + cursor-1; i < len; i++)
line[i] = line[i+1];
clear = 1;
len--;
if (cursor > 0)
cursor--;
if (cursor > 0 || first == 0)
continue;
/* show full line if it fits */
if (len < x_max) {
cursor = first;
first = 0;
continue;
}
/* jump left to see what we delete */
if (first > 10) {
first -= 10;
cursor = 10;
} else {
cursor = first;
first = 0;
}
continue;
case KEYPRESS(0, 0, ' ') ... KEYPRESS(0, 0, '~'):
case KEYPRESS(0, 0, 0x80) ... KEYPRESS(0, 0, 0xffff):
if (len+1 == size)
continue;
for (UINTN i = len; i > first + cursor; i--)
line[i] = line[i-1];
line[first + cursor] = KEYCHAR(key);
len++;
line[len] = '\0';
if (cursor+1 < x_max)
cursor++;
else if (first + cursor < len)
first++;
continue;
}
}
}
static UINTN entry_lookup_key(Config *config, UINTN start, char16_t key) {
assert(config);
if (key == 0)
return IDX_INVALID;
/* select entry by number key */
if (key >= '1' && key <= '9') {
UINTN i = key - '0';
if (i > config->entry_count)
i = config->entry_count;
return i-1;
}
/* find matching key in config entries */
for (UINTN i = start; i < config->entry_count; i++)
if (config->entries[i]->key == key)
return i;
for (UINTN i = 0; i < start; i++)
if (config->entries[i]->key == key)
return i;
return IDX_INVALID;
}
static char16_t *update_timeout_efivar(uint32_t *t, bool inc) {
assert(t);
switch (*t) {
case TIMEOUT_MAX:
*t = inc ? TIMEOUT_MAX : (*t - 1);
break;
case TIMEOUT_UNSET:
*t = inc ? TIMEOUT_MENU_FORCE : TIMEOUT_UNSET;
break;
case TIMEOUT_MENU_FORCE:
*t = inc ? TIMEOUT_MENU_HIDDEN : TIMEOUT_UNSET;
break;
case TIMEOUT_MENU_HIDDEN:
*t = inc ? TIMEOUT_MIN : TIMEOUT_MENU_FORCE;
break;
default:
*t += inc ? 1 : -1;
}
switch (*t) {
case TIMEOUT_UNSET:
return xstrdup16(u"Menu timeout defined by configuration file.");
case TIMEOUT_MENU_FORCE:
return xstrdup16(u"Timeout disabled, menu will always be shown.");
case TIMEOUT_MENU_HIDDEN:
return xstrdup16(u"Menu disabled. Hold down key at bootup to show menu.");
default:
return xpool_print(L"Menu timeout set to %u s.", *t);
}
}
static bool unicode_supported(void) {
static int cache = -1;
if (cache < 0)
/* Basic unicode box drawing support is mandated by the spec, but it does
* not hurt to make sure it works. */
cache = ST->ConOut->TestString(ST->ConOut, (char16_t *) L"─") == EFI_SUCCESS;
return cache;
}
static void ps_string(const char16_t *fmt, const void *value) {
assert(fmt);
if (value)
Print(fmt, value);
}
static void ps_bool(const char16_t *fmt, bool value) {
assert(fmt);
Print(fmt, yes_no(value));
}
static bool ps_continue(void) {
if (unicode_supported())
Print(L"\n─── Press any key to continue, ESC or q to quit. ───\n\n");
else
Print(L"\n--- Press any key to continue, ESC or q to quit. ---\n\n");
uint64_t key;
return console_key_read(&key, UINT64_MAX) == EFI_SUCCESS &&
!IN_SET(key, KEYPRESS(0, SCAN_ESC, 0), KEYPRESS(0, 0, 'q'), KEYPRESS(0, 0, 'Q'));
}
static void print_status(Config *config, char16_t *loaded_image_path) {
UINTN x_max, y_max;
uint32_t screen_width = 0, screen_height = 0;
SecureBootMode secure;
_cleanup_free_ char16_t *device_part_uuid = NULL;
assert(config);
clear_screen(COLOR_NORMAL);
console_query_mode(&x_max, &y_max);
query_screen_resolution(&screen_width, &screen_height);
secure = secure_boot_mode();
(void) efivar_get(LOADER_GUID, L"LoaderDevicePartUUID", &device_part_uuid);
/* We employ some unusual indentation here for readability. */
ps_string(L" systemd-boot version: %a\n", GIT_VERSION);
ps_string(L" loaded image: %s\n", loaded_image_path);
ps_string(L" loader partition UUID: %s\n", device_part_uuid);
ps_string(L" architecture: %a\n", EFI_MACHINE_TYPE_NAME);
Print(L" UEFI specification: %u.%02u\n", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
ps_string(L" firmware vendor: %s\n", ST->FirmwareVendor);
Print(L" firmware version: %u.%02u\n", ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
Print(L" OS indications: %lu\n", get_os_indications_supported());
Print(L" secure boot: %s (%s)\n", yes_no(IN_SET(secure, SECURE_BOOT_USER, SECURE_BOOT_DEPLOYED)), secure_boot_mode_to_string(secure));
ps_bool(L" shim: %s\n", shim_loaded());
ps_bool(L" TPM: %s\n", tpm_present());
Print(L" console mode: %d/%ld (%" PRIuN L"x%" PRIuN L" @%ux%u)\n", ST->ConOut->Mode->Mode, ST->ConOut->Mode->MaxMode - INT64_C(1), x_max, y_max, screen_width, screen_height);
if (!ps_continue())
return;
switch (config->timeout_sec_config) {
case TIMEOUT_UNSET:
break;
case TIMEOUT_MENU_FORCE:
Print(L" timeout (config): menu-force\n"); break;
case TIMEOUT_MENU_HIDDEN:
Print(L" timeout (config): menu-hidden\n"); break;
default:
Print(L" timeout (config): %u s\n", config->timeout_sec_config);
}
switch (config->timeout_sec_efivar) {
case TIMEOUT_UNSET:
break;
case TIMEOUT_MENU_FORCE:
Print(L" timeout (EFI var): menu-force\n"); break;
case TIMEOUT_MENU_HIDDEN:
Print(L" timeout (EFI var): menu-hidden\n"); break;
default:
Print(L" timeout (EFI var): %u s\n", config->timeout_sec_efivar);
}
ps_string(L" default (config): %s\n", config->entry_default_config);
ps_string(L" default (EFI var): %s\n", config->entry_default_efivar);
ps_string(L" default (one-shot): %s\n", config->entry_oneshot);
ps_string(L" saved entry: %s\n", config->entry_saved);
ps_bool(L" editor: %s\n", config->editor);
ps_bool(L" auto-entries: %s\n", config->auto_entries);
ps_bool(L" auto-firmware: %s\n", config->auto_firmware);
ps_bool(L" beep: %s\n", config->beep);
ps_bool(L" reboot-for-bitlocker: %s\n", config->reboot_for_bitlocker);
ps_string(L" random-seed-mode: %s\n", random_seed_modes_table[config->random_seed_mode]);
switch (config->secure_boot_enroll) {
case ENROLL_OFF:
Print(L" secure-boot-enroll: off\n"); break;
case ENROLL_MANUAL:
Print(L" secure-boot-enroll: manual\n"); break;
case ENROLL_FORCE:
Print(L" secure-boot-enroll: force\n"); break;
default:
assert_not_reached();
}
switch (config->console_mode) {
case CONSOLE_MODE_AUTO:
Print(L" console-mode (config): %s\n", L"auto"); break;
case CONSOLE_MODE_KEEP:
Print(L" console-mode (config): %s\n", L"keep"); break;
case CONSOLE_MODE_FIRMWARE_MAX:
Print(L" console-mode (config): %s\n", L"max"); break;
default:
Print(L" console-mode (config): %ld\n", config->console_mode); break;
}
/* EFI var console mode is always a concrete value or unset. */
if (config->console_mode_efivar != CONSOLE_MODE_KEEP)
Print(L"console-mode (EFI var): %ld\n", config->console_mode_efivar);
if (!ps_continue())
return;
for (UINTN i = 0; i < config->entry_count; i++) {
ConfigEntry *entry = config->entries[i];
_cleanup_free_ char16_t *dp = NULL;
if (entry->device)
(void) device_path_to_str(DevicePathFromHandle(entry->device), &dp);
Print(L" config entry: %" PRIuN L"/%" PRIuN L"\n", i + 1, config->entry_count);
ps_string(L" id: %s\n", entry->id);
ps_string(L" title: %s\n", entry->title);
ps_string(L" title show: %s\n", streq16(entry->title, entry->title_show) ? NULL : entry->title_show);
ps_string(L" sort key: %s\n", entry->sort_key);
ps_string(L" version: %s\n", entry->version);
ps_string(L" machine-id: %s\n", entry->machine_id);
ps_string(L" device: %s\n", dp);
ps_string(L" loader: %s\n", entry->loader);
STRV_FOREACH(initrd, entry->initrd)
Print(L" initrd: %s\n", *initrd);
ps_string(L" devicetree: %s\n", entry->devicetree);
ps_string(L" options: %s\n", entry->options);
ps_bool(L" internal call: %s\n", !!entry->call);
ps_bool(L"counting boots: %s\n", entry->tries_left >= 0);
if (entry->tries_left >= 0) {
Print(L" tries: %u left, %u done\n", entry->tries_left, entry->tries_done);
Print(L" current path: %s\\%s\n", entry->path, entry->current_name);
Print(L" next path: %s\\%s\n", entry->path, entry->next_name);
}
if (!ps_continue())
return;
}
}
static EFI_STATUS reboot_into_firmware(void) {
uint64_t osind = 0;
EFI_STATUS err;
if (!FLAGS_SET(get_os_indications_supported(), EFI_OS_INDICATIONS_BOOT_TO_FW_UI))
return log_error_status_stall(EFI_UNSUPPORTED, L"Reboot to firmware interface not supported.");
(void) efivar_get_uint64_le(EFI_GLOBAL_GUID, L"OsIndications", &osind);
osind |= EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
err = efivar_set_uint64_le(EFI_GLOBAL_GUID, L"OsIndications", osind, EFI_VARIABLE_NON_VOLATILE);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Error setting OsIndications: %r", err);
RT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
assert_not_reached();
}
static bool menu_run(
Config *config,
ConfigEntry **chosen_entry,
char16_t *loaded_image_path) {
assert(config);
assert(chosen_entry);
EFI_STATUS err;
UINTN visible_max = 0;
UINTN idx_highlight = config->idx_default;
UINTN idx_highlight_prev = 0;
UINTN idx, idx_first = 0, idx_last = 0;
bool new_mode = true, clear = true;
bool refresh = true, highlight = false;
UINTN x_start = 0, y_start = 0, y_status = 0;
UINTN x_max, y_max;
_cleanup_(strv_freep) char16_t **lines = NULL;
_cleanup_free_ char16_t *clearline = NULL, *separator = NULL, *status = NULL;
uint32_t timeout_efivar_saved = config->timeout_sec_efivar;
uint32_t timeout_remain = config->timeout_sec == TIMEOUT_MENU_FORCE ? 0 : config->timeout_sec;
bool exit = false, run = true, firmware_setup = false;
int64_t console_mode_initial = ST->ConOut->Mode->Mode, console_mode_efivar_saved = config->console_mode_efivar;
UINTN default_efivar_saved = config->idx_default_efivar;
graphics_mode(false);
ST->ConIn->Reset(ST->ConIn, false);
ST->ConOut->EnableCursor(ST->ConOut, false);
/* draw a single character to make ClearScreen work on some firmware */
Print(L" ");
err = console_set_mode(config->console_mode_efivar != CONSOLE_MODE_KEEP ?
config->console_mode_efivar : config->console_mode);
if (err != EFI_SUCCESS) {
clear_screen(COLOR_NORMAL);
log_error_stall(L"Error switching console mode: %r", err);
}
UINTN line_width = 0, entry_padding = 3;
while (!exit) {
uint64_t key;
if (new_mode) {
console_query_mode(&x_max, &y_max);
/* account for padding+status */
visible_max = y_max - 2;
/* Drawing entries starts at idx_first until idx_last. We want to make
* sure that idx_highlight is centered, but not if we are close to the
* beginning/end of the entry list. Otherwise we would have a half-empty
* screen. */
if (config->entry_count <= visible_max || idx_highlight <= visible_max / 2)
idx_first = 0;
else if (idx_highlight >= config->entry_count - (visible_max / 2))
idx_first = config->entry_count - visible_max;
else
idx_first = idx_highlight - (visible_max / 2);
idx_last = idx_first + visible_max - 1;
/* length of the longest entry */
line_width = 0;
for (UINTN i = 0; i < config->entry_count; i++)
line_width = MAX(line_width, strlen16(config->entries[i]->title_show));
line_width = MIN(line_width + 2 * entry_padding, x_max);
/* offsets to center the entries on the screen */
x_start = (x_max - (line_width)) / 2;
if (config->entry_count < visible_max)
y_start = ((visible_max - config->entry_count) / 2) + 1;
else
y_start = 0;
/* Put status line after the entry list, but give it some breathing room. */
y_status = MIN(y_start + MIN(visible_max, config->entry_count) + 1, y_max - 1);
lines = strv_free(lines);
clearline = mfree(clearline);
separator = mfree(separator);
/* menu entries title lines */
lines = xnew(char16_t *, config->entry_count + 1);
for (UINTN i = 0; i < config->entry_count; i++) {
UINTN j, padding;
lines[i] = xnew(char16_t, line_width + 1);
padding = (line_width - MIN(strlen16(config->entries[i]->title_show), line_width)) / 2;
for (j = 0; j < padding; j++)
lines[i][j] = ' ';
for (UINTN k = 0; config->entries[i]->title_show[k] != '\0' && j < line_width; j++, k++)
lines[i][j] = config->entries[i]->title_show[k];
for (; j < line_width; j++)
lines[i][j] = ' ';
lines[i][line_width] = '\0';
}
lines[config->entry_count] = NULL;
clearline = xnew(char16_t, x_max + 1);
separator = xnew(char16_t, x_max + 1);
for (UINTN i = 0; i < x_max; i++) {
clearline[i] = ' ';
separator[i] = unicode_supported() ? L'─' : L'-';
}
clearline[x_max] = 0;
separator[x_max] = 0;
new_mode = false;
clear = true;
}
if (clear) {
clear_screen(COLOR_NORMAL);
clear = false;
refresh = true;
}
if (refresh) {
for (UINTN i = idx_first; i <= idx_last && i < config->entry_count; i++) {
print_at(x_start, y_start + i - idx_first,
i == idx_highlight ? COLOR_HIGHLIGHT : COLOR_ENTRY,
lines[i]);
if (i == config->idx_default_efivar)
print_at(x_start,
y_start + i - idx_first,
i == idx_highlight ? COLOR_HIGHLIGHT : COLOR_ENTRY,
unicode_supported() ? L" ►" : L"=>");
}
refresh = false;
} else if (highlight) {
print_at(x_start, y_start + idx_highlight_prev - idx_first, COLOR_ENTRY, lines[idx_highlight_prev]);
print_at(x_start, y_start + idx_highlight - idx_first, COLOR_HIGHLIGHT, lines[idx_highlight]);
if (idx_highlight_prev == config->idx_default_efivar)
print_at(x_start,
y_start + idx_highlight_prev - idx_first,
COLOR_ENTRY,
unicode_supported() ? L" ►" : L"=>");
if (idx_highlight == config->idx_default_efivar)
print_at(x_start,
y_start + idx_highlight - idx_first,
COLOR_HIGHLIGHT,
unicode_supported() ? L" ►" : L"=>");
highlight = false;
}
if (timeout_remain > 0) {
free(status);
status = xpool_print(L"Boot in %u s.", timeout_remain);
}
if (status) {
/* If we draw the last char of the last line, the screen will scroll and break our
* input. Therefore, draw one less character then we could for the status message.
* Note that the same does not apply for the separator line as it will never be drawn
* on the last line. */
UINTN len = strnlen16(status, x_max - 1);
UINTN x = (x_max - len) / 2;
status[len] = '\0';
print_at(0, y_status, COLOR_NORMAL, clearline + x_max - x);
ST->ConOut->OutputString(ST->ConOut, status);
ST->ConOut->OutputString(ST->ConOut, clearline + 1 + x + len);
len = MIN(MAX(len, line_width) + 2 * entry_padding, x_max);
x = (x_max - len) / 2;
print_at(x, y_status - 1, COLOR_NORMAL, separator + x_max - len);
} else {
print_at(0, y_status - 1, COLOR_NORMAL, clearline);
print_at(0, y_status, COLOR_NORMAL, clearline + 1); /* See comment above. */
}
/* Beep several times so that the selected entry can be distinguished. */
if (config->beep)
beep(idx_highlight + 1);
err = console_key_read(&key, timeout_remain > 0 ? 1000 * 1000 : UINT64_MAX);
if (err == EFI_NOT_READY)
/* No input device returned a key, try again. This
* normally should not happen. */
continue;
if (err == EFI_TIMEOUT) {
assert(timeout_remain > 0);
timeout_remain--;
if (timeout_remain == 0) {
exit = true;
break;
}
/* update status */
continue;
}
if (err != EFI_SUCCESS) {
exit = true;
break;
}
timeout_remain = 0;
/* clear status after keystroke */
status = mfree(status);
idx_highlight_prev = idx_highlight;
if (firmware_setup) {
firmware_setup = false;
if (key == KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN))
reboot_into_firmware();
continue;
}
switch (key) {
case KEYPRESS(0, SCAN_UP, 0):
case KEYPRESS(0, 0, 'k'):
case KEYPRESS(0, 0, 'K'):
if (idx_highlight > 0)
idx_highlight--;
break;
case KEYPRESS(0, SCAN_DOWN, 0):
case KEYPRESS(0, 0, 'j'):
case KEYPRESS(0, 0, 'J'):
if (idx_highlight < config->entry_count-1)
idx_highlight++;
break;
case KEYPRESS(0, SCAN_HOME, 0):
case KEYPRESS(EFI_ALT_PRESSED, 0, '<'):
if (idx_highlight > 0) {
refresh = true;
idx_highlight = 0;
}
break;
case KEYPRESS(0, SCAN_END, 0):
case KEYPRESS(EFI_ALT_PRESSED, 0, '>'):
if (idx_highlight < config->entry_count-1) {
refresh = true;
idx_highlight = config->entry_count-1;
}
break;
case KEYPRESS(0, SCAN_PAGE_UP, 0):
if (idx_highlight > visible_max)
idx_highlight -= visible_max;
else
idx_highlight = 0;
break;
case KEYPRESS(0, SCAN_PAGE_DOWN, 0):
idx_highlight += visible_max;
if (idx_highlight > config->entry_count-1)
idx_highlight = config->entry_count-1;
break;
case KEYPRESS(0, 0, CHAR_LINEFEED):
case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
case KEYPRESS(0, SCAN_F3, 0): /* EZpad Mini 4s firmware sends malformed events */
case KEYPRESS(0, SCAN_F3, CHAR_CARRIAGE_RETURN): /* Teclast X98+ II firmware sends malformed events */
case KEYPRESS(0, SCAN_RIGHT, 0):
exit = true;
break;
case KEYPRESS(0, SCAN_F1, 0):
case KEYPRESS(0, 0, 'h'):
case KEYPRESS(0, 0, 'H'):
case KEYPRESS(0, 0, '?'):
/* This must stay below 80 characters! Q/v/Ctrl+l/f deliberately not advertised. */
status = xstrdup16(u"(d)efault (t/T)timeout (e)dit (r/R)resolution (p)rint (h)elp");
break;
case KEYPRESS(0, 0, 'Q'):
exit = true;
run = false;
break;
case KEYPRESS(0, 0, 'd'):
case KEYPRESS(0, 0, 'D'):
if (config->idx_default_efivar != idx_highlight) {
free(config->entry_default_efivar);
config->entry_default_efivar = xstrdup16(config->entries[idx_highlight]->id);
config->idx_default_efivar = idx_highlight;
status = xstrdup16(u"Default boot entry selected.");
} else {
config->entry_default_efivar = mfree(config->entry_default_efivar);
config->idx_default_efivar = IDX_INVALID;
status = xstrdup16(u"Default boot entry cleared.");
}
config->use_saved_entry_efivar = false;
refresh = true;
break;
case KEYPRESS(0, 0, '-'):
case KEYPRESS(0, 0, 'T'):
status = update_timeout_efivar(&config->timeout_sec_efivar, false);
break;
case KEYPRESS(0, 0, '+'):
case KEYPRESS(0, 0, 't'):
status = update_timeout_efivar(&config->timeout_sec_efivar, true);
break;
case KEYPRESS(0, 0, 'e'):
case KEYPRESS(0, 0, 'E'):
/* only the options of configured entries can be edited */
if (!config->editor ||
!IN_SET(config->entries[idx_highlight]->type, LOADER_EFI, LOADER_LINUX, LOADER_UNIFIED_LINUX)) {
status = xstrdup16(u"Entry does not support editing the command line.");
break;
}
/* Unified kernels that are signed as a whole will not accept command line options
* when secure boot is enabled unless there is none embedded in the image. Do not try
* to pretend we can edit it to only have it be ignored. */
if (config->entries[idx_highlight]->type == LOADER_UNIFIED_LINUX &&
secure_boot_enabled() &&
config->entries[idx_highlight]->options) {
status = xstrdup16(u"Entry not editable in SecureBoot mode.");
break;
}
/* The edit line may end up on the last line of the screen. And even though we're
* not telling the firmware to advance the line, it still does in this one case,
* causing a scroll to happen that screws with our beautiful boot loader output.
* Since we cannot paint the last character of the edit line, we simply start
* at x-offset 1 for symmetry. */
print_at(1, y_status, COLOR_EDIT, clearline + 2);
exit = line_edit(&config->entries[idx_highlight]->options, x_max - 2, y_status);
print_at(1, y_status, COLOR_NORMAL, clearline + 2);
break;
case KEYPRESS(0, 0, 'v'):
status = xpool_print(
L"systemd-boot " GIT_VERSION L" (" EFI_MACHINE_TYPE_NAME L"), "
L"UEFI Specification %u.%02u, Vendor %s %u.%02u",
ST->Hdr.Revision >> 16,
ST->Hdr.Revision & 0xffff,
ST->FirmwareVendor,
ST->FirmwareRevision >> 16,
ST->FirmwareRevision & 0xffff);
break;
case KEYPRESS(0, 0, 'p'):
case KEYPRESS(0, 0, 'P'):
print_status(config, loaded_image_path);
clear = true;
break;
case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'l'):
case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('l')):
clear = true;
break;
case KEYPRESS(0, 0, 'r'):
err = console_set_mode(CONSOLE_MODE_NEXT);
if (err != EFI_SUCCESS)
status = xpool_print(L"Error changing console mode: %r", err);
else {
config->console_mode_efivar = ST->ConOut->Mode->Mode;
status = xpool_print(L"Console mode changed to %ld.", config->console_mode_efivar);
}
new_mode = true;
break;
case KEYPRESS(0, 0, 'R'):
config->console_mode_efivar = CONSOLE_MODE_KEEP;
err = console_set_mode(config->console_mode == CONSOLE_MODE_KEEP ?
console_mode_initial : config->console_mode);
if (err != EFI_SUCCESS)
status = xpool_print(L"Error resetting console mode: %r", err);
else
status = xpool_print(L"Console mode reset to %s default.",
config->console_mode == CONSOLE_MODE_KEEP ? L"firmware" : L"configuration file");
new_mode = true;
break;
case KEYPRESS(0, 0, 'f'):
case KEYPRESS(0, 0, 'F'):
case KEYPRESS(0, SCAN_F2, 0): /* Most vendors. */
case KEYPRESS(0, SCAN_F10, 0): /* HP and Lenovo. */
case KEYPRESS(0, SCAN_DELETE, 0): /* Same as F2. */
case KEYPRESS(0, SCAN_ESC, 0): /* HP. */
if (FLAGS_SET(get_os_indications_supported(), EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
firmware_setup = true;
/* Let's make sure the user really wants to do this. */
status = xpool_print(L"Press Enter to reboot into firmware interface.");
} else
status = xpool_print(L"Reboot into firmware interface not supported.");
break;
default:
/* jump with a hotkey directly to a matching entry */
idx = entry_lookup_key(config, idx_highlight+1, KEYCHAR(key));
if (idx == IDX_INVALID)
break;
idx_highlight = idx;
refresh = true;
}
if (idx_highlight > idx_last) {
idx_last = idx_highlight;
idx_first = 1 + idx_highlight - visible_max;
refresh = true;
} else if (idx_highlight < idx_first) {
idx_first = idx_highlight;
idx_last = idx_highlight + visible_max-1;
refresh = true;
}
if (!refresh && idx_highlight != idx_highlight_prev)
highlight = true;
}
*chosen_entry = config->entries[idx_highlight];
/* Update EFI vars after we left the menu to reduce NVRAM writes. */
if (default_efivar_saved != config->idx_default_efivar)
efivar_set(LOADER_GUID, L"LoaderEntryDefault", config->entry_default_efivar, EFI_VARIABLE_NON_VOLATILE);
if (console_mode_efivar_saved != config->console_mode_efivar) {
if (config->console_mode_efivar == CONSOLE_MODE_KEEP)
efivar_set(LOADER_GUID, L"LoaderConfigConsoleMode", NULL, EFI_VARIABLE_NON_VOLATILE);
else
efivar_set_uint_string(LOADER_GUID, L"LoaderConfigConsoleMode",
config->console_mode_efivar, EFI_VARIABLE_NON_VOLATILE);
}
if (timeout_efivar_saved != config->timeout_sec_efivar) {
switch (config->timeout_sec_efivar) {
case TIMEOUT_UNSET:
efivar_set(LOADER_GUID, L"LoaderConfigTimeout", NULL, EFI_VARIABLE_NON_VOLATILE);
break;
case TIMEOUT_MENU_FORCE:
efivar_set(LOADER_GUID, u"LoaderConfigTimeout", u"menu-force", EFI_VARIABLE_NON_VOLATILE);
break;
case TIMEOUT_MENU_HIDDEN:
efivar_set(LOADER_GUID, u"LoaderConfigTimeout", u"menu-hidden", EFI_VARIABLE_NON_VOLATILE);
break;
default:
efivar_set_uint_string(LOADER_GUID, L"LoaderConfigTimeout",
config->timeout_sec_efivar, EFI_VARIABLE_NON_VOLATILE);
}
}
clear_screen(COLOR_NORMAL);
return run;
}
static void config_add_entry(Config *config, ConfigEntry *entry) {
assert(config);
assert(entry);
/* This is just for paranoia. */
assert(config->entry_count < IDX_MAX);
if ((config->entry_count & 15) == 0) {
config->entries = xrealloc(
config->entries,
sizeof(void *) * config->entry_count,
sizeof(void *) * (config->entry_count + 16));
}
config->entries[config->entry_count++] = entry;
}
static void config_entry_free(ConfigEntry *entry) {
if (!entry)
return;
free(entry->id);
free(entry->title_show);
free(entry->title);
free(entry->sort_key);
free(entry->version);
free(entry->machine_id);
free(entry->loader);
free(entry->devicetree);
free(entry->options);
strv_free(entry->initrd);
free(entry->path);
free(entry->current_name);
free(entry->next_name);
free(entry);
}
static inline void config_entry_freep(ConfigEntry **entry) {
config_entry_free(*entry);
}
static char *line_get_key_value(
char *content,
const char *sep,
UINTN *pos,
char **key_ret,
char **value_ret) {
char *line, *value;
UINTN linelen;
assert(content);
assert(sep);
assert(pos);
assert(key_ret);
assert(value_ret);
for (;;) {
line = content + *pos;
if (*line == '\0')
return NULL;
linelen = 0;
while (line[linelen] && !strchr8("\n\r", line[linelen]))
linelen++;
/* move pos to next line */
*pos += linelen;
if (content[*pos])
(*pos)++;
/* empty line */
if (linelen == 0)
continue;
/* terminate line */
line[linelen] = '\0';
/* remove leading whitespace */
while (linelen > 0 && strchr8(" \t", *line)) {
line++;
linelen--;
}
/* remove trailing whitespace */
while (linelen > 0 && strchr8(" \t", line[linelen - 1]))
linelen--;
line[linelen] = '\0';
if (*line == '#')
continue;
/* split key/value */
value = line;
while (*value && !strchr8(sep, *value))
value++;
if (*value == '\0')
continue;
*value = '\0';
value++;
while (*value && strchr8(sep, *value))
value++;
/* unquote */
if (value[0] == '"' && line[linelen - 1] == '"') {
value++;
line[linelen - 1] = '\0';
}
*key_ret = line;
*value_ret = value;
return line;
}
}
static void config_defaults_load_from_file(Config *config, char *content) {
char *line;
UINTN pos = 0;
char *key, *value;
EFI_STATUS err;
assert(config);
assert(content);
while ((line = line_get_key_value(content, " \t", &pos, &key, &value))) {
if (streq8(key, "timeout")) {
if (streq8( value, "menu-force"))
config->timeout_sec_config = TIMEOUT_MENU_FORCE;
else if (streq8(value, "menu-hidden"))
config->timeout_sec_config = TIMEOUT_MENU_HIDDEN;
else {
uint64_t u;
if (!parse_number8(value, &u, NULL) || u > TIMEOUT_TYPE_MAX) {
log_error_stall(L"Error parsing 'timeout' config option: %a", value);
continue;
}
config->timeout_sec_config = u;
}
config->timeout_sec = config->timeout_sec_config;
continue;
}
if (streq8(key, "default")) {
if (value[0] == '@' && !strcaseeq8(value, "@saved")) {
log_error_stall(L"Unsupported special entry identifier: %a", value);
continue;
}
free(config->entry_default_config);
config->entry_default_config = xstr8_to_16(value);
continue;
}
if (streq8(key, "editor")) {
err = parse_boolean(value, &config->editor);
if (err != EFI_SUCCESS)
log_error_stall(L"Error parsing 'editor' config option: %a", value);
continue;
}
if (streq8(key, "auto-entries")) {
err = parse_boolean(value, &config->auto_entries);
if (err != EFI_SUCCESS)
log_error_stall(L"Error parsing 'auto-entries' config option: %a", value);
continue;
}
if (streq8(key, "auto-firmware")) {
err = parse_boolean(value, &config->auto_firmware);
if (err != EFI_SUCCESS)
log_error_stall(L"Error parsing 'auto-firmware' config option: %a", value);
continue;
}
if (streq8(key, "beep")) {
err = parse_boolean(value, &config->beep);
if (err != EFI_SUCCESS)
log_error_stall(L"Error parsing 'beep' config option: %a", value);
continue;
}
if (streq8(key, "reboot-for-bitlocker")) {
err = parse_boolean(value, &config->reboot_for_bitlocker);
if (err != EFI_SUCCESS)
log_error_stall(L"Error parsing 'reboot-for-bitlocker' config option: %a", value);
}
if (streq8(key, "secure-boot-enroll")) {
if (streq8(value, "manual"))
config->secure_boot_enroll = ENROLL_MANUAL;
else if (streq8(value, "force"))
config->secure_boot_enroll = ENROLL_FORCE;
else if (streq8(value, "off"))
config->secure_boot_enroll = ENROLL_OFF;
else
log_error_stall(L"Error parsing 'secure-boot-enroll' config option: %a", value);
continue;
}
if (streq8(key, "console-mode")) {
if (streq8(value, "auto"))
config->console_mode = CONSOLE_MODE_AUTO;
else if (streq8(value, "max"))
config->console_mode = CONSOLE_MODE_FIRMWARE_MAX;
else if (streq8(value, "keep"))
config->console_mode = CONSOLE_MODE_KEEP;
else {
uint64_t u;
if (!parse_number8(value, &u, NULL) || u > CONSOLE_MODE_RANGE_MAX) {
log_error_stall(L"Error parsing 'console-mode' config option: %a", value);
continue;
}
config->console_mode = u;
}
continue;
}
if (streq8(key, "random-seed-mode")) {
if (streq8(value, "off"))
config->random_seed_mode = RANDOM_SEED_OFF;
else if (streq8(value, "with-system-token"))
config->random_seed_mode = RANDOM_SEED_WITH_SYSTEM_TOKEN;
else if (streq8(value, "always"))
config->random_seed_mode = RANDOM_SEED_ALWAYS;
else {
bool on;
err = parse_boolean(value, &on);
if (err != EFI_SUCCESS) {
log_error_stall(L"Error parsing 'random-seed-mode' config option: %a", value);
continue;
}
config->random_seed_mode = on ? RANDOM_SEED_ALWAYS : RANDOM_SEED_OFF;
}
continue;
}
}
}
static void config_entry_parse_tries(
ConfigEntry *entry,
const char16_t *path,
const char16_t *file,
const char16_t *suffix) {
assert(entry);
assert(path);
assert(file);
assert(suffix);
/*
* Parses a suffix of two counters (one going down, one going up) in the form "+LEFT-DONE" from the end of the
* filename (but before the .efi/.conf suffix), where the "-DONE" part is optional and may be left out (in
* which case that counter as assumed to be zero, i.e. the missing part is synonymous to "-0").
*
* Names we grok, and the series they result in:
*
* foobar+3.efi → foobar+2-1.efi → foobar+1-2.efi → foobar+0-3.efi → STOP!
* foobar+4-0.efi → foobar+3-1.efi → foobar+2-2.efi → foobar+1-3.efi → foobar+0-4.efi → STOP!
*/
const char16_t *counter = NULL;
for (;;) {
char16_t *plus = strchr16(counter ?: file, '+');
if (plus) {
/* We want the last "+". */
counter = plus + 1;
continue;
}
if (counter)
break;
/* No boot counter found. */
return;
}
uint64_t tries_left, tries_done = 0;
size_t prefix_len = counter - file;
if (!parse_number16(counter, &tries_left, &counter) || tries_left > INT_MAX)
return;
/* Parse done counter only if present. */
if (*counter == '-' && (!parse_number16(counter + 1, &tries_done, &counter) || tries_done > INT_MAX))
return;
/* Boot counter in the middle of the name? */
if (!streq16(counter, suffix))
return;
entry->tries_left = tries_left;
entry->tries_done = tries_done;
entry->path = xstrdup16(path);
entry->current_name = xstrdup16(file);
entry->next_name = xpool_print(
L"%.*s%u-%u%s",
prefix_len,
file,
LESS_BY(tries_left, 1u),
MIN(tries_done + 1, (uint64_t) INT_MAX),
suffix);
}
static EFI_STATUS config_entry_bump_counters(ConfigEntry *entry) {
_cleanup_free_ char16_t* old_path = NULL, *new_path = NULL;
_cleanup_(file_closep) EFI_FILE *handle = NULL;
_cleanup_free_ EFI_FILE_INFO *file_info = NULL;
UINTN file_info_size;
EFI_STATUS err;
assert(entry);
if (entry->tries_left < 0)
return EFI_SUCCESS;
if (!entry->path || !entry->current_name || !entry->next_name)
return EFI_SUCCESS;
_cleanup_(file_closep) EFI_FILE *root = NULL;
err = open_volume(entry->device, &root);
if (err != EFI_SUCCESS) {
log_error_stall(L"Error opening entry root path: %r", err);
return err;
}
old_path = xpool_print(L"%s\\%s", entry->path, entry->current_name);
err = root->Open(root, &handle, old_path, EFI_FILE_MODE_READ|EFI_FILE_MODE_WRITE, 0ULL);
if (err != EFI_SUCCESS) {
log_error_stall(L"Error opening boot entry: %r", err);
return err;
}
err = get_file_info_harder(handle, &file_info, &file_info_size);
if (err != EFI_SUCCESS) {
log_error_stall(L"Error getting boot entry file info: %r", err);
return err;
}
/* And rename the file */
strcpy16(file_info->FileName, entry->next_name);
err = handle->SetInfo(handle, &GenericFileInfo, file_info_size, file_info);
if (err != EFI_SUCCESS) {
log_error_stall(L"Failed to rename '%s' to '%s', ignoring: %r", old_path, entry->next_name, err);
return err;
}
/* Flush everything to disk, just in case… */
err = handle->Flush(handle);
if (err != EFI_SUCCESS) {
log_error_stall(L"Error flushing boot entry file info: %r", err);
return err;
}
/* Let's tell the OS that we renamed this file, so that it knows what to rename to the counter-less name on
* success */
new_path = xpool_print(L"%s\\%s", entry->path, entry->next_name);
efivar_set(LOADER_GUID, L"LoaderBootCountPath", new_path, 0);
/* If the file we just renamed is the loader path, then let's update that. */
if (streq16(entry->loader, old_path)) {
free(entry->loader);
entry->loader = TAKE_PTR(new_path);
}
return EFI_SUCCESS;
}
static void config_entry_add_type1(
Config *config,
EFI_HANDLE *device,
EFI_FILE *root_dir,
const char16_t *path,
const char16_t *file,
char *content,
const char16_t *loaded_image_path) {
_cleanup_(config_entry_freep) ConfigEntry *entry = NULL;
char *line;
UINTN pos = 0, n_initrd = 0;
char *key, *value;
EFI_STATUS err;
assert(config);
assert(device);
assert(root_dir);
assert(path);
assert(file);
assert(content);
entry = xnew(ConfigEntry, 1);
*entry = (ConfigEntry) {
.tries_done = -1,
.tries_left = -1,
};
while ((line = line_get_key_value(content, " \t", &pos, &key, &value))) {
if (streq8(key, "title")) {
free(entry->title);
entry->title = xstr8_to_16(value);
continue;
}
if (streq8(key, "sort-key")) {
free(entry->sort_key);
entry->sort_key = xstr8_to_16(value);
continue;
}
if (streq8(key, "version")) {
free(entry->version);
entry->version = xstr8_to_16(value);
continue;
}
if (streq8(key, "machine-id")) {
free(entry->machine_id);
entry->machine_id = xstr8_to_16(value);
continue;
}
if (streq8(key, "linux")) {
free(entry->loader);
entry->type = LOADER_LINUX;
entry->loader = xstr8_to_path(value);
entry->key = 'l';
continue;
}
if (streq8(key, "efi")) {
entry->type = LOADER_EFI;
free(entry->loader);
entry->loader = xstr8_to_path(value);
/* do not add an entry for ourselves */
if (strcaseeq16(entry->loader, loaded_image_path)) {
entry->type = LOADER_UNDEFINED;
break;
}
continue;
}
if (streq8(key, "architecture")) {
/* do not add an entry for an EFI image of architecture not matching with that of the image */
if (!streq8(value, EFI_MACHINE_TYPE_NAME)) {
entry->type = LOADER_UNDEFINED;
break;
}
continue;
}
if (streq8(key, "devicetree")) {
free(entry->devicetree);
entry->devicetree = xstr8_to_path(value);
continue;
}
if (streq8(key, "initrd")) {
entry->initrd = xrealloc(
entry->initrd,
n_initrd == 0 ? 0 : (n_initrd + 1) * sizeof(uint16_t *),
(n_initrd + 2) * sizeof(uint16_t *));
entry->initrd[n_initrd++] = xstr8_to_path(value);
entry->initrd[n_initrd] = NULL;
continue;
}
if (streq8(key, "options")) {
_cleanup_free_ char16_t *new = NULL;
new = xstr8_to_16(value);
if (entry->options) {
char16_t *s = xpool_print(L"%s %s", entry->options, new);
free(entry->options);
entry->options = s;
} else
entry->options = TAKE_PTR(new);
continue;
}
}
if (entry->type == LOADER_UNDEFINED)
return;
/* check existence */
_cleanup_(file_closep) EFI_FILE *handle = NULL;
err = root_dir->Open(root_dir, &handle, entry->loader, EFI_FILE_MODE_READ, 0ULL);
if (err != EFI_SUCCESS)
return;
entry->device = device;
entry->id = xstrdup16(file);
strtolower16(entry->id);
config_add_entry(config, entry);
config_entry_parse_tries(entry, path, file, L".conf");
TAKE_PTR(entry);
}
static EFI_STATUS efivar_get_timeout(const char16_t *var, uint32_t *ret_value) {
_cleanup_free_ char16_t *value = NULL;
EFI_STATUS err;
assert(var);
assert(ret_value);
err = efivar_get(LOADER_GUID, var, &value);
if (err != EFI_SUCCESS)
return err;
if (streq16(value, u"menu-force")) {
*ret_value = TIMEOUT_MENU_FORCE;
return EFI_SUCCESS;
}
if (streq16(value, u"menu-hidden")) {
*ret_value = TIMEOUT_MENU_HIDDEN;
return EFI_SUCCESS;
}
uint64_t timeout;
if (!parse_number16(value, &timeout, NULL))
return EFI_INVALID_PARAMETER;
*ret_value = MIN(timeout, TIMEOUT_TYPE_MAX);
return EFI_SUCCESS;
}
static void config_load_defaults(Config *config, EFI_FILE *root_dir) {
_cleanup_free_ char *content = NULL;
UINTN value = 0; /* avoid false maybe-uninitialized warning */
EFI_STATUS err;
assert(root_dir);
*config = (Config) {
.editor = true,
.auto_entries = true,
.auto_firmware = true,
.reboot_for_bitlocker = false,
.secure_boot_enroll = ENROLL_MANUAL,
.random_seed_mode = RANDOM_SEED_WITH_SYSTEM_TOKEN,
.idx_default_efivar = IDX_INVALID,
.console_mode = CONSOLE_MODE_KEEP,
.console_mode_efivar = CONSOLE_MODE_KEEP,
.timeout_sec_config = TIMEOUT_UNSET,
.timeout_sec_efivar = TIMEOUT_UNSET,
};
err = file_read(root_dir, L"\\loader\\loader.conf", 0, 0, &content, NULL);
if (err == EFI_SUCCESS)
config_defaults_load_from_file(config, content);
err = efivar_get_timeout(u"LoaderConfigTimeout", &config->timeout_sec_efivar);
if (err == EFI_SUCCESS)
config->timeout_sec = config->timeout_sec_efivar;
else if (err != EFI_NOT_FOUND)
log_error_stall(u"Error reading LoaderConfigTimeout EFI variable: %r", err);
err = efivar_get_timeout(u"LoaderConfigTimeoutOneShot", &config->timeout_sec);
if (err == EFI_SUCCESS) {
/* Unset variable now, after all it's "one shot". */
(void) efivar_set(LOADER_GUID, L"LoaderConfigTimeoutOneShot", NULL, EFI_VARIABLE_NON_VOLATILE);
config->force_menu = true; /* force the menu when this is set */
} else if (err != EFI_NOT_FOUND)
log_error_stall(u"Error reading LoaderConfigTimeoutOneShot EFI variable: %r", err);
err = efivar_get_uint_string(LOADER_GUID, L"LoaderConfigConsoleMode", &value);
if (err == EFI_SUCCESS)
config->console_mode_efivar = value;
err = efivar_get(LOADER_GUID, L"LoaderEntryOneShot", &config->entry_oneshot);
if (err == EFI_SUCCESS)
/* Unset variable now, after all it's "one shot". */
(void) efivar_set(LOADER_GUID, L"LoaderEntryOneShot", NULL, EFI_VARIABLE_NON_VOLATILE);
(void) efivar_get(LOADER_GUID, L"LoaderEntryDefault", &config->entry_default_efivar);
strtolower16(config->entry_default_config);
strtolower16(config->entry_default_efivar);
strtolower16(config->entry_oneshot);
strtolower16(config->entry_saved);
config->use_saved_entry = streq16(config->entry_default_config, L"@saved");
config->use_saved_entry_efivar = streq16(config->entry_default_efivar, L"@saved");
if (config->use_saved_entry || config->use_saved_entry_efivar)
(void) efivar_get(LOADER_GUID, L"LoaderEntryLastBooted", &config->entry_saved);
}
static void config_load_entries(
Config *config,
EFI_HANDLE *device,
EFI_FILE *root_dir,
const char16_t *loaded_image_path) {
_cleanup_(file_closep) EFI_FILE *entries_dir = NULL;
_cleanup_free_ EFI_FILE_INFO *f = NULL;
UINTN f_size = 0;
EFI_STATUS err;
assert(config);
assert(device);
assert(root_dir);
/* Adds Boot Loader Type #1 entries (i.e. /loader/entries/….conf) */
err = open_directory(root_dir, L"\\loader\\entries", &entries_dir);
if (err != EFI_SUCCESS)
return;
for (;;) {
_cleanup_free_ char *content = NULL;
err = readdir_harder(entries_dir, &f, &f_size);
if (err != EFI_SUCCESS || !f)
break;
if (f->FileName[0] == '.')
continue;
if (FLAGS_SET(f->Attribute, EFI_FILE_DIRECTORY))
continue;
if (!endswith_no_case(f->FileName, L".conf"))
continue;
if (startswith(f->FileName, L"auto-"))
continue;
err = file_read(entries_dir, f->FileName, 0, 0, &content, NULL);
if (err == EFI_SUCCESS)
config_entry_add_type1(config, device, root_dir, L"\\loader\\entries", f->FileName, content, loaded_image_path);
}
}
static int config_entry_compare(const ConfigEntry *a, const ConfigEntry *b) {
int r;
assert(a);
assert(b);
/* Order entries that have no tries left to the end of the list */
r = CMP(a->tries_left == 0, b->tries_left == 0);
if (r != 0)
return r;
/* If there's a sort key defined for *both* entries, then we do new-style ordering, i.e. by
* sort-key/machine-id/version, with a final fallback to id. If there's no sort key for either, we do
* old-style ordering, i.e. by id only. If one has sort key and the other does not, we put new-style
* before old-style. */
r = CMP(!a->sort_key, !b->sort_key);
if (r != 0) /* one is old-style, one new-style */
return r;
if (a->sort_key && b->sort_key) {
r = strcmp16(a->sort_key, b->sort_key);
if (r != 0)
return r;
/* If multiple installations of the same OS are around, group by machine ID */
r = strcmp16(a->machine_id, b->machine_id);
if (r != 0)
return r;
/* If the sort key was defined, then order by version now (downwards, putting the newest first) */
r = -strverscmp_improved(a->version, b->version);
if (r != 0)
return r;
}
/* Now order by ID. The version is likely part of the ID, thus note that this will generatelly put
* the newer versions earlier. Specifying a sort key explicitly is preferable, because it gives an
* explicit sort order. */
r = -strverscmp_improved(a->id, b->id);
if (r != 0)
return r;
if (a->tries_left < 0 || b->tries_left < 0)
return 0;
/* If both items have boot counting, and otherwise are identical, put the entry with more tries left first */
r = -CMP(a->tries_left, b->tries_left);
if (r != 0)
return r;
/* If they have the same number of tries left, then let the one win which was tried fewer times so far */
return CMP(a->tries_done, b->tries_done);
}
static UINTN config_entry_find(Config *config, const char16_t *pattern) {
assert(config);
/* We expect pattern and entry IDs to be already case folded. */
if (!pattern)
return IDX_INVALID;
for (UINTN i = 0; i < config->entry_count; i++)
if (efi_fnmatch(pattern, config->entries[i]->id))
return i;
return IDX_INVALID;
}
static void config_default_entry_select(Config *config) {
UINTN i;
assert(config);
i = config_entry_find(config, config->entry_oneshot);
if (i != IDX_INVALID) {
config->idx_default = i;
return;
}
i = config_entry_find(config, config->use_saved_entry_efivar ? config->entry_saved : config->entry_default_efivar);
if (i != IDX_INVALID) {
config->idx_default = i;
config->idx_default_efivar = i;
return;
}
if (config->use_saved_entry)
/* No need to do the same thing twice. */
i = config->use_saved_entry_efivar ? IDX_INVALID : config_entry_find(config, config->entry_saved);
else
i = config_entry_find(config, config->entry_default_config);
if (i != IDX_INVALID) {
config->idx_default = i;
return;
}
/* select the first suitable entry */
for (i = 0; i < config->entry_count; i++) {
if (config->entries[i]->type == LOADER_AUTO || config->entries[i]->call)
continue;
config->idx_default = i;
return;
}
/* If no configured entry to select from was found, enable the menu. */
config->idx_default = 0;
if (config->timeout_sec == 0)
config->timeout_sec = 10;
}
static bool entries_unique(ConfigEntry **entries, bool *unique, UINTN entry_count) {
bool is_unique = true;
assert(entries);
assert(unique);
for (UINTN i = 0; i < entry_count; i++)
for (UINTN k = i + 1; k < entry_count; k++) {
if (!streq16(entries[i]->title_show, entries[k]->title_show))
continue;
is_unique = unique[i] = unique[k] = false;
}
return is_unique;
}
/* generate a unique title, avoiding non-distinguishable menu entries */
static void config_title_generate(Config *config) {
assert(config);
bool unique[config->entry_count];
/* set title */
for (UINTN i = 0; i < config->entry_count; i++) {
assert(!config->entries[i]->title_show);
unique[i] = true;
config->entries[i]->title_show = xstrdup16(config->entries[i]->title ?: config->entries[i]->id);
}
if (entries_unique(config->entries, unique, config->entry_count))
return;
/* add version to non-unique titles */
for (UINTN i = 0; i < config->entry_count; i++) {
if (unique[i])
continue;
unique[i] = true;
if (!config->entries[i]->version)
continue;
_cleanup_free_ char16_t *t = config->entries[i]->title_show;
config->entries[i]->title_show = xpool_print(L"%s (%s)", t, config->entries[i]->version);
}
if (entries_unique(config->entries, unique, config->entry_count))
return;
/* add machine-id to non-unique titles */
for (UINTN i = 0; i < config->entry_count; i++) {
if (unique[i])
continue;
unique[i] = true;
if (!config->entries[i]->machine_id)
continue;
_cleanup_free_ char16_t *t = config->entries[i]->title_show;
config->entries[i]->title_show = xpool_print(
L"%s (%.*s)",
t,
strnlen16(config->entries[i]->machine_id, 8),
config->entries[i]->machine_id);
}
if (entries_unique(config->entries, unique, config->entry_count))
return;
/* add file name to non-unique titles */
for (UINTN i = 0; i < config->entry_count; i++) {
if (unique[i])
continue;
_cleanup_free_ char16_t *t = config->entries[i]->title_show;
config->entries[i]->title_show = xpool_print(L"%s (%s)", t, config->entries[i]->id);
}
}
static bool is_sd_boot(EFI_FILE *root_dir, const char16_t *loader_path) {
EFI_STATUS err;
static const char * const sections[] = {
".sdmagic",
NULL
};
UINTN offset = 0, size = 0, read;
_cleanup_free_ char *content = NULL;
assert(root_dir);
assert(loader_path);
err = pe_file_locate_sections(root_dir, loader_path, sections, &offset, &size);
if (err != EFI_SUCCESS || size != sizeof(magic))
return false;
err = file_read(root_dir, loader_path, offset, size, &content, &read);
if (err != EFI_SUCCESS || size != read)
return false;
return memcmp(content, magic, sizeof(magic)) == 0;
}
static ConfigEntry *config_entry_add_loader_auto(
Config *config,
EFI_HANDLE *device,
EFI_FILE *root_dir,
const char16_t *loaded_image_path,
const char16_t *id,
char16_t key,
const char16_t *title,
const char16_t *loader) {
assert(config);
assert(device);
assert(root_dir);
assert(id);
assert(title);
if (!config->auto_entries)
return NULL;
if (!loader) {
loader = L"\\EFI\\BOOT\\BOOT" EFI_MACHINE_TYPE_NAME ".efi";
/* We are trying to add the default EFI loader here,
* but we do not want to do that if that would be us.
*
* If the default loader is not us, it might be shim. It would
* chainload GRUBX64.EFI in that case, which might be us.*/
if (strcaseeq16(loader, loaded_image_path) ||
is_sd_boot(root_dir, loader) ||
is_sd_boot(root_dir, L"\\EFI\\BOOT\\GRUB" EFI_MACHINE_TYPE_NAME L".EFI"))
return NULL;
}
/* check existence */
_cleanup_(file_closep) EFI_FILE *handle = NULL;
EFI_STATUS err = root_dir->Open(root_dir, &handle, (char16_t *) loader, EFI_FILE_MODE_READ, 0ULL);
if (err != EFI_SUCCESS)
return NULL;
ConfigEntry *entry = xnew(ConfigEntry, 1);
*entry = (ConfigEntry) {
.id = xstrdup16(id),
.type = LOADER_AUTO,
.title = xstrdup16(title),
.device = device,
.loader = xstrdup16(loader),
.key = key,
.tries_done = -1,
.tries_left = -1,
};
config_add_entry(config, entry);
return entry;
}
static void config_entry_add_osx(Config *config) {
EFI_STATUS err;
UINTN n_handles = 0;
_cleanup_free_ EFI_HANDLE *handles = NULL;
assert(config);
if (!config->auto_entries)
return;
err = BS->LocateHandleBuffer(ByProtocol, &FileSystemProtocol, NULL, &n_handles, &handles);
if (err != EFI_SUCCESS)
return;
for (UINTN i = 0; i < n_handles; i++) {
_cleanup_(file_closep) EFI_FILE *root = NULL;
if (open_volume(handles[i], &root) != EFI_SUCCESS)
continue;
if (config_entry_add_loader_auto(
config,
handles[i],
root,
NULL,
L"auto-osx",
'a',
L"macOS",
L"\\System\\Library\\CoreServices\\boot.efi"))
break;
}
}
static EFI_STATUS boot_windows_bitlocker(void) {
_cleanup_free_ EFI_HANDLE *handles = NULL;
UINTN n_handles;
EFI_STATUS err;
// FIXME: Experimental for now. Should be generalized, and become a per-entry option that can be
// enabled independently of BitLocker, and without a BootXXXX entry pre-existing.
/* BitLocker key cannot be sealed without a TPM present. */
if (!tpm_present())
return EFI_NOT_FOUND;
err = BS->LocateHandleBuffer(ByProtocol, &BlockIoProtocol, NULL, &n_handles, &handles);
if (err != EFI_SUCCESS)
return err;
/* Look for BitLocker magic string on all block drives. */
bool found = false;
for (UINTN i = 0; i < n_handles; i++) {
EFI_BLOCK_IO_PROTOCOL *block_io;
err = BS->HandleProtocol(handles[i], &BlockIoProtocol, (void **) &block_io);
if (err != EFI_SUCCESS || block_io->Media->BlockSize < 512 || block_io->Media->BlockSize > 4096)
continue;
char buf[4096];
err = block_io->ReadBlocks(block_io, block_io->Media->MediaId, 0, sizeof(buf), buf);
if (err != EFI_SUCCESS)
continue;
if (memcmp(buf + 3, "-FVE-FS-", STRLEN("-FVE-FS-")) == 0) {
found = true;
break;
}
}
/* If no BitLocker drive was found, we can just chainload bootmgfw.efi directly. */
if (!found)
return EFI_NOT_FOUND;
_cleanup_free_ uint16_t *boot_order = NULL;
UINTN boot_order_size;
/* There can be gaps in Boot#### entries. Instead of iterating over the full
* EFI var list or uint16_t namespace, just look for "Windows Boot Manager" in BootOrder. */
err = efivar_get_raw(EFI_GLOBAL_GUID, L"BootOrder", (char **) &boot_order, &boot_order_size);
if (err != EFI_SUCCESS || boot_order_size % sizeof(uint16_t) != 0)
return err;
for (UINTN i = 0; i < boot_order_size / sizeof(uint16_t); i++) {
_cleanup_free_ char *buf = NULL;
char16_t name[sizeof(L"Boot0000")];
UINTN buf_size;
SPrint(name, sizeof(name), L"Boot%04x", (uint32_t) boot_order[i]);
err = efivar_get_raw(EFI_GLOBAL_GUID, name, &buf, &buf_size);
if (err != EFI_SUCCESS)
continue;
/* Boot#### are EFI_LOAD_OPTION. But we really are only interested
* for the description, which is at this offset. */
UINTN offset = sizeof(uint32_t) + sizeof(uint16_t);
if (buf_size < offset + sizeof(char16_t))
continue;
if (streq16((char16_t *) (buf + offset), L"Windows Boot Manager")) {
err = efivar_set_raw(
EFI_GLOBAL_GUID,
L"BootNext",
boot_order + i,
sizeof(boot_order[i]),
EFI_VARIABLE_NON_VOLATILE);
if (err != EFI_SUCCESS)
return err;
RT->ResetSystem(EfiResetWarm, EFI_SUCCESS, 0, NULL);
assert_not_reached();
}
}
return EFI_NOT_FOUND;
}
static void config_entry_add_windows(Config *config, EFI_HANDLE *device, EFI_FILE *root_dir) {
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
_cleanup_free_ char *bcd = NULL;
char16_t *title = NULL;
EFI_STATUS err;
UINTN len;
assert(config);
assert(device);
assert(root_dir);
if (!config->auto_entries)
return;
/* Try to find a better title. */
err = file_read(root_dir, L"\\EFI\\Microsoft\\Boot\\BCD", 0, 100*1024, &bcd, &len);
if (err == EFI_SUCCESS)
title = get_bcd_title((uint8_t *) bcd, len);
ConfigEntry *e = config_entry_add_loader_auto(config, device, root_dir, NULL,
L"auto-windows", 'w', title ?: L"Windows Boot Manager",
L"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
if (config->reboot_for_bitlocker)
e->call = boot_windows_bitlocker;
#endif
}
static void config_entry_add_unified(
Config *config,
EFI_HANDLE *device,
EFI_FILE *root_dir) {
_cleanup_(file_closep) EFI_FILE *linux_dir = NULL;
_cleanup_free_ EFI_FILE_INFO *f = NULL;
UINTN f_size = 0;
EFI_STATUS err;
/* Adds Boot Loader Type #2 entries (i.e. /EFI/Linux/….efi) */
assert(config);
assert(device);
assert(root_dir);
err = open_directory(root_dir, L"\\EFI\\Linux", &linux_dir);
if (err != EFI_SUCCESS)
return;
for (;;) {
enum {
SECTION_CMDLINE,
SECTION_OSREL,
_SECTION_MAX,
};
static const char * const sections[_SECTION_MAX + 1] = {
[SECTION_CMDLINE] = ".cmdline",
[SECTION_OSREL] = ".osrel",
NULL,
};
_cleanup_free_ char16_t *os_pretty_name = NULL, *os_image_id = NULL, *os_name = NULL, *os_id = NULL,
*os_image_version = NULL, *os_version = NULL, *os_version_id = NULL, *os_build_id = NULL;
const char16_t *good_name, *good_version, *good_sort_key;
_cleanup_free_ char *content = NULL;
UINTN offs[_SECTION_MAX] = {};
UINTN szs[_SECTION_MAX] = {};
char *line;
UINTN pos = 0;
char *key, *value;
err = readdir_harder(linux_dir, &f, &f_size);
if (err != EFI_SUCCESS || !f)
break;
if (f->FileName[0] == '.')
continue;
if (FLAGS_SET(f->Attribute, EFI_FILE_DIRECTORY))
continue;
if (!endswith_no_case(f->FileName, L".efi"))
continue;
if (startswith(f->FileName, L"auto-"))
continue;
/* look for .osrel and .cmdline sections in the .efi binary */
err = pe_file_locate_sections(linux_dir, f->FileName, sections, offs, szs);
if (err != EFI_SUCCESS || szs[SECTION_OSREL] == 0)
continue;
err = file_read(linux_dir, f->FileName, offs[SECTION_OSREL], szs[SECTION_OSREL], &content, NULL);
if (err != EFI_SUCCESS)
continue;
/* read properties from the embedded os-release file */
while ((line = line_get_key_value(content, "=", &pos, &key, &value))) {
if (streq8(key, "PRETTY_NAME")) {
free(os_pretty_name);
os_pretty_name = xstr8_to_16(value);
continue;
}
if (streq8(key, "IMAGE_ID")) {
free(os_image_id);
os_image_id = xstr8_to_16(value);
continue;
}
if (streq8(key, "NAME")) {
free(os_name);
os_name = xstr8_to_16(value);
continue;
}
if (streq8(key, "ID")) {
free(os_id);
os_id = xstr8_to_16(value);
continue;
}
if (streq8(key, "IMAGE_VERSION")) {
free(os_image_version);
os_image_version = xstr8_to_16(value);
continue;
}
if (streq8(key, "VERSION")) {
free(os_version);
os_version = xstr8_to_16(value);
continue;
}
if (streq8(key, "VERSION_ID")) {
free(os_version_id);
os_version_id = xstr8_to_16(value);
continue;
}
if (streq8(key, "BUILD_ID")) {
free(os_build_id);
os_build_id = xstr8_to_16(value);
continue;
}
}
if (!bootspec_pick_name_version_sort_key(
os_pretty_name,
os_image_id,
os_name,
os_id,
os_image_version,
os_version,
os_version_id,
os_build_id,
&good_name,
&good_version,
&good_sort_key))
continue;
ConfigEntry *entry = xnew(ConfigEntry, 1);
*entry = (ConfigEntry) {
.id = xstrdup16(f->FileName),
.type = LOADER_UNIFIED_LINUX,
.title = xstrdup16(good_name),
.version = xstrdup16(good_version),
.device = device,
.loader = xpool_print(L"\\EFI\\Linux\\%s", f->FileName),
.sort_key = xstrdup16(good_sort_key),
.key = 'l',
.tries_done = -1,
.tries_left = -1,
};
strtolower16(entry->id);
config_add_entry(config, entry);
config_entry_parse_tries(entry, L"\\EFI\\Linux", f->FileName, L".efi");
if (szs[SECTION_CMDLINE] == 0)
continue;
content = mfree(content);
/* read the embedded cmdline file */
size_t cmdline_len;
err = file_read(linux_dir, f->FileName, offs[SECTION_CMDLINE], szs[SECTION_CMDLINE], &content, &cmdline_len);
if (err == EFI_SUCCESS) {
entry->options = xstrn8_to_16(content, cmdline_len);
mangle_stub_cmdline(entry->options);
}
}
}
static void config_load_xbootldr(
Config *config,
EFI_HANDLE *device) {
_cleanup_(file_closep) EFI_FILE *root_dir = NULL;
EFI_HANDLE new_device = NULL; /* avoid false maybe-uninitialized warning */
EFI_STATUS err;
assert(config);
assert(device);
err = xbootldr_open(device, &new_device, &root_dir);
if (err != EFI_SUCCESS)
return;
config_entry_add_unified(config, new_device, root_dir);
config_load_entries(config, new_device, root_dir, NULL);
}
static EFI_STATUS initrd_prepare(
EFI_FILE *root,
const ConfigEntry *entry,
char16_t **ret_options,
void **ret_initrd,
UINTN *ret_initrd_size) {
assert(root);
assert(entry);
assert(ret_options);
assert(ret_initrd);
assert(ret_initrd_size);
if (entry->type != LOADER_LINUX || !entry->initrd) {
*ret_options = NULL;
*ret_initrd = NULL;
*ret_initrd_size = 0;
return EFI_SUCCESS;
}
/* Note that order of initrds matters. The kernel will only look for microcode updates in the very
* first one it sees. */
/* Add initrd= to options for older kernels that do not support LINUX_INITRD_MEDIA. Should be dropped
* if linux_x86.c is dropped. */
_cleanup_free_ char16_t *options = NULL;
EFI_STATUS err;
UINTN size = 0;
_cleanup_free_ uint8_t *initrd = NULL;
STRV_FOREACH(i, entry->initrd) {
_cleanup_free_ char16_t *o = options;
if (o)
options = xpool_print(L"%s initrd=%s", o, *i);
else
options = xpool_print(L"initrd=%s", *i);
_cleanup_(file_closep) EFI_FILE *handle = NULL;
err = root->Open(root, &handle, *i, EFI_FILE_MODE_READ, 0);
if (err != EFI_SUCCESS)
return err;
_cleanup_free_ EFI_FILE_INFO *info = NULL;
err = get_file_info_harder(handle, &info, NULL);
if (err != EFI_SUCCESS)
return err;
if (info->FileSize == 0) /* Automatically skip over empty files */
continue;
UINTN new_size, read_size = info->FileSize;
if (__builtin_add_overflow(size, read_size, &new_size))
return EFI_OUT_OF_RESOURCES;
initrd = xrealloc(initrd, size, new_size);
err = chunked_read(handle, &read_size, initrd + size);
if (err != EFI_SUCCESS)
return err;
/* Make sure the actual read size is what we expected. */
assert(size + read_size == new_size);
size = new_size;
}
if (entry->options) {
_cleanup_free_ char16_t *o = options;
options = xpool_print(L"%s %s", o, entry->options);
}
*ret_options = TAKE_PTR(options);
*ret_initrd = TAKE_PTR(initrd);
*ret_initrd_size = size;
return EFI_SUCCESS;
}
static EFI_STATUS image_start(
EFI_HANDLE parent_image,
const ConfigEntry *entry) {
_cleanup_(devicetree_cleanup) struct devicetree_state dtstate = {};
_cleanup_(unload_imagep) EFI_HANDLE image = NULL;
_cleanup_free_ EFI_DEVICE_PATH *path = NULL;
EFI_STATUS err;
assert(entry);
/* If this loader entry has a special way to boot, try that first. */
if (entry->call)
(void) entry->call();
_cleanup_(file_closep) EFI_FILE *image_root = NULL;
err = open_volume(entry->device, &image_root);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Error opening root path: %r", err);
err = make_file_device_path(entry->device, entry->loader, &path);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Error making file device path: %r", err);
UINTN initrd_size = 0;
_cleanup_free_ void *initrd = NULL;
_cleanup_free_ char16_t *options_initrd = NULL;
err = initrd_prepare(image_root, entry, &options_initrd, &initrd, &initrd_size);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Error preparing initrd: %r", err);
err = shim_load_image(parent_image, path, &image);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Error loading %s: %r", entry->loader, err);
/* DTBs are loaded by the kernel before ExitBootServices, and they can be used to map and assign
* arbitrary memory ranges, so skip it when secure boot is enabled as the DTB here is unverified. */
if (entry->devicetree && !secure_boot_enabled()) {
err = devicetree_install(&dtstate, image_root, entry->devicetree);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Error loading %s: %r", entry->devicetree, err);
}
_cleanup_(cleanup_initrd) EFI_HANDLE initrd_handle = NULL;
err = initrd_register(initrd, initrd_size, &initrd_handle);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Error registering initrd: %r", err);
EFI_LOADED_IMAGE_PROTOCOL *loaded_image;
err = BS->HandleProtocol(image, &LoadedImageProtocol, (void **) &loaded_image);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Error getting LoadedImageProtocol handle: %r", err);
char16_t *options = options_initrd ?: entry->options;
if (options) {
loaded_image->LoadOptions = options;
loaded_image->LoadOptionsSize = strsize16(options);
/* Try to log any options to the TPM, especially to catch manually edited options */
(void) tpm_log_load_options(options, NULL);
}
efivar_set_time_usec(LOADER_GUID, L"LoaderTimeExecUSec", 0);
err = BS->StartImage(image, NULL, NULL);
graphics_mode(false);
if (err == EFI_SUCCESS)
return EFI_SUCCESS;
/* Try calling the kernel compat entry point if one exists. */
if (err == EFI_UNSUPPORTED && entry->type == LOADER_LINUX) {
uint32_t compat_address;
err = pe_kernel_info(loaded_image->ImageBase, &compat_address);
if (err != EFI_SUCCESS) {
if (err != EFI_UNSUPPORTED)
return log_error_status_stall(err, L"Error finding kernel compat entry address: %r", err);
} else if (compat_address > 0) {
EFI_IMAGE_ENTRY_POINT kernel_entry =
(EFI_IMAGE_ENTRY_POINT) ((uint8_t *) loaded_image->ImageBase + compat_address);
err = kernel_entry(image, ST);
graphics_mode(false);
if (err == EFI_SUCCESS)
return EFI_SUCCESS;
} else
err = EFI_UNSUPPORTED;
}
return log_error_status_stall(err, L"Failed to execute %s (%s): %r", entry->title_show, entry->loader, err);
}
static void config_free(Config *config) {
assert(config);
for (UINTN i = 0; i < config->entry_count; i++)
config_entry_free(config->entries[i]);
free(config->entries);
free(config->entry_default_config);
free(config->entry_default_efivar);
free(config->entry_oneshot);
free(config->entry_saved);
}
static void config_write_entries_to_variable(Config *config) {
_cleanup_free_ char *buffer = NULL;
UINTN sz = 0;
char *p;
assert(config);
for (UINTN i = 0; i < config->entry_count; i++)
sz += strsize16(config->entries[i]->id);
p = buffer = xmalloc(sz);
for (UINTN i = 0; i < config->entry_count; i++)
p = mempcpy(p, config->entries[i]->id, strsize16(config->entries[i]->id));
assert(p == buffer + sz);
/* Store the full list of discovered entries. */
(void) efivar_set_raw(LOADER_GUID, L"LoaderEntries", buffer, sz, 0);
}
static void save_selected_entry(const Config *config, const ConfigEntry *entry) {
assert(config);
assert(entry);
assert(entry->loader || !entry->call);
/* Always export the selected boot entry to the system in a volatile var. */
(void) efivar_set(LOADER_GUID, L"LoaderEntrySelected", entry->id, 0);
/* Do not save or delete if this was a oneshot boot. */
if (streq16(config->entry_oneshot, entry->id))
return;
if (config->use_saved_entry_efivar || (!config->entry_default_efivar && config->use_saved_entry)) {
/* Avoid unnecessary NVRAM writes. */
if (streq16(config->entry_saved, entry->id))
return;
(void) efivar_set(LOADER_GUID, L"LoaderEntryLastBooted", entry->id, EFI_VARIABLE_NON_VOLATILE);
} else
/* Delete the non-volatile var if not needed. */
(void) efivar_set(LOADER_GUID, L"LoaderEntryLastBooted", NULL, EFI_VARIABLE_NON_VOLATILE);
}
static EFI_STATUS secure_boot_discover_keys(Config *config, EFI_FILE *root_dir) {
EFI_STATUS err;
_cleanup_(file_closep) EFI_FILE *keys_basedir = NULL;
if (!IN_SET(secure_boot_mode(), SECURE_BOOT_SETUP, SECURE_BOOT_AUDIT))
return EFI_SUCCESS;
/* the lack of a 'keys' directory is not fatal and is silently ignored */
err = open_directory(root_dir, u"\\loader\\keys", &keys_basedir);
if (err == EFI_NOT_FOUND)
return EFI_SUCCESS;
if (err != EFI_SUCCESS)
return err;
for (;;) {
_cleanup_free_ EFI_FILE_INFO *dirent = NULL;
size_t dirent_size = 0;
ConfigEntry *entry = NULL;
err = readdir_harder(keys_basedir, &dirent, &dirent_size);
if (err != EFI_SUCCESS || !dirent)
return err;
if (dirent->FileName[0] == '.')
continue;
if (!FLAGS_SET(dirent->Attribute, EFI_FILE_DIRECTORY))
continue;
entry = xnew(ConfigEntry, 1);
*entry = (ConfigEntry) {
.id = xpool_print(L"secure-boot-keys-%s", dirent->FileName),
.title = xpool_print(L"Enroll Secure Boot keys: %s", dirent->FileName),
.path = xpool_print(L"\\loader\\keys\\%s", dirent->FileName),
.type = LOADER_SECURE_BOOT_KEYS,
.tries_done = -1,
.tries_left = -1,
};
config_add_entry(config, entry);
if (config->secure_boot_enroll == ENROLL_FORCE && strcaseeq16(dirent->FileName, u"auto"))
/* if we auto enroll successfully this call does not return, if it fails we still
* want to add other potential entries to the menu */
secure_boot_enroll_at(root_dir, entry->path);
}
return EFI_SUCCESS;
}
static void export_variables(
EFI_LOADED_IMAGE_PROTOCOL *loaded_image,
const char16_t *loaded_image_path,
uint64_t init_usec) {
static const uint64_t loader_features =
EFI_LOADER_FEATURE_CONFIG_TIMEOUT |
EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT |
EFI_LOADER_FEATURE_ENTRY_DEFAULT |
EFI_LOADER_FEATURE_ENTRY_ONESHOT |
EFI_LOADER_FEATURE_BOOT_COUNTING |
EFI_LOADER_FEATURE_XBOOTLDR |
EFI_LOADER_FEATURE_RANDOM_SEED |
EFI_LOADER_FEATURE_LOAD_DRIVER |
EFI_LOADER_FEATURE_SORT_KEY |
EFI_LOADER_FEATURE_SAVED_ENTRY |
EFI_LOADER_FEATURE_DEVICETREE |
0;
_cleanup_free_ char16_t *infostr = NULL, *typestr = NULL;
char16_t uuid[37];
assert(loaded_image);
efivar_set_time_usec(LOADER_GUID, L"LoaderTimeInitUSec", init_usec);
efivar_set(LOADER_GUID, L"LoaderInfo", L"systemd-boot " GIT_VERSION, 0);
infostr = xpool_print(L"%s %u.%02u", ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
efivar_set(LOADER_GUID, L"LoaderFirmwareInfo", infostr, 0);
typestr = xpool_print(L"UEFI %u.%02u", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
efivar_set(LOADER_GUID, L"LoaderFirmwareType", typestr, 0);
(void) efivar_set_uint64_le(LOADER_GUID, L"LoaderFeatures", loader_features, 0);
/* the filesystem path to this image, to prevent adding ourselves to the menu */
efivar_set(LOADER_GUID, L"LoaderImageIdentifier", loaded_image_path, 0);
/* export the device path this image is started from */
if (disk_get_part_uuid(loaded_image->DeviceHandle, uuid) == EFI_SUCCESS)
efivar_set(LOADER_GUID, L"LoaderDevicePartUUID", uuid, 0);
}
static void config_load_all_entries(
Config *config,
EFI_LOADED_IMAGE_PROTOCOL *loaded_image,
const char16_t *loaded_image_path,
EFI_FILE *root_dir) {
assert(config);
assert(loaded_image);
assert(root_dir);
config_load_defaults(config, root_dir);
/* scan /EFI/Linux/ directory */
config_entry_add_unified(config, loaded_image->DeviceHandle, root_dir);
/* scan /loader/entries/\*.conf files */
config_load_entries(config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
/* Similar, but on any XBOOTLDR partition */
config_load_xbootldr(config, loaded_image->DeviceHandle);
/* sort entries after version number */
sort_pointer_array((void **) config->entries, config->entry_count, (compare_pointer_func_t) config_entry_compare);
/* if we find some well-known loaders, add them to the end of the list */
config_entry_add_osx(config);
config_entry_add_windows(config, loaded_image->DeviceHandle, root_dir);
config_entry_add_loader_auto(config, loaded_image->DeviceHandle, root_dir, NULL,
L"auto-efi-shell", 's', L"EFI Shell", L"\\shell" EFI_MACHINE_TYPE_NAME ".efi");
config_entry_add_loader_auto(config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
L"auto-efi-default", '\0', L"EFI Default Loader", NULL);
if (config->auto_firmware && FLAGS_SET(get_os_indications_supported(), EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
ConfigEntry *entry = xnew(ConfigEntry, 1);
*entry = (ConfigEntry) {
.id = xstrdup16(u"auto-reboot-to-firmware-setup"),
.title = xstrdup16(u"Reboot Into Firmware Interface"),
.call = reboot_into_firmware,
.tries_done = -1,
.tries_left = -1,
};
config_add_entry(config, entry);
}
/* find if secure boot signing keys exist and autoload them if necessary
otherwise creates menu entries so that the user can load them manually
if the secure-boot-enroll variable is set to no (the default), we do not
even search for keys on the ESP */
if (config->secure_boot_enroll != ENROLL_OFF)
secure_boot_discover_keys(config, root_dir);
if (config->entry_count == 0)
return;
config_write_entries_to_variable(config);
config_title_generate(config);
/* select entry by configured pattern or EFI LoaderDefaultEntry= variable */
config_default_entry_select(config);
}
EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *sys_table) {
EFI_LOADED_IMAGE_PROTOCOL *loaded_image;
_cleanup_(file_closep) EFI_FILE *root_dir = NULL;
_cleanup_(config_free) Config config = {};
_cleanup_free_ char16_t *loaded_image_path = NULL;
EFI_STATUS err;
uint64_t init_usec;
bool menu = false;
InitializeLib(image, sys_table);
init_usec = time_usec();
debug_hook(L"systemd-boot");
/* Uncomment the next line if you need to wait for debugger. */
// debug_break();
err = BS->OpenProtocol(image,
&LoadedImageProtocol,
(void **)&loaded_image,
image,
NULL,
EFI_OPEN_PROTOCOL_GET_PROTOCOL);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Error getting a LoadedImageProtocol handle: %r", err);
(void) device_path_to_str(loaded_image->FilePath, &loaded_image_path);
export_variables(loaded_image, loaded_image_path, init_usec);
/* The firmware may skip initializing some devices for the sake of a faster boot. This is especially
* true for fastboot enabled firmwares. But this means that things we use like input devices or the
* xbootldr partition may not be available yet. Reconnect all drivers should hopefully make the
* firmware initialize everything we need. */
if (is_direct_boot(loaded_image->DeviceHandle))
(void) reconnect_all_drivers();
err = open_volume(loaded_image->DeviceHandle, &root_dir);
if (err != EFI_SUCCESS)
return log_error_status_stall(err, L"Unable to open root directory: %r", err);
(void) load_drivers(image, loaded_image, root_dir);
config_load_all_entries(&config, loaded_image, loaded_image_path, root_dir);
if (config.entry_count == 0) {
log_error_stall(L"No loader found. Configuration files in \\loader\\entries\\*.conf are needed.");
goto out;
}
/* select entry or show menu when key is pressed or timeout is set */
if (config.force_menu || config.timeout_sec > 0)
menu = true;
else {
uint64_t key;
/* Block up to 100ms to give firmware time to get input working. */
err = console_key_read(&key, 100 * 1000);
if (err == EFI_SUCCESS) {
/* find matching key in config entries */
UINTN idx = entry_lookup_key(&config, config.idx_default, KEYCHAR(key));
if (idx != IDX_INVALID)
config.idx_default = idx;
else
menu = true;
}
}
for (;;) {
ConfigEntry *entry;
entry = config.entries[config.idx_default];
if (menu) {
efivar_set_time_usec(LOADER_GUID, L"LoaderTimeMenuUSec", 0);
if (!menu_run(&config, &entry, loaded_image_path))
break;
}
/* if auto enrollment is activated, we try to load keys for the given entry. */
if (entry->type == LOADER_SECURE_BOOT_KEYS && config.secure_boot_enroll != ENROLL_OFF) {
err = secure_boot_enroll_at(root_dir, entry->path);
if (err != EFI_SUCCESS)
return err;
continue;
}
/* Run special entry like "reboot" now. Those that have a loader
* will be handled by image_start() instead. */
if (entry->call && !entry->loader) {
entry->call();
continue;
}
(void) config_entry_bump_counters(entry);
save_selected_entry(&config, entry);
/* Optionally, read a random seed off the ESP and pass it to the OS */
(void) process_random_seed(root_dir, config.random_seed_mode);
err = image_start(image, entry);
if (err != EFI_SUCCESS)
goto out;
menu = true;
config.timeout_sec = 0;
}
err = EFI_SUCCESS;
out:
BS->CloseProtocol(image, &LoadedImageProtocol, image, NULL);
return err;
}
|