Debian Codegraph @

src/boot/boot.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "bcd.h"
4 #include "bootspec.h"
5 #include "console.h"
6 #include "cpio.h"
7 #include "device-path-util.h"
8 #include "devicetree.h"
9 #include "drivers.h"
10 #include "efi-efivars.h"
11 #include "efi-log.h"
12 #include "efi-string-table.h"
13 #include "efivars.h"
14 #include "export-vars.h"
15 #include "graphics.h"
16 #include "initrd.h"
17 #include "iovec-util.h"
18 #include "line-edit.h"
19 #include "measure.h"
20 #include "measure-smbios.h"
21 #include "memory-util.h"
22 #include "part-discovery.h"
23 #include "pe.h"
24 #include "proto/block-io.h"
25 #include "proto/disk-io.h"
26 #include "proto/load-file.h"
27 #include "proto/simple-text-io.h"
28 #include "random-seed.h"
29 #include "sbat.h"
30 #include "secure-boot.h"
31 #include "shim.h"
32 #include "smbios.h"
33 #include "strv.h"
34 #include "sysfail.h"
35 #include "ticks.h"
36 #include "tpm2-pcr.h"
37 #include "uki.h"
38 #include "url-discovery.h"
39 #include "util.h"
40 #include "version.h"
41 #include "vmm.h"
42
43 /* Safety margin, refuse larger extra files (this is not load bearing, only a safety net for robustness reasons). */
44 #define EXTRA_SIZE_MAX (1024U * 1024U * 1536U)
45
46 /* Magic string for recognizing our own binaries */
47 #define SD_MAGIC "#### LoaderInfo: systemd-boot " GIT_VERSION " ####"
48 DECLARE_NOALLOC_SECTION(".sdmagic", SD_MAGIC);
49
50 /* Makes systemd-boot available from \EFI\Linux\ for testing purposes. */
51 DECLARE_NOALLOC_SECTION(
52 ".osrel",
53 "ID=systemd-boot\n"
54 "VERSION=\"" GIT_VERSION "\"\n"
55 "NAME=\"systemd-boot " GIT_VERSION "\"\n");
56
57 DECLARE_SBAT(SBAT_BOOT_SECTION_TEXT);
58
59 typedef enum LoaderType {
60 LOADER_UNDEFINED,
61 LOADER_AUTO,
62 LOADER_EFI, /* Boot loader spec type #1 entries with "efi" line */
63 LOADER_LINUX, /* Boot loader spec type #1 entries with "linux" line */
64 LOADER_UKI, /* Boot loader spec type #1 entries with "uki" line */
65 LOADER_UKI_URL, /* Boot loader spec type #1 entries with "uki-url" line */
66 LOADER_TYPE2_UKI, /* Boot loader spec type #2 entries */
67 LOADER_SECURE_BOOT_KEYS,
68 LOADER_BAD, /* Marker: this boot loader spec type #1 entry is invalid */
69 LOADER_IGNORE, /* Marker: this boot loader spec type #1 entry does not match local host */
70 LOADER_REBOOT,
71 LOADER_POWEROFF,
72 LOADER_FWSETUP,
73 _LOADER_TYPE_MAX,
74 } LoaderType;
75
76 /* Which loader types permit command line editing */
77 #define LOADER_TYPE_ALLOW_EDITOR(t) IN_SET(t, LOADER_EFI, LOADER_LINUX, LOADER_UKI, LOADER_UKI_URL, LOADER_TYPE2_UKI)
78
79 /* Which loader types allow command line editing in SecureBoot mode */
80 #define LOADER_TYPE_ALLOW_EDITOR_IN_SB(t) IN_SET(t, LOADER_EFI, LOADER_LINUX)
81
82 /* Which loader types shall be considered for automatic selection */
83 #define LOADER_TYPE_MAY_AUTO_SELECT(t) IN_SET(t, LOADER_EFI, LOADER_LINUX, LOADER_UKI, LOADER_UKI_URL, LOADER_TYPE2_UKI)
84
85 /* Whether to do boot attempt counting logic (only works if userspace can actually find the selected option later) */
86 #define LOADER_TYPE_BUMP_COUNTERS(t) IN_SET(t, LOADER_LINUX, LOADER_UKI, LOADER_TYPE2_UKI)
87
88 /* Whether to do random seed management (only we invoke Linux) */
89 #define LOADER_TYPE_PROCESS_RANDOM_SEED(t) IN_SET(t, LOADER_LINUX, LOADER_UKI, LOADER_TYPE2_UKI)
90
91 /* Whether to persistently save the selected entry in an EFI variable, if that's requested. */
92 #define LOADER_TYPE_SAVE_ENTRY(t) IN_SET(t, LOADER_AUTO, LOADER_EFI, LOADER_LINUX, LOADER_UKI, LOADER_UKI_URL, LOADER_TYPE2_UKI)
93
94 /* Whether this item is implemented fully inside of systemd-boot */
95 #define LOADER_TYPE_IS_INTERNAL(t) IN_SET(t, LOADER_SECURE_BOOT_KEYS, LOADER_REBOOT, LOADER_POWEROFF, LOADER_FWSETUP)
96
97 typedef enum {
98 REBOOT_NO,
99 REBOOT_YES,
100 REBOOT_AUTO,
101 _REBOOT_ON_ERROR_MAX,
102 } RebootOnError;
103
104 static const char *reboot_on_error_table[_REBOOT_ON_ERROR_MAX] = {
105 [REBOOT_NO] = "no",
106 [REBOOT_YES] = "yes",
107 [REBOOT_AUTO] = "auto",
108 };
109
110 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(reboot_on_error, RebootOnError);
111
112 typedef struct BootEntry {
113 char16_t *id; /* The unique identifier for this entry (typically the filename of the file defining the entry, possibly suffixed with a profile id) */
114 char16_t *id_without_profile; /* same, but without any profile id suffixed */
115 char16_t *title_show; /* The string to actually display (this is made unique before showing) */
116 char16_t *title; /* The raw (human-readable) title string of the entry (not necessarily unique) */
117 char16_t *sort_key; /* The string to use as primary sort key, usually ID= from os-release, possibly suffixed */
118 char16_t *version; /* The raw (human-readable) version string of the entry */
119 char16_t *machine_id;
120 EFI_HANDLE *device;
121 LoaderType type;
122 char16_t *loader;
123 char16_t *url;
124 char16_t *devicetree;
125 char16_t *options;
126 bool options_implied; /* If true, these options are implied if we invoke the PE binary without any parameters (as in: UKI). If false we must specify these options explicitly. */
127 char16_t **initrd;
128 char16_t **extras;
129 char16_t key;
130 EFI_STATUS (*call)(const struct BootEntry *entry, EFI_FILE *root_dir, EFI_HANDLE parent_image);
131 int tries_done;
132 int tries_left;
133 char16_t *directory;
134 char16_t *current_name;
135 char16_t *next_name;
136 unsigned profile;
137 } BootEntry;
138
139 typedef struct {
140 BootEntry **entries;
141 size_t n_entries;
142 size_t idx_default;
143 size_t idx_default_efivar;
144 uint64_t timeout_sec; /* Actual timeout used (efi_main() override > smbios > efivar > config). */
145 uint64_t timeout_sec_smbios;
146 uint64_t timeout_sec_config;
147 uint64_t timeout_sec_efivar;
148 char16_t *entry_default_config;
149 char16_t *entry_preferred_config;
150 char16_t *entry_default_efivar;
151 char16_t *entry_preferred_efivar;
152 char16_t *entry_oneshot;
153 char16_t *entry_saved;
154 char16_t *entry_sysfail;
155 bool editor;
156 bool auto_entries;
157 bool auto_firmware;
158 bool auto_poweroff;
159 bool auto_reboot;
160 bool reboot_for_bitlocker;
161 RebootOnError reboot_on_error;
162 secure_boot_enroll secure_boot_enroll;
163 secure_boot_enroll_action secure_boot_enroll_action;
164 uint64_t secure_boot_enroll_timeout_sec;
165 bool force_menu;
166 bool use_saved_entry;
167 bool use_saved_entry_efivar;
168 bool use_saved_entry_preferred;
169 bool use_saved_entry_preferred_efivar;
170 bool beep;
171 bool sysfail_occurred;
172 int64_t console_mode;
173 int64_t console_mode_efivar;
174 } Config;
175
176 /* These values have been chosen so that the transitions the user sees could employ unsigned over-/underflow
177 * like this:
178 * efivar unset ↔ force menu ↔ no timeout/skip menu ↔ 1 s ↔ 2 s ↔ …
179 *
180 * Note: all the values below are ABI, so they are not allowed to change. The bootctl tool sets the numerical
181 * value of TIMEOUT_MENU_FORCE and TIMEOUT_MENU_HIDDEN, instead of the string for compatibility reasons.
182 *
183 * The other values may be set by systemd-boot itself and changing those will lead to functional regression
184 * when new version of systemd-boot is installed.
185 *
186 * All the 64bit values are not ABI and will never be written to an efi variable.
187 */
188 enum {
189 TIMEOUT_MIN = 1,
190 TIMEOUT_MAX = UINT32_MAX - 2U,
191 TIMEOUT_UNSET = UINT32_MAX - 1U,
192 TIMEOUT_MENU_FORCE = UINT32_MAX,
193 TIMEOUT_MENU_HIDDEN = 0,
194 TIMEOUT_TYPE_MAX = UINT32_MAX,
195 TIMEOUT_MENU_DISABLED = (uint64_t)UINT32_MAX + 1U,
196 TIMEOUT_TYPE_MAX64 = UINT64_MAX,
197 };
198
199 enum {
200 IDX_MAX = INT16_MAX,
201 IDX_INVALID,
202 };
203
204
205 static size_t entry_lookup_key(Config *config, size_t start, char16_t key) {
206 assert(config);
207
208 if (key == 0)
209 return IDX_INVALID;
210
211 /* select entry by number key */
212 if (key >= '1' && key <= '9') {
213 size_t i = key - '0';
214 if (i > config->n_entries)
215 i = config->n_entries;
216 return i-1;
217 }
218
219 /* find matching key in boot entries */
220 for (size_t i = start; i < config->n_entries; i++)
221 if (config->entries[i]->key == key)
222 return i;
223
224 for (size_t i = 0; i < start; i++)
225 if (config->entries[i]->key == key)
226 return i;
227
228 return IDX_INVALID;
229 }
230
231 static char16_t* update_timeout_efivar(Config *config, bool inc) {
232 assert(config);
233
234 switch (config->timeout_sec) {
235 case TIMEOUT_MAX:
236 config->timeout_sec = inc ? TIMEOUT_MAX : config->timeout_sec - 1;
237 break;
238 case TIMEOUT_UNSET:
239 config->timeout_sec = inc ? TIMEOUT_MENU_FORCE : TIMEOUT_UNSET;
240 break;
241 case TIMEOUT_MENU_DISABLED:
242 config->timeout_sec = inc ? TIMEOUT_MIN : TIMEOUT_MENU_FORCE;
243 break;
244 case TIMEOUT_MENU_FORCE:
245 config->timeout_sec = inc ? TIMEOUT_MENU_HIDDEN : TIMEOUT_MENU_FORCE;
246 break;
247 case TIMEOUT_MENU_HIDDEN:
248 config->timeout_sec = inc ? TIMEOUT_MIN : TIMEOUT_MENU_FORCE;
249 break;
250 default:
251 config->timeout_sec = config->timeout_sec + (inc ? 1 : -1);
252 }
253
254 config->timeout_sec_efivar = config->timeout_sec;
255
256 switch (config->timeout_sec) {
257 case TIMEOUT_UNSET:
258 return xstrdup16(u"Menu timeout defined by configuration file.");
259 case TIMEOUT_MENU_DISABLED:
260 assert_not_reached();
261 case TIMEOUT_MENU_FORCE:
262 return xstrdup16(u"Timeout disabled, menu will always be shown.");
263 case TIMEOUT_MENU_HIDDEN:
264 return xstrdup16(u"Menu hidden. Hold down key at bootup to show menu.");
265 default:
266 return xasprintf("Menu timeout set to %"PRIu64"s.", config->timeout_sec_efivar);
267 }
268 }
269
270 static bool unicode_supported(void) {
271 static int cache = -1;
272
273 if (cache < 0)
274 /* Basic unicode box drawing support is mandated by the spec, but it does
275 * not hurt to make sure it works. */
276 cache = ST->ConOut->TestString(ST->ConOut, (char16_t *) u"─") == EFI_SUCCESS;
277
278 return cache;
279 }
280
281 static bool ps_continue(void) {
282 const char16_t *sep = unicode_supported() ? u"───" : u"---";
283 printf("\n%ls Press any key to continue, ESC or q to quit. %ls\n\n", sep, sep);
284
285 uint64_t key;
286 return console_key_read(&key, UINT64_MAX) == EFI_SUCCESS &&
287 !IN_SET(key, KEYPRESS(0, SCAN_ESC, 0), KEYPRESS(0, 0, 'q'), KEYPRESS(0, 0, 'Q'));
288 }
289
290 static void print_timeout_status(const char *label, uint64_t t) {
291 switch (t) {
292 case TIMEOUT_UNSET:
293 return;
294 case TIMEOUT_MENU_DISABLED:
295 return (void) printf("%s: menu-disabled\n", label);
296 case TIMEOUT_MENU_FORCE:
297 return (void) printf("%s: menu-force\n", label);
298 case TIMEOUT_MENU_HIDDEN:
299 return (void) printf("%s: menu-hidden\n", label);
300 default:
301 return (void) printf("%s: %"PRIu64"s\n", label, t);
302 }
303 }
304
305 static void print_status(Config *config, char16_t *loaded_image_path) {
306 size_t x_max, y_max;
307 uint32_t screen_width = 0, screen_height = 0;
308 SecureBootMode secure;
309 _cleanup_free_ char16_t *device_part_uuid = NULL;
310
311 assert(config);
312
313 clear_screen(COLOR_NORMAL);
314 console_query_mode(&x_max, &y_max);
315 query_screen_resolution(&screen_width, &screen_height);
316
317 secure = secure_boot_mode();
318 (void) efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderDevicePartUUID", &device_part_uuid);
319
320 printf(" systemd-boot version: " GIT_VERSION "\n");
321 if (loaded_image_path)
322 printf(" loaded image: %ls\n", loaded_image_path);
323 if (device_part_uuid)
324 printf(" loader partition UUID: %ls\n", device_part_uuid);
325 printf(" architecture: " EFI_MACHINE_TYPE_NAME "\n");
326 printf(" UEFI specification: %u.%02u\n", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
327 printf(" firmware vendor: %ls\n", ST->FirmwareVendor);
328 printf(" firmware version: %u.%02u\n", ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
329 printf(" OS indications: %#" PRIx64 "\n", get_os_indications_supported());
330 printf(" secure boot: %ls (%ls)\n",
331 yes_no(IN_SET(secure, SECURE_BOOT_USER, SECURE_BOOT_DEPLOYED)),
332 secure_boot_mode_to_string(secure));
333 printf(" shim: %ls\n", yes_no(shim_loaded()));
334 printf(" TPM: %ls\n", yes_no(tpm_present()));
335 printf(" console mode: %i/%" PRIi64 " (%zux%zu",
336 ST->ConOut->Mode->Mode, ST->ConOut->Mode->MaxMode - INT64_C(1),
337 x_max, y_max);
338 if (screen_width > 0 && screen_height > 0)
339 printf(" @ %ux%u",
340 screen_width, screen_height);
341 printf(")\n");
342
343 if (!ps_continue())
344 return;
345
346 print_timeout_status(" timeout (config)", config->timeout_sec_config);
347 print_timeout_status(" timeout (EFI var)", config->timeout_sec_efivar);
348 print_timeout_status(" timeout (smbios)", config->timeout_sec_smbios);
349
350 if (config->entry_default_config)
351 printf(" default (config): %ls\n", config->entry_default_config);
352 if (config->entry_preferred_config)
353 printf(" preferred (config): %ls\n", config->entry_preferred_config);
354 if (config->entry_default_efivar)
355 printf(" default (EFI var): %ls\n", config->entry_default_efivar);
356 if (config->entry_preferred_efivar)
357 printf(" preferred (EFI var): %ls\n", config->entry_preferred_efivar);
358 if (config->entry_oneshot)
359 printf(" default (one-shot): %ls\n", config->entry_oneshot);
360 if (config->entry_sysfail)
361 printf(" sysfail: %ls\n", config->entry_sysfail);
362 if (config->entry_saved)
363 printf(" saved entry: %ls\n", config->entry_saved);
364 printf(" editor: %ls\n", yes_no(config->editor));
365 printf(" auto-entries: %ls\n", yes_no(config->auto_entries));
366 printf(" auto-firmware: %ls\n", yes_no(config->auto_firmware));
367 printf(" auto-poweroff: %ls\n", yes_no(config->auto_poweroff));
368 printf(" auto-reboot: %ls\n", yes_no(config->auto_reboot));
369 printf(" beep: %ls\n", yes_no(config->beep));
370 printf(" reboot-for-bitlocker: %ls\n", yes_no(config->reboot_for_bitlocker));
371 printf(" reboot-on-error: %s\n", reboot_on_error_to_string(config->reboot_on_error));
372 printf(" secure-boot-enroll: %s\n", secure_boot_enroll_to_string(config->secure_boot_enroll));
373 printf(" secure-boot-enroll-action: %s\n", secure_boot_enroll_action_to_string(config->secure_boot_enroll_action));
374 printf("secure-boot-enroll-timeout-sec: %"PRIu64"s\n", config->secure_boot_enroll_timeout_sec);
375
376 switch (config->console_mode) {
377 case CONSOLE_MODE_AUTO:
378 printf(" console-mode (config): auto\n");
379 break;
380 case CONSOLE_MODE_KEEP:
381 printf(" console-mode (config): keep\n");
382 break;
383 case CONSOLE_MODE_FIRMWARE_MAX:
384 printf(" console-mode (config): max\n");
385 break;
386 default:
387 printf(" console-mode (config): %" PRIi64 "\n", config->console_mode);
388 }
389
390 /* EFI var console mode is always a concrete value or unset. */
391 if (config->console_mode_efivar != CONSOLE_MODE_KEEP)
392 printf(" console-mode (EFI var): %" PRIi64 "\n", config->console_mode_efivar);
393
394 printf(" log-level: %s\n", log_level_to_string(log_get_max_level()));
395
396 if (!ps_continue())
397 return;
398
399 for (size_t i = 0; i < config->n_entries; i++) {
400 BootEntry *entry = config->entries[i];
401 EFI_DEVICE_PATH *dp = NULL;
402 _cleanup_free_ char16_t *dp_str = NULL;
403
404 if (entry->device &&
405 BS->HandleProtocol(entry->device, MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), (void **) &dp) ==
406 EFI_SUCCESS)
407 (void) device_path_to_str(dp, &dp_str);
408
409 printf(" boot entry: %zu/%zu\n", i + 1, config->n_entries);
410 printf(" id: %ls", entry->id);
411 if (entry->id_without_profile && !streq(entry->id_without_profile, entry->id))
412 printf(" (without profile: %ls)\n", entry->id_without_profile);
413 else
414 printf("\n");
415 if (entry->title)
416 printf(" title: %ls\n", entry->title);
417 if (entry->title_show && !streq16(entry->title, entry->title_show))
418 printf(" title show: %ls\n", entry->title_show);
419 if (entry->sort_key)
420 printf(" sort key: %ls\n", entry->sort_key);
421 if (entry->version)
422 printf(" version: %ls\n", entry->version);
423 if (entry->machine_id)
424 printf(" machine-id: %ls\n", entry->machine_id);
425 if (dp_str)
426 printf(" device: %ls\n", dp_str);
427 if (entry->loader)
428 printf(" loader: %ls\n", entry->loader);
429 if (entry->url)
430 printf(" url: %ls\n", entry->url);
431 STRV_FOREACH(initrd, entry->initrd)
432 printf(" initrd: %ls\n", *initrd);
433 STRV_FOREACH(extra, entry->extras)
434 printf(" extra: %ls\n", *extra);
435 if (entry->devicetree)
436 printf(" devicetree: %ls\n", entry->devicetree);
437 if (entry->options)
438 printf(" options: %ls\n", entry->options);
439 if (entry->profile > 0)
440 printf(" profile: %u\n", entry->profile);
441 printf(" internal call: %ls\n", yes_no(LOADER_TYPE_IS_INTERNAL(entry->type)));
442
443 printf("counting boots: %ls\n", yes_no(entry->tries_left >= 0));
444 if (entry->tries_left >= 0) {
445 printf(" tries: %i left, %i done\n", entry->tries_left, entry->tries_done);
446 printf(" current path: %ls\\%ls\n", entry->directory, entry->current_name);
447 printf(" next path: %ls\\%ls\n", entry->directory, entry->next_name);
448 }
449
450 if (!ps_continue())
451 return;
452 }
453 }
454
455 static EFI_STATUS set_reboot_into_firmware(void) {
456 EFI_STATUS err;
457
458 uint64_t osind = 0;
459 (void) efivar_get_uint64_le(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"OsIndications", &osind);
460
461 if (FLAGS_SET(osind, EFI_OS_INDICATIONS_BOOT_TO_FW_UI))
462 return EFI_SUCCESS;
463
464 osind |= EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
465
466 err = efivar_set_uint64_le(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"OsIndications", osind, EFI_VARIABLE_NON_VOLATILE);
467 if (err != EFI_SUCCESS)
468 return log_warning_status(err, "Error setting OsIndications, ignoring: %m");
469
470 return EFI_SUCCESS;
471 }
472
473 _noreturn_ static EFI_STATUS call_poweroff_system(const BootEntry *entry, EFI_FILE *root_dir, EFI_HANDLE parent_image) {
474 RT->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
475 assert_not_reached();
476 }
477
478 _noreturn_ static EFI_STATUS call_reboot_system(const BootEntry *entry, EFI_FILE *root_dir, EFI_HANDLE parent_image) {
479 RT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
480 assert_not_reached();
481 }
482
483 static EFI_STATUS call_reboot_into_firmware(const BootEntry *entry, EFI_FILE *root_dir, EFI_HANDLE parent_image) {
484 EFI_STATUS err;
485
486 err = set_reboot_into_firmware();
487 if (err != EFI_SUCCESS)
488 return err;
489
490 return call_reboot_system(entry, root_dir, parent_image);
491 }
492
493 static bool menu_run(
494 Config *config,
495 BootEntry **chosen_entry,
496 char16_t *loaded_image_path) {
497
498 assert(config);
499 assert(chosen_entry);
500
501 EFI_STATUS err;
502 size_t visible_max = 0;
503 size_t idx_highlight = config->idx_default, idx_highlight_prev = 0;
504 size_t idx, idx_first = 0, idx_last = 0;
505 bool new_mode = true, clear = true;
506 bool refresh = true, highlight = false;
507 size_t x_start = 0, y_start = 0, y_status = 0, x_max, y_max;
508 _cleanup_strv_free_ char16_t **lines = NULL;
509 _cleanup_free_ char16_t *clearline = NULL, *separator = NULL, *status = NULL;
510 uint64_t timeout_efivar_saved = config->timeout_sec_efivar,
511 timeout_remain = config->timeout_sec == TIMEOUT_MENU_FORCE ? 0 : config->timeout_sec;
512 int64_t console_mode_initial = ST->ConOut->Mode->Mode, console_mode_efivar_saved = config->console_mode_efivar;
513 size_t default_efivar_saved = config->idx_default_efivar;
514
515 enum {
516 ACTION_CONTINUE, /* Continue with loop over user input */
517 ACTION_FIRMWARE_SETUP, /* Ask for confirmation and reboot into firmware setup */
518 ACTION_POWEROFF, /* Power off the machine */
519 ACTION_REBOOT, /* Reboot the machine */
520 ACTION_RUN, /* Execute a boot entry */
521 ACTION_QUIT, /* Return to the firmware */
522 } action = ACTION_CONTINUE;
523
524 graphics_mode(false);
525 ST->ConIn->Reset(ST->ConIn, false);
526 ST->ConOut->EnableCursor(ST->ConOut, false);
527
528 /* Draw a single character to the beginning of a line, in order to make ClearScreen() work on certain
529 * broken firmware. And let's immediately move back to the beginning of the line. */
530 printf("\r \r");
531
532 err = console_set_mode(config->console_mode_efivar != CONSOLE_MODE_KEEP ?
533 config->console_mode_efivar : config->console_mode);
534 if (err != EFI_SUCCESS) {
535 clear_screen(COLOR_NORMAL);
536 log_error_status(err, "Error switching console mode: %m");
537 }
538
539 size_t line_width = 0, entry_padding = 3;
540 while (IN_SET(action, ACTION_CONTINUE, ACTION_FIRMWARE_SETUP)) {
541 uint64_t key;
542
543 if (new_mode) {
544 console_query_mode(&x_max, &y_max);
545
546 /* account for padding+status */
547 visible_max = y_max - 2;
548
549 /* Drawing entries starts at idx_first until idx_last. We want to make
550 * sure that idx_highlight is centered, but not if we are close to the
551 * beginning/end of the entry list. Otherwise we would have a half-empty
552 * screen. */
553 if (config->n_entries <= visible_max || idx_highlight <= visible_max / 2)
554 idx_first = 0;
555 else if (idx_highlight >= config->n_entries - (visible_max / 2))
556 idx_first = config->n_entries - visible_max;
557 else
558 idx_first = idx_highlight - (visible_max / 2);
559 idx_last = idx_first + visible_max - 1;
560
561 /* length of the longest entry */
562 line_width = 0;
563 for (size_t i = 0; i < config->n_entries; i++)
564 line_width = MAX(line_width, strlen16(config->entries[i]->title_show));
565 line_width = MIN(line_width + 2 * entry_padding, x_max);
566
567 /* offsets to center the entries on the screen */
568 x_start = (x_max - (line_width)) / 2;
569 if (config->n_entries < visible_max)
570 y_start = ((visible_max - config->n_entries) / 2) + 1;
571 else
572 y_start = 0;
573
574 /* Put status line after the entry list, but give it some breathing room. */
575 y_status = MIN(y_start + MIN(visible_max, config->n_entries) + 1, y_max - 1);
576
577 lines = strv_free(lines);
578 clearline = mfree(clearline);
579 separator = mfree(separator);
580
581 /* menu entries title lines */
582 lines = xnew(char16_t *, config->n_entries + 1);
583
584 for (size_t i = 0; i < config->n_entries; i++) {
585 size_t width = line_width - MIN(strlen16(config->entries[i]->title_show), line_width);
586 size_t padding = width / 2;
587 bool odd = width % 2;
588
589 /* Make sure there is space for => */
590 padding = MAX((size_t) 2, padding);
591
592 size_t print_width = MIN(
593 strlen16(config->entries[i]->title_show),
594 line_width - padding * 2);
595
596 assert((padding + 1) <= INT_MAX);
597 assert(print_width <= INT_MAX);
598
599 lines[i] = xasprintf(
600 "%*ls%.*ls%*ls",
601 (int) padding, u"",
602 (int) print_width, config->entries[i]->title_show,
603 odd ? (int) (padding + 1) : (int) padding, u"");
604 }
605 lines[config->n_entries] = NULL;
606
607 clearline = xnew(char16_t, x_max + 1);
608 separator = xnew(char16_t, x_max + 1);
609 for (size_t i = 0; i < x_max; i++) {
610 clearline[i] = ' ';
611 separator[i] = unicode_supported() ? L'─' : L'-';
612 }
613 clearline[x_max] = 0;
614 separator[x_max] = 0;
615
616 new_mode = false;
617 clear = true;
618 }
619
620 if (clear) {
621 clear_screen(COLOR_NORMAL);
622 clear = false;
623 refresh = true;
624 }
625
626 if (refresh) {
627 for (size_t i = idx_first; i <= idx_last && i < config->n_entries; i++) {
628 print_at(x_start, y_start + i - idx_first,
629 i == idx_highlight ? COLOR_HIGHLIGHT : COLOR_ENTRY,
630 lines[i]);
631 if (i == config->idx_default_efivar)
632 print_at(x_start,
633 y_start + i - idx_first,
634 i == idx_highlight ? COLOR_HIGHLIGHT : COLOR_ENTRY,
635 unicode_supported() ? u" ►" : u"=>");
636 }
637 refresh = false;
638 } else if (highlight) {
639 print_at(x_start, y_start + idx_highlight_prev - idx_first, COLOR_ENTRY, lines[idx_highlight_prev]);
640 print_at(x_start, y_start + idx_highlight - idx_first, COLOR_HIGHLIGHT, lines[idx_highlight]);
641 if (idx_highlight_prev == config->idx_default_efivar)
642 print_at(x_start,
643 y_start + idx_highlight_prev - idx_first,
644 COLOR_ENTRY,
645 unicode_supported() ? u" ►" : u"=>");
646 if (idx_highlight == config->idx_default_efivar)
647 print_at(x_start,
648 y_start + idx_highlight - idx_first,
649 COLOR_HIGHLIGHT,
650 unicode_supported() ? u" ►" : u"=>");
651 highlight = false;
652 }
653
654 if (timeout_remain > 0) {
655 free(status);
656 status = xasprintf("Boot in %"PRIu64"s.", timeout_remain);
657 }
658
659 if (status) {
660 /* If we draw the last char of the last line, the screen will scroll and break our
661 * input. Therefore, draw one less character then we could for the status message.
662 * Note that the same does not apply for the separator line as it will never be drawn
663 * on the last line. */
664 size_t len = strnlen16(status, x_max - 1);
665 size_t x = (x_max - len) / 2;
666 status[len] = '\0';
667 print_at(0, y_status, COLOR_NORMAL, clearline + x_max - x);
668 ST->ConOut->OutputString(ST->ConOut, status);
669 ST->ConOut->OutputString(ST->ConOut, clearline + 1 + x + len);
670
671 len = MIN(MAX(len, line_width) + 2 * entry_padding, x_max);
672 x = (x_max - len) / 2;
673 print_at(x, y_status - 1, COLOR_NORMAL, separator + x_max - len);
674 } else {
675 print_at(0, y_status - 1, COLOR_NORMAL, clearline);
676 print_at(0, y_status, COLOR_NORMAL, clearline + 1); /* See comment above. */
677 }
678
679 /* Beep several times so that the selected entry can be distinguished. */
680 if (config->beep)
681 beep(idx_highlight + 1);
682
683 err = console_key_read(&key, timeout_remain > 0 ? 1000 * 1000 : UINT64_MAX);
684 if (err == EFI_NOT_READY)
685 /* No input device returned a key, try again. This
686 * normally should not happen. */
687 continue;
688 if (err == EFI_TIMEOUT) {
689 assert(timeout_remain > 0);
690 timeout_remain--;
691 if (timeout_remain == 0) {
692 action = ACTION_RUN;
693 break;
694 }
695
696 /* update status */
697 continue;
698 }
699 if (err != EFI_SUCCESS) {
700 action = ACTION_RUN;
701 break;
702 }
703
704 timeout_remain = 0;
705
706 /* clear status after keystroke */
707 status = mfree(status);
708
709 idx_highlight_prev = idx_highlight;
710
711 if (action == ACTION_FIRMWARE_SETUP) {
712 if (IN_SET(key, KEYPRESS(0, 0, '\r'), KEYPRESS(0, 0, '\n')) &&
713 set_reboot_into_firmware() == EFI_SUCCESS)
714 break;
715
716 /* Any key other than newline or a failed attempt cancel the request. */
717 action = ACTION_CONTINUE;
718 continue;
719 }
720
721 switch (key) {
722 case KEYPRESS(0, SCAN_UP, 0):
723 case KEYPRESS(0, SCAN_VOLUME_UP, 0): /* Handle phones/tablets that only have a volume up/down rocker + power key (and otherwise just touchscreen input) */
724 case KEYPRESS(0, 0, 'k'):
725 case KEYPRESS(0, 0, 'K'):
726 if (idx_highlight > 0)
727 idx_highlight--;
728 break;
729
730 case KEYPRESS(0, SCAN_DOWN, 0):
731 case KEYPRESS(0, SCAN_VOLUME_DOWN, 0):
732 case KEYPRESS(0, 0, 'j'):
733 case KEYPRESS(0, 0, 'J'):
734 if (idx_highlight < config->n_entries-1)
735 idx_highlight++;
736 break;
737
738 case KEYPRESS(0, SCAN_HOME, 0):
739 case KEYPRESS(EFI_ALT_PRESSED, 0, '<'):
740 if (idx_highlight > 0) {
741 refresh = true;
742 idx_highlight = 0;
743 }
744 break;
745
746 case KEYPRESS(0, SCAN_END, 0):
747 case KEYPRESS(EFI_ALT_PRESSED, 0, '>'):
748 if (idx_highlight < config->n_entries-1) {
749 refresh = true;
750 idx_highlight = config->n_entries-1;
751 }
752 break;
753
754 case KEYPRESS(0, SCAN_PAGE_UP, 0):
755 if (idx_highlight > visible_max)
756 idx_highlight -= visible_max;
757 else
758 idx_highlight = 0;
759 break;
760
761 case KEYPRESS(0, SCAN_PAGE_DOWN, 0):
762 idx_highlight += visible_max;
763 if (idx_highlight > config->n_entries-1)
764 idx_highlight = config->n_entries-1;
765 break;
766
767 case KEYPRESS(0, 0, '\n'):
768 case KEYPRESS(0, 0, '\r'):
769 case KEYPRESS(0, SCAN_F3, 0): /* EZpad Mini 4s firmware sends malformed events */
770 case KEYPRESS(0, SCAN_F3, '\r'): /* Teclast X98+ II firmware sends malformed events */
771 case KEYPRESS(0, SCAN_RIGHT, 0):
772 case KEYPRESS(0, SCAN_SUSPEND, 0): /* Handle phones/tablets with only a power key + volume up/down rocker (and otherwise just touchscreen input) */
773 action = ACTION_RUN;
774 break;
775
776 case KEYPRESS(0, SCAN_F1, 0):
777 case KEYPRESS(0, 0, 'h'):
778 case KEYPRESS(0, 0, 'H'):
779 case KEYPRESS(0, 0, '?'):
780 /* This must stay below 80 characters! Q/v/Ctrl+l/f deliberately not advertised. */
781 status = xasprintf("(d)efault (t/T)imeout (e)dit (r/R)esolution (p)rint %s%s(h)elp",
782 config->auto_poweroff ? "" : "(O)ff ",
783 config->auto_reboot ? "" : "re(B)oot ");
784 break;
785
786 case KEYPRESS(0, 0, 'Q'):
787 action = ACTION_QUIT;
788 break;
789
790 /* Set/unset the preferred entry */
791 case KEYPRESS(0, 0, 'd'):
792 if (config->idx_default_efivar != idx_highlight) {
793 free(config->entry_preferred_efivar);
794 config->entry_preferred_efivar = xstrdup16(config->entries[idx_highlight]->id);
795 config->idx_default_efivar = idx_highlight;
796 status = xstrdup16(u"Preferred boot entry selected.");
797 } else {
798 config->entry_preferred_efivar = mfree(config->entry_preferred_efivar);
799 config->idx_default_efivar = IDX_INVALID;
800 status = xstrdup16(u"Preferred boot entry cleared.");
801 }
802 config->entry_default_efivar = mfree(config->entry_default_efivar);
803 config->use_saved_entry_efivar = false;
804 config->use_saved_entry_preferred_efivar = false;
805 refresh = true;
806 break;
807
808 /* Set/unset the default entry */
809 case KEYPRESS(0, 0, 'D'):
810 if (config->idx_default_efivar != idx_highlight) {
811 free(config->entry_default_efivar);
812 config->entry_default_efivar = xstrdup16(config->entries[idx_highlight]->id);
813 config->idx_default_efivar = idx_highlight;
814 status = xstrdup16(u"Default boot entry selected.");
815 } else {
816 config->entry_default_efivar = mfree(config->entry_default_efivar);
817 config->idx_default_efivar = IDX_INVALID;
818 status = xstrdup16(u"Default boot entry cleared.");
819 }
820 config->entry_preferred_efivar = mfree(config->entry_preferred_efivar);
821 config->use_saved_entry_efivar = false;
822 config->use_saved_entry_preferred_efivar = false;
823 refresh = true;
824 break;
825
826 case KEYPRESS(0, 0, '-'):
827 case KEYPRESS(0, 0, 'T'):
828 status = update_timeout_efivar(config, false);
829 break;
830
831 case KEYPRESS(0, 0, '+'):
832 case KEYPRESS(0, 0, 't'):
833 status = update_timeout_efivar(config, true);
834 break;
835
836 case KEYPRESS(0, 0, 'e'):
837 case KEYPRESS(0, 0, 'E'):
838 /* only the options of configured entries can be edited */
839 if (!config->editor ||
840 !LOADER_TYPE_ALLOW_EDITOR(config->entries[idx_highlight]->type)) {
841 status = xstrdup16(u"Entry does not support editing the command line.");
842 break;
843 }
844
845 /* Unified kernels that are signed as a whole will not accept command line options
846 * when secure boot is enabled unless there is none embedded in the image. Do not try
847 * to pretend we can edit it to only have it be ignored. */
848 if (!LOADER_TYPE_ALLOW_EDITOR_IN_SB(config->entries[idx_highlight]->type) &&
849 secure_boot_enabled() &&
850 config->entries[idx_highlight]->options) {
851 status = xstrdup16(u"Entry not editable in SecureBoot mode.");
852 break;
853 }
854
855 /* The edit line may end up on the last line of the screen. And even though we're
856 * not telling the firmware to advance the line, it still does in this one case,
857 * causing a scroll to happen that screws with our beautiful boot loader output.
858 * Since we cannot paint the last character of the edit line, we simply start
859 * at x-offset 1 for symmetry. */
860 print_at(1, y_status, COLOR_EDIT, clearline + 2);
861 if (line_edit(&config->entries[idx_highlight]->options, x_max - 2, y_status))
862 action = ACTION_RUN;
863 print_at(1, y_status, COLOR_NORMAL, clearline + 2);
864
865 /* The options string was now edited, hence we have to pass it to the invoked
866 * binary. */
867 config->entries[idx_highlight]->options_implied = false;
868 break;
869
870 case KEYPRESS(0, 0, 'v'):
871 status = xasprintf(
872 "systemd-boot " GIT_VERSION " (" EFI_MACHINE_TYPE_NAME "), "
873 "UEFI Specification %u.%02u, Vendor %ls %u.%02u",
874 ST->Hdr.Revision >> 16,
875 ST->Hdr.Revision & 0xffff,
876 ST->FirmwareVendor,
877 ST->FirmwareRevision >> 16,
878 ST->FirmwareRevision & 0xffff);
879 break;
880
881 case KEYPRESS(0, 0, 'p'):
882 case KEYPRESS(0, 0, 'P'):
883 print_status(config, loaded_image_path);
884 clear = true;
885 break;
886
887 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'l'):
888 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('l')):
889 case 'L': /* only uppercase, do not conflict with lower-case 'l' which picks first Linux entry */
890 clear = true;
891 break;
892
893 case KEYPRESS(0, 0, 'r'):
894 err = console_set_mode(CONSOLE_MODE_NEXT);
895 if (err != EFI_SUCCESS)
896 status = xasprintf_status(err, "Error changing console mode: %m");
897 else {
898 config->console_mode_efivar = ST->ConOut->Mode->Mode;
899 status = xasprintf(
900 "Console mode changed to %" PRIi64 ".",
901 config->console_mode_efivar);
902 }
903 new_mode = true;
904 break;
905
906 case KEYPRESS(0, 0, 'R'):
907 config->console_mode_efivar = CONSOLE_MODE_KEEP;
908 err = console_set_mode(config->console_mode == CONSOLE_MODE_KEEP ?
909 console_mode_initial : config->console_mode);
910 if (err != EFI_SUCCESS)
911 status = xasprintf_status(err, "Error resetting console mode: %m");
912 else
913 status = xasprintf(
914 "Console mode reset to %s default.",
915 config->console_mode == CONSOLE_MODE_KEEP ?
916 "firmware" :
917 "configuration file");
918 new_mode = true;
919 break;
920
921 case KEYPRESS(0, 0, 'f'):
922 case KEYPRESS(0, 0, 'F'):
923 case KEYPRESS(0, SCAN_F2, 0): /* Most vendors. */
924 case KEYPRESS(0, SCAN_F10, 0): /* HP and Lenovo. */
925 case KEYPRESS(0, SCAN_DELETE, 0): /* Same as F2. */
926 case KEYPRESS(0, SCAN_ESC, 0): /* HP. */
927 if (FLAGS_SET(get_os_indications_supported(), EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
928 action = ACTION_FIRMWARE_SETUP;
929 /* Let's make sure the user really wants to do this. */
930 status = xstrdup16(u"Press Enter to reboot into firmware interface.");
931 } else
932 status = xstrdup16(u"Reboot into firmware interface not supported.");
933 break;
934
935 case KEYPRESS(0, 0, 'O'): /* Only uppercase, so that it can't be hit so easily fat-fingered,
936 * but still works safely over serial. */
937 action = ACTION_POWEROFF;
938 break;
939
940 case KEYPRESS(0, 0, 'B'): /* ditto */
941 action = ACTION_REBOOT;
942 break;
943
944 default:
945 /* jump with a hotkey directly to a matching entry */
946 idx = entry_lookup_key(config, idx_highlight+1, KEYCHAR(key));
947 if (idx == IDX_INVALID)
948 break;
949 idx_highlight = idx;
950 refresh = true;
951 }
952
953 if (idx_highlight > idx_last) {
954 idx_last = idx_highlight;
955 idx_first = 1 + idx_highlight - visible_max;
956 refresh = true;
957 } else if (idx_highlight < idx_first) {
958 idx_first = idx_highlight;
959 idx_last = idx_highlight + visible_max-1;
960 refresh = true;
961 }
962
963 if (!refresh && idx_highlight != idx_highlight_prev)
964 highlight = true;
965 }
966
967 /* Update EFI vars after we left the menu to reduce NVRAM writes. */
968
969 if (default_efivar_saved != config->idx_default_efivar) {
970 if (config->entry_preferred_efivar)
971 efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryPreferred", config->entry_preferred_efivar, EFI_VARIABLE_NON_VOLATILE);
972 else
973 efivar_unset(MAKE_GUID_PTR(LOADER), u"LoaderEntryPreferred", EFI_VARIABLE_NON_VOLATILE);
974
975 if (config->entry_default_efivar)
976 efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryDefault", config->entry_default_efivar, EFI_VARIABLE_NON_VOLATILE);
977 else
978 efivar_unset(MAKE_GUID_PTR(LOADER), u"LoaderEntryDefault", EFI_VARIABLE_NON_VOLATILE);
979 }
980
981 if (console_mode_efivar_saved != config->console_mode_efivar) {
982 if (config->console_mode_efivar == CONSOLE_MODE_KEEP)
983 efivar_unset(MAKE_GUID_PTR(LOADER), u"LoaderConfigConsoleMode", EFI_VARIABLE_NON_VOLATILE);
984 else
985 efivar_set_uint64_str16(MAKE_GUID_PTR(LOADER), u"LoaderConfigConsoleMode",
986 config->console_mode_efivar, EFI_VARIABLE_NON_VOLATILE);
987 }
988
989 if (timeout_efivar_saved != config->timeout_sec_efivar) {
990 switch (config->timeout_sec_efivar) {
991 case TIMEOUT_UNSET:
992 efivar_unset(MAKE_GUID_PTR(LOADER), u"LoaderConfigTimeout", EFI_VARIABLE_NON_VOLATILE);
993 break;
994 case TIMEOUT_MENU_DISABLED:
995 assert_not_reached();
996 case TIMEOUT_MENU_FORCE:
997 efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderConfigTimeout", u"menu-force", EFI_VARIABLE_NON_VOLATILE);
998 break;
999 case TIMEOUT_MENU_HIDDEN:
1000 efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderConfigTimeout", u"menu-hidden", EFI_VARIABLE_NON_VOLATILE);
1001 break;
1002 default:
1003 assert(config->timeout_sec_efivar < UINT32_MAX);
1004 efivar_set_uint64_str16(MAKE_GUID_PTR(LOADER), u"LoaderConfigTimeout",
1005 config->timeout_sec_efivar, EFI_VARIABLE_NON_VOLATILE);
1006 }
1007 }
1008
1009 switch (action) {
1010 case ACTION_CONTINUE:
1011 assert_not_reached();
1012 case ACTION_POWEROFF:
1013 (void) call_poweroff_system(/* entry= */ NULL, /* root_dir= */ NULL, /* parent_image= */ NULL);
1014 case ACTION_REBOOT:
1015 case ACTION_FIRMWARE_SETUP:
1016 (void) call_reboot_system(/* entry= */ NULL, /* root_dir= */ NULL, /* parent_image= */ NULL);
1017 case ACTION_RUN:
1018 case ACTION_QUIT:
1019 break;
1020 }
1021
1022 *chosen_entry = config->entries[idx_highlight];
1023 clear_screen(COLOR_NORMAL);
1024 return action == ACTION_RUN;
1025 }
1026
1027 static void config_add_entry(Config *config, BootEntry *entry) {
1028 assert(config);
1029 assert(entry);
1030
1031 /* This is just for paranoia. */
1032 assert(config->n_entries < IDX_MAX);
1033
1034 if ((config->n_entries & 15) == 0)
1035 config->entries = xrealloc(
1036 config->entries,
1037 sizeof(void *) * config->n_entries,
1038 sizeof(void *) * (config->n_entries + 16));
1039 config->entries[config->n_entries++] = entry;
1040 }
1041
1042 static BootEntry* boot_entry_free(BootEntry *entry) {
1043 if (!entry)
1044 return NULL;
1045
1046 free(entry->id);
1047 free(entry->id_without_profile);
1048 free(entry->title_show);
1049 free(entry->title);
1050 free(entry->sort_key);
1051 free(entry->version);
1052 free(entry->machine_id);
1053 free(entry->loader);
1054 free(entry->url);
1055 free(entry->devicetree);
1056 free(entry->options);
1057 strv_free(entry->initrd);
1058 strv_free(entry->extras);
1059 free(entry->directory);
1060 free(entry->current_name);
1061 free(entry->next_name);
1062
1063 return mfree(entry);
1064 }
1065
1066 DEFINE_TRIVIAL_CLEANUP_FUNC(BootEntry *, boot_entry_free);
1067
1068 static EFI_STATUS config_timeout_sec_from_string(const char *value, uint64_t *dst) {
1069 assert(dst);
1070
1071 if (streq8(value, "menu-disabled"))
1072 *dst = TIMEOUT_MENU_DISABLED;
1073 else if (streq8(value, "menu-force"))
1074 *dst = TIMEOUT_MENU_FORCE;
1075 else if (streq8(value, "menu-hidden"))
1076 *dst = TIMEOUT_MENU_HIDDEN;
1077 else {
1078 uint64_t u;
1079 if (!parse_number8(value, &u, NULL) || u > TIMEOUT_TYPE_MAX)
1080 return EFI_INVALID_PARAMETER;
1081 *dst = u;
1082 }
1083 return EFI_SUCCESS;
1084 }
1085
1086 static void config_timeout_load_from_smbios(Config *config) {
1087 EFI_STATUS err;
1088
1089 if (is_confidential_vm())
1090 return; /* Don't consume SMBIOS in Confidential Computing contexts */
1091
1092 const char *value = smbios_find_oem_string("io.systemd.boot.timeout=", /* after= */ NULL);
1093 if (!value)
1094 return;
1095
1096 err = config_timeout_sec_from_string(value, &config->timeout_sec_smbios);
1097 if (err != EFI_SUCCESS) {
1098 log_warning_status(err, "Error parsing 'timeout' smbios option, ignoring: %s",
1099 value);
1100 return;
1101 }
1102 config->timeout_sec = config->timeout_sec_smbios;
1103 }
1104
1105 static void config_defaults_load_from_file(Config *config, char *content) {
1106 char *line;
1107 size_t pos = 0;
1108 char *key, *value;
1109
1110 assert(config);
1111 assert(content);
1112
1113 /* If you add, remove, or change an option name here, please also update
1114 * shared/bootspec.c@boot_loader_read_conf() to make parsing by bootctl/logind/etc. work. */
1115 while ((line = line_get_key_value(content, " \t", &pos, &key, &value)))
1116 if (streq8(key, "timeout")) {
1117 EFI_STATUS err = config_timeout_sec_from_string(value, &config->timeout_sec_config);
1118 if (err != EFI_SUCCESS) {
1119 log_warning_status(err, "Error parsing 'timeout' config option, ignoring: %s",
1120 value);
1121 continue;
1122 }
1123 config->timeout_sec = config->timeout_sec_config;
1124
1125 } else if (streq8(key, "default")) {
1126 if (value[0] == '@' && !strcaseeq8(value, "@saved")) {
1127 log_warning("Unsupported special entry identifier, ignoring: %s", value);
1128 continue;
1129 }
1130 free(config->entry_default_config);
1131 config->entry_default_config = xstr8_to_16(value);
1132
1133 } else if (streq8(key, "preferred")) {
1134 if (value[0] == '@' && !strcaseeq8(value, "@saved")) {
1135 log_warning("Unsupported special entry identifier, ignoring: %s", value);
1136 continue;
1137 }
1138 free(config->entry_preferred_config);
1139 config->entry_preferred_config = xstr8_to_16(value);
1140
1141 } else if (streq8(key, "editor")) {
1142 if (!parse_boolean(value, &config->editor))
1143 log_warning("Error parsing 'editor' config option, ignoring: %s", value);
1144
1145 } else if (streq8(key, "auto-entries")) {
1146 if (!parse_boolean(value, &config->auto_entries))
1147 log_warning("Error parsing 'auto-entries' config option, ignoring: %s", value);
1148
1149 } else if (streq8(key, "auto-firmware")) {
1150 if (!parse_boolean(value, &config->auto_firmware))
1151 log_warning("Error parsing 'auto-firmware' config option, ignoring: %s", value);
1152
1153 } else if (streq8(key, "auto-poweroff")) {
1154 if (!parse_boolean(value, &config->auto_poweroff))
1155 log_warning("Error parsing 'auto-poweroff' config option, ignoring: %s", value);
1156
1157 } else if (streq8(key, "auto-reboot")) {
1158 if (!parse_boolean(value, &config->auto_reboot))
1159 log_warning("Error parsing 'auto-reboot' config option, ignoring: %s", value);
1160
1161 } else if (streq8(key, "beep")) {
1162 if (!parse_boolean(value, &config->beep))
1163 log_warning("Error parsing 'beep' config option, ignoring: %s", value);
1164
1165 } else if (streq8(key, "reboot-for-bitlocker")) {
1166 if (!parse_boolean(value, &config->reboot_for_bitlocker))
1167 log_warning("Error parsing 'reboot-for-bitlocker' config option, ignoring: %s",
1168 value);
1169
1170 } else if (streq8(key, "reboot-on-error")) {
1171 if (streq8(value, "auto"))
1172 config->reboot_on_error = REBOOT_AUTO;
1173 else {
1174 bool reboot_yes_no;
1175 if (!parse_boolean(value, &reboot_yes_no))
1176 log_warning("Error parsing 'reboot-on-error' config option, ignoring: %s", value);
1177 else
1178 config->reboot_on_error = reboot_yes_no ? REBOOT_YES : REBOOT_NO;
1179 }
1180
1181 } else if (streq8(key, "secure-boot-enroll")) {
1182 if (streq8(value, "manual"))
1183 config->secure_boot_enroll = ENROLL_MANUAL;
1184 else if (streq8(value, "force"))
1185 config->secure_boot_enroll = ENROLL_FORCE;
1186 else if (streq8(value, "if-safe"))
1187 config->secure_boot_enroll = ENROLL_IF_SAFE;
1188 else if (streq8(value, "off"))
1189 config->secure_boot_enroll = ENROLL_OFF;
1190 else
1191 log_warning("Error parsing 'secure-boot-enroll' config option, ignoring: %s",
1192 value);
1193 } else if (streq8(key, "secure-boot-enroll-action")) {
1194 if (streq8(value, "reboot"))
1195 config->secure_boot_enroll_action = ENROLL_ACTION_REBOOT;
1196 else if (streq8(value, "shutdown"))
1197 config->secure_boot_enroll_action = ENROLL_ACTION_SHUTDOWN;
1198 else
1199 log_warning("Error parsing 'secure-boot-enroll-action' config option, ignoring: %s",
1200 value);
1201 } else if (streq8(key, "secure-boot-enroll-timeout-sec")) {
1202 if (streq8(value, "hidden"))
1203 config->secure_boot_enroll_timeout_sec = ENROLL_TIMEOUT_HIDDEN;
1204 else {
1205 uint64_t u;
1206 if (!parse_number8(value, &u, NULL) || u > ENROLL_TIMEOUT_MAX) {
1207 log_warning("Error parsing 'secure-boot-enroll-timeout-sec' config option, ignoring: %s",
1208 value);
1209 continue;
1210 }
1211 config->secure_boot_enroll_timeout_sec = u;
1212 }
1213 } else if (streq8(key, "console-mode")) {
1214 if (streq8(value, "auto"))
1215 config->console_mode = CONSOLE_MODE_AUTO;
1216 else if (streq8(value, "max"))
1217 config->console_mode = CONSOLE_MODE_FIRMWARE_MAX;
1218 else if (streq8(value, "keep"))
1219 config->console_mode = CONSOLE_MODE_KEEP;
1220 else {
1221 uint64_t u;
1222 if (!parse_number8(value, &u, NULL) || u > CONSOLE_MODE_RANGE_MAX) {
1223 log_warning("Error parsing 'console-mode' config option, ignoring: %s",
1224 value);
1225 continue;
1226 }
1227 config->console_mode = u;
1228 }
1229 } else if (streq8(key, "log-level")) {
1230 if (log_set_max_level_from_string(value) < 0)
1231 log_warning("Error parsing 'log-level' config option, ignoring: %s", value);
1232 }
1233 }
1234
1235 static void boot_entry_parse_tries(
1236 BootEntry *entry,
1237 const char16_t *directory,
1238 const char16_t *file,
1239 const char16_t *suffix) {
1240
1241 assert(entry);
1242 assert(directory);
1243 assert(file);
1244 assert(suffix);
1245
1246 /*
1247 * Parses a suffix of two counters (one going down, one going up) in the form "+LEFT-DONE" from the end of the
1248 * filename (but before the .efi/.conf suffix), where the "-DONE" part is optional and may be left out (in
1249 * which case that counter as assumed to be zero, i.e. the missing part is synonymous to "-0").
1250 *
1251 * Names we grok, and the series they result in:
1252 *
1253 * foobar+3.efi → foobar+2-1.efi → foobar+1-2.efi → foobar+0-3.efi → STOP!
1254 * foobar+4-0.efi → foobar+3-1.efi → foobar+2-2.efi → foobar+1-3.efi → foobar+0-4.efi → STOP!
1255 */
1256
1257 const char16_t *counter = NULL;
1258 for (;;) {
1259 char16_t *plus = strchr16(counter ?: file, '+');
1260 if (plus) {
1261 /* We want the last "+". */
1262 counter = plus + 1;
1263 continue;
1264 }
1265 if (counter)
1266 break;
1267
1268 /* No boot counter found. */
1269 return;
1270 }
1271
1272 uint64_t tries_left, tries_done = 0;
1273 size_t prefix_len = counter - file;
1274
1275 if (!parse_number16(counter, &tries_left, &counter) || tries_left > INT_MAX)
1276 return;
1277
1278 /* Parse done counter only if present. */
1279 if (*counter == '-' && (!parse_number16(counter + 1, &tries_done, &counter) || tries_done > INT_MAX))
1280 return;
1281
1282 /* Boot counter in the middle of the name? */
1283 if (!strcaseeq16(counter, suffix))
1284 return;
1285
1286 entry->id = xasprintf("%.*ls%ls",
1287 (int) prefix_len - 1,
1288 file,
1289 suffix);
1290 entry->tries_left = tries_left;
1291 entry->tries_done = tries_done;
1292 entry->directory = xstrdup16(directory);
1293 entry->current_name = xstrdup16(file);
1294 entry->next_name = xasprintf(
1295 "%.*ls%" PRIu64 "-%" PRIu64 "%ls",
1296 (int) prefix_len,
1297 file,
1298 LESS_BY(tries_left, 1u),
1299 MIN(tries_done + 1, (uint64_t) INT_MAX),
1300 suffix);
1301 }
1302
1303 static EFI_STATUS boot_entry_bump_counters(BootEntry *entry) {
1304 _cleanup_free_ char16_t* old_path = NULL, *new_path = NULL;
1305 _cleanup_file_close_ EFI_FILE *handle = NULL;
1306 _cleanup_free_ EFI_FILE_INFO *file_info = NULL;
1307 size_t file_info_size;
1308 EFI_STATUS err;
1309
1310 assert(entry);
1311
1312 if (!LOADER_TYPE_BUMP_COUNTERS(entry->type))
1313 return EFI_SUCCESS;
1314
1315 if (entry->tries_left < 0)
1316 return EFI_SUCCESS;
1317
1318 if (!entry->directory || !entry->current_name || !entry->next_name)
1319 return EFI_SUCCESS;
1320
1321 _cleanup_file_close_ EFI_FILE *root = NULL;
1322 err = open_volume(entry->device, &root);
1323 if (err != EFI_SUCCESS)
1324 return log_error_status(err, "Error opening entry root path: %m");
1325
1326 old_path = xasprintf("%ls\\%ls", entry->directory, entry->current_name);
1327
1328 err = root->Open(root, &handle, old_path, EFI_FILE_MODE_READ|EFI_FILE_MODE_WRITE, 0ULL);
1329 if (err != EFI_SUCCESS)
1330 return log_error_status(err, "Error opening boot entry '%ls': %m", old_path);
1331
1332 err = get_file_info(handle, &file_info, &file_info_size);
1333 if (err != EFI_SUCCESS)
1334 return log_error_status(err, "Error getting boot entry file info: %m");
1335
1336 /* And rename the file */
1337 strcpy16(file_info->FileName, entry->next_name);
1338 err = handle->SetInfo(handle, MAKE_GUID_PTR(EFI_FILE_INFO), file_info_size, file_info);
1339 if (err != EFI_SUCCESS)
1340 return log_error_status(
1341 err, "Failed to rename '%ls' to '%ls', ignoring: %m", old_path, entry->next_name);
1342
1343 /* Flush everything to disk, just in case… */
1344 err = handle->Flush(handle);
1345 if (err != EFI_SUCCESS)
1346 return log_error_status(err, "Error flushing boot entry file info: %m");
1347
1348 /* Let's tell the OS that we renamed this file, so that it knows what to rename to the counter-less name on
1349 * success */
1350 new_path = xasprintf("%ls\\%ls", entry->directory, entry->next_name);
1351 efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderBootCountPath", new_path, 0);
1352
1353 /* If the file we just renamed is the loader path, then let's update that. */
1354 if (streq16(entry->loader, old_path)) {
1355 free(entry->loader);
1356 entry->loader = TAKE_PTR(new_path);
1357 }
1358
1359 return EFI_SUCCESS;
1360 }
1361
1362 static EFI_STATUS call_image_start(const BootEntry *entry, EFI_FILE *root_dir, EFI_HANDLE parent_image);
1363
1364 static void boot_entry_add_type1(
1365 Config *config,
1366 EFI_HANDLE *device,
1367 EFI_FILE *root_dir,
1368 const char16_t *path,
1369 const char16_t *file,
1370 char *content,
1371 const char16_t *loaded_image_path) {
1372
1373 _cleanup_(boot_entry_freep) BootEntry *entry = NULL;
1374 char *line;
1375 size_t pos = 0, n_initrd = 0, n_extras = 0;
1376 char *key, *value;
1377 EFI_STATUS err;
1378
1379 assert(config);
1380 assert(device);
1381 assert(root_dir);
1382 assert(file);
1383 assert(content);
1384
1385 entry = xnew(BootEntry, 1);
1386 *entry = (BootEntry) {
1387 .tries_done = -1,
1388 .tries_left = -1,
1389 .call = call_image_start,
1390 };
1391
1392 /* If you add, remove, or change an option name here, please also update shared/bootspec.c and
1393 * shared/varlink-io.systemd.BootControl to make parsing by bootctl/logind/etc. work. */
1394 while ((line = line_get_key_value(content, " \t", &pos, &key, &value)))
1395 if (streq8(key, "title")) {
1396 free(entry->title);
1397 entry->title = xstr8_to_16(value);
1398
1399 } else if (streq8(key, "sort-key")) {
1400 free(entry->sort_key);
1401 entry->sort_key = xstr8_to_16(value);
1402
1403 } else if (streq8(key, "profile")) {
1404 uint64_t u;
1405 if (parse_number8(value, &u, NULL) && u <= UINT_MAX)
1406 entry->profile = (unsigned)u;
1407 else
1408 log_warning("Error parsing 'profile' entry option, ignoring: %s", value);
1409
1410 } else if (streq8(key, "version")) {
1411 free(entry->version);
1412 entry->version = xstr8_to_16(value);
1413
1414 } else if (streq8(key, "machine-id")) {
1415 free(entry->machine_id);
1416 entry->machine_id = xstr8_to_16(value);
1417
1418 } else if (streq8(key, "linux")) {
1419
1420 if (!IN_SET(entry->type, LOADER_UNDEFINED, LOADER_LINUX)) {
1421 entry->type = LOADER_BAD;
1422 break;
1423 }
1424
1425 free(entry->loader);
1426 entry->type = LOADER_LINUX;
1427 entry->loader = xstr8_to_path(value);
1428 entry->key = 'l';
1429
1430 } else if (streq8(key, "uki")) {
1431
1432 if (!IN_SET(entry->type, LOADER_UNDEFINED, LOADER_UKI)) {
1433 entry->type = LOADER_BAD;
1434 break;
1435 }
1436
1437 free(entry->loader);
1438 entry->type = LOADER_UKI;
1439 entry->loader = xstr8_to_path(value);
1440 entry->key = 'l';
1441
1442 } else if (streq8(key, "uki-url")) {
1443
1444 if (!IN_SET(entry->type, LOADER_UNDEFINED, LOADER_UKI_URL)) {
1445 entry->type = LOADER_BAD;
1446 break;
1447 }
1448
1449 _cleanup_free_ char16_t *p = xstr8_to_16(value);
1450
1451 const char16_t *e = startswith(p, u":");
1452 if (e) {
1453 _cleanup_free_ char16_t *origin = disk_get_url(device);
1454
1455 if (!origin) {
1456 /* Automatically hide entries that require an original URL but where none is available. */
1457 entry->type = LOADER_IGNORE;
1458 break;
1459 }
1460
1461 entry->url = url_replace_last_component(origin, p);
1462 } else
1463 entry->url = TAKE_PTR(p);
1464
1465 entry->type = LOADER_UKI_URL;
1466 entry->key = 'l';
1467
1468 } else if (streq8(key, "efi")) {
1469
1470 if (!IN_SET(entry->type, LOADER_UNDEFINED, LOADER_EFI)) {
1471 entry->type = LOADER_BAD;
1472 break;
1473 }
1474
1475 entry->type = LOADER_EFI;
1476 free(entry->loader);
1477 entry->loader = xstr8_to_path(value);
1478
1479 /* do not add an entry for ourselves */
1480 if (strcaseeq16(entry->loader, loaded_image_path)) {
1481 entry->type = LOADER_IGNORE;
1482 break;
1483 }
1484
1485 } else if (streq8(key, "architecture")) {
1486 /* do not add an entry for an EFI image of architecture not matching with that of the image */
1487 if (!strcaseeq8(value, EFI_MACHINE_TYPE_NAME)) {
1488 entry->type = LOADER_IGNORE;
1489 break;
1490 }
1491
1492 } else if (streq8(key, "devicetree")) {
1493 free(entry->devicetree);
1494 entry->devicetree = xstr8_to_path(value);
1495
1496 } else if (streq8(key, "initrd")) {
1497 entry->initrd = xrealloc(
1498 entry->initrd,
1499 n_initrd == 0 ? 0 : (n_initrd + 1) * sizeof(uint16_t *),
1500 (n_initrd + 2) * sizeof(uint16_t *));
1501 entry->initrd[n_initrd++] = xstr8_to_path(value);
1502 entry->initrd[n_initrd] = NULL;
1503
1504 } else if (streq8(key, "extra")) {
1505 entry->extras = xrealloc(
1506 entry->extras,
1507 n_extras == 0 ? 0 : (n_extras + 1) * sizeof(uint16_t *),
1508 (n_extras + 2) * sizeof(uint16_t *));
1509 entry->extras[n_extras++] = xstr8_to_path(value);
1510 entry->extras[n_extras] = NULL;
1511
1512 } else if (streq8(key, "options")) {
1513 _cleanup_free_ char16_t *new = NULL;
1514
1515 new = xstr8_to_16(value);
1516 if (entry->options) {
1517 char16_t *s = xasprintf("%ls %ls", entry->options, new);
1518 free(entry->options);
1519 entry->options = s;
1520 } else
1521 entry->options = TAKE_PTR(new);
1522 }
1523
1524 /* Filter all entries that are badly defined or don't apply to the local system. */
1525 if (IN_SET(entry->type, LOADER_UNDEFINED, LOADER_BAD, LOADER_IGNORE))
1526 return;
1527
1528 /* Check existence of loader file */
1529 if (entry->loader) {
1530 _cleanup_file_close_ EFI_FILE *handle = NULL;
1531 err = root_dir->Open(root_dir, &handle, entry->loader, EFI_FILE_MODE_READ, 0ULL);
1532 if (err != EFI_SUCCESS)
1533 return;
1534 }
1535
1536 entry->device = device;
1537
1538 if (path)
1539 boot_entry_parse_tries(entry, path, file, u".conf");
1540
1541 if (!entry->id)
1542 entry->id = xstrdup16(file);
1543
1544 strtolower16(entry->id);
1545
1546 config_add_entry(config, entry);
1547 TAKE_PTR(entry);
1548 }
1549
1550 static EFI_STATUS efivar_get_timeout(const char16_t *var, uint64_t *ret_value) {
1551 _cleanup_free_ char16_t *value = NULL;
1552 EFI_STATUS err;
1553
1554 assert(var);
1555 assert(ret_value);
1556
1557 err = efivar_get_str16(MAKE_GUID_PTR(LOADER), var, &value);
1558 if (err != EFI_SUCCESS)
1559 return err;
1560
1561 if (streq16(value, u"menu-disabled")) {
1562 *ret_value = TIMEOUT_MENU_DISABLED;
1563 return EFI_SUCCESS;
1564 }
1565 if (streq16(value, u"menu-force")) {
1566 *ret_value = TIMEOUT_MENU_FORCE;
1567 return EFI_SUCCESS;
1568 }
1569 if (streq16(value, u"menu-hidden")) {
1570 *ret_value = TIMEOUT_MENU_HIDDEN;
1571 return EFI_SUCCESS;
1572 }
1573
1574 uint64_t timeout;
1575 if (!parse_number16(value, &timeout, NULL))
1576 return EFI_INVALID_PARAMETER;
1577
1578 *ret_value = MIN(timeout, TIMEOUT_TYPE_MAX);
1579 return EFI_SUCCESS;
1580 }
1581
1582 static void config_load_defaults(Config *config, EFI_FILE *root_dir) {
1583 _cleanup_free_ char *content = NULL;
1584 size_t content_size;
1585 EFI_STATUS err;
1586
1587 assert(root_dir);
1588 assert(config);
1589
1590 *config = (Config) {
1591 .editor = true,
1592 .auto_entries = true,
1593 .auto_firmware = true,
1594 .reboot_on_error = REBOOT_AUTO,
1595 .secure_boot_enroll = ENROLL_IF_SAFE,
1596 .secure_boot_enroll_action = ENROLL_ACTION_REBOOT,
1597 .secure_boot_enroll_timeout_sec = ENROLL_TIMEOUT_DEFAULT,
1598 .idx_default_efivar = IDX_INVALID,
1599 .console_mode = CONSOLE_MODE_KEEP,
1600 .console_mode_efivar = CONSOLE_MODE_KEEP,
1601 .timeout_sec_config = TIMEOUT_UNSET,
1602 .timeout_sec_efivar = TIMEOUT_UNSET,
1603 .timeout_sec_smbios = TIMEOUT_UNSET,
1604 };
1605
1606 err = file_read(root_dir, u"\\loader\\loader.conf", 0, 0, &content, &content_size);
1607 if (err == EFI_SUCCESS) {
1608 /* First, measure. */
1609 err = tpm_log_tagged_event(
1610 TPM2_PCR_BOOT_LOADER_CONFIG,
1611 POINTER_TO_PHYSICAL_ADDRESS(content),
1612 content_size,
1613 LOADER_CONF_EVENT_TAG_ID,
1614 u"loader.conf",
1615 /* ret_measured= */ NULL);
1616 if (err != EFI_SUCCESS)
1617 log_error_status(err, "Error measuring loader.conf into TPM: %m");
1618
1619 /* Then: parse */
1620 config_defaults_load_from_file(config, content);
1621 }
1622
1623 err = efivar_get_timeout(u"LoaderConfigTimeout", &config->timeout_sec_efivar);
1624 if (err == EFI_SUCCESS)
1625 config->timeout_sec = config->timeout_sec_efivar;
1626 else if (err != EFI_NOT_FOUND)
1627 log_warning_status(err, "Error reading LoaderConfigTimeout EFI variable, ignoring: %m");
1628 config_timeout_load_from_smbios(config);
1629
1630 err = efivar_get_timeout(u"LoaderConfigTimeoutOneShot", &config->timeout_sec);
1631 if (err == EFI_SUCCESS) {
1632 /* Unset variable now, after all it's "one shot". */
1633 (void) efivar_unset(MAKE_GUID_PTR(LOADER), u"LoaderConfigTimeoutOneShot", EFI_VARIABLE_NON_VOLATILE);
1634
1635 config->force_menu = true; /* force the menu when this is set */
1636 } else if (err != EFI_NOT_FOUND)
1637 log_warning_status(err, "Error reading LoaderConfigTimeoutOneShot EFI variable, ignoring: %m");
1638
1639 uint64_t value;
1640 err = efivar_get_uint64_str16(MAKE_GUID_PTR(LOADER), u"LoaderConfigConsoleMode", &value);
1641 if (err == EFI_SUCCESS && value <= INT64_MAX)
1642 config->console_mode_efivar = value;
1643
1644 err = efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryOneShot", &config->entry_oneshot);
1645 if (err == EFI_SUCCESS)
1646 /* Unset variable now, after all it's "one shot". */
1647 (void) efivar_unset(MAKE_GUID_PTR(LOADER), u"LoaderEntryOneShot", EFI_VARIABLE_NON_VOLATILE);
1648
1649 (void) efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryDefault", &config->entry_default_efivar);
1650 (void) efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryPreferred", &config->entry_preferred_efivar);
1651 (void) efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntrySysFail", &config->entry_sysfail);
1652
1653 strtolower16(config->entry_default_config);
1654 strtolower16(config->entry_default_efivar);
1655 strtolower16(config->entry_preferred_config);
1656 strtolower16(config->entry_preferred_efivar);
1657 strtolower16(config->entry_oneshot);
1658 strtolower16(config->entry_saved);
1659 strtolower16(config->entry_sysfail);
1660
1661 config->use_saved_entry = streq16(config->entry_default_config, u"@saved");
1662 config->use_saved_entry_efivar = streq16(config->entry_default_efivar, u"@saved");
1663 config->use_saved_entry_preferred = streq16(config->entry_preferred_config, u"@saved");
1664 config->use_saved_entry_preferred_efivar = streq16(config->entry_preferred_efivar, u"@saved");
1665 if (config->use_saved_entry || config->use_saved_entry_efivar || config->use_saved_entry_preferred || config->use_saved_entry_preferred_efivar)
1666 (void) efivar_get_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryLastBooted", &config->entry_saved);
1667
1668 }
1669
1670 static bool valid_type1_filename(const char16_t *fname) {
1671 assert(fname);
1672
1673 if (IN_SET(fname[0], u'.', u'\0'))
1674 return false;
1675 if (!endswith_no_case(fname, u".conf"))
1676 return false;
1677 if (startswith_no_case(fname, u"auto-"))
1678 return false;
1679
1680 return true;
1681 }
1682
1683 static void config_load_type1_entries(
1684 Config *config,
1685 EFI_HANDLE *device,
1686 EFI_FILE *root_dir,
1687 const char16_t *loaded_image_path) {
1688
1689 _cleanup_file_close_ EFI_FILE *entries_dir = NULL;
1690 _cleanup_free_ EFI_FILE_INFO *f = NULL;
1691 size_t f_size = 0;
1692 EFI_STATUS err;
1693
1694 assert(config);
1695 assert(device);
1696 assert(root_dir);
1697
1698 /* Adds Boot Loader Type #1 entries (i.e. /loader/entries/….conf) */
1699
1700 const uint16_t dropin_path[] = u"\\loader\\entries";
1701
1702 err = open_directory(root_dir, dropin_path, &entries_dir);
1703 if (err != EFI_SUCCESS)
1704 return;
1705
1706 for (;;) {
1707 _cleanup_free_ char *content = NULL;
1708
1709 err = readdir(entries_dir, &f, &f_size);
1710 if (err != EFI_SUCCESS || !f)
1711 break;
1712
1713 if (FLAGS_SET(f->Attribute, EFI_FILE_DIRECTORY))
1714 continue;
1715 if (!valid_type1_filename(f->FileName))
1716 continue;
1717
1718 err = file_read(entries_dir,
1719 f->FileName,
1720 /* offset= */ 0,
1721 /* size= */ 0,
1722 &content,
1723 /* ret_size= */ NULL);
1724 if (err != EFI_SUCCESS)
1725 continue;
1726
1727 boot_entry_add_type1(config, device, root_dir, dropin_path, f->FileName, content, loaded_image_path);
1728 }
1729 }
1730
1731 static void config_load_smbios_entries(
1732 Config *config,
1733 EFI_HANDLE *device,
1734 EFI_FILE *root_dir,
1735 const char16_t *loaded_image_path) {
1736
1737 assert(config);
1738 assert(device);
1739 assert(root_dir);
1740
1741 /* Loads Boot Loader Type #1 entries from SMBIOS 11 */
1742
1743 if (is_confidential_vm())
1744 return; /* Don't consume SMBIOS in CoCo contexts */
1745
1746 for (const char *after = NULL, *extra;; after = extra) {
1747 extra = smbios_find_oem_string("io.systemd.boot.entries-extra:", after);
1748 if (!extra)
1749 break;
1750
1751 const char *eq = strchr8(extra, '=');
1752 if (!eq)
1753 continue;
1754
1755 _cleanup_free_ char16_t *fname = xstrn8_to_16(extra, eq - extra);
1756 if (!valid_type1_filename(fname))
1757 continue;
1758
1759 /* Make a copy, since boot_entry_add_type1() wants to modify it */
1760 _cleanup_free_ char *contents = xstrdup8(eq + 1);
1761
1762 boot_entry_add_type1(config, device, root_dir, /* path= */ NULL, fname, contents, loaded_image_path);
1763 }
1764 }
1765
1766 static unsigned boot_entry_profile(const BootEntry *a) {
1767 assert(a);
1768
1769 return a->profile == UINT_MAX ? 0 : a->profile;
1770 }
1771
1772 static int boot_entry_compare(const BootEntry *a, const BootEntry *b) {
1773 int r;
1774
1775 assert(a);
1776 assert(b);
1777
1778 /* Order entries that have no tries left to the end of the list */
1779 r = CMP(a->tries_left == 0, b->tries_left == 0);
1780 if (r != 0)
1781 return r;
1782
1783 /* If there's a sort key defined for *both* entries, then we do new-style ordering, i.e. by
1784 * sort-key/machine-id/version, with a final fallback to id. If there's no sort key for either, we do
1785 * old-style ordering, i.e. by id only. If one has sort key and the other does not, we put new-style
1786 * before old-style. */
1787 r = CMP(!a->sort_key, !b->sort_key);
1788 if (r != 0) /* one is old-style, one new-style */
1789 return r;
1790
1791 if (a->sort_key && b->sort_key) {
1792 r = strcmp16(a->sort_key, b->sort_key);
1793 if (r != 0)
1794 return r;
1795
1796 /* If multiple installations of the same OS are around, group by machine ID */
1797 r = strcmp16(a->machine_id, b->machine_id);
1798 if (r != 0)
1799 return r;
1800
1801 /* If the sort key was defined, then order by version now (downwards, putting the newest first) */
1802 r = -strverscmp_improved(a->version, b->version);
1803 if (r != 0)
1804 return r;
1805
1806 r = CMP(boot_entry_profile(a), boot_entry_profile(b));
1807 if (r != 0)
1808 return r;
1809 }
1810
1811 /* Now order by ID. The version is likely part of the ID, thus note that this will generatelly put
1812 * the newer versions earlier. Specifying a sort key explicitly is preferable, because it gives an
1813 * explicit sort order. */
1814 r = -strverscmp_improved(a->id_without_profile ?: a->id, b->id_without_profile ?: b->id);
1815 if (r != 0)
1816 return r;
1817
1818 /* Let's sort profiles by their profile */
1819 if (a->id_without_profile && b->id_without_profile) {
1820 /* Note: the strverscmp_improved() call above checked for us that we are looking at the very
1821 * same id, hence at this point we only need to compare profile numbers, since we know they
1822 * belong to the same UKI. */
1823 r = CMP(boot_entry_profile(a), boot_entry_profile(b));
1824 if (r != 0)
1825 return r;
1826 }
1827
1828 if (a->tries_left < 0 || b->tries_left < 0)
1829 return 0;
1830
1831 /* If both items have boot counting, and otherwise are identical, put the entry with more tries left first */
1832 r = -CMP(a->tries_left, b->tries_left);
1833 if (r != 0)
1834 return r;
1835
1836 /* If they have the same number of tries left, then let the one win which was tried fewer times so far */
1837 return CMP(a->tries_done, b->tries_done);
1838 }
1839
1840 static size_t config_find_entry(Config *config, const char16_t *pattern, const bool check_assessment) {
1841 assert(config);
1842
1843 /* We expect pattern and entry IDs to be already case folded. */
1844
1845 if (!pattern)
1846 return IDX_INVALID;
1847
1848 for (size_t i = 0; i < config->n_entries; i++)
1849 if (efi_fnmatch(pattern, config->entries[i]->id) && (!check_assessment || config->entries[i]->tries_left != 0))
1850 return i;
1851
1852 return IDX_INVALID;
1853 }
1854
1855 static bool sysfail_process(Config *config) {
1856 SysFailType sysfail_type;
1857
1858 assert(config);
1859
1860 sysfail_type = sysfail_check();
1861 if (sysfail_type == SYSFAIL_NO_FAILURE)
1862 return false;
1863
1864 /* Store reason string in LoaderSysFailReason EFI variable */
1865 const char16_t *reason_str = sysfail_get_error_str(sysfail_type);
1866 if (reason_str)
1867 (void) efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderSysFailReason", reason_str, 0);
1868
1869 config->sysfail_occurred = true;
1870
1871 return true;
1872 }
1873
1874 static void config_select_default_entry(Config *config) {
1875 size_t i;
1876
1877 assert(config);
1878
1879 if (config->sysfail_occurred) {
1880 i = config_find_entry(config, config->entry_sysfail, /* check_assessment= */ false);
1881 if (i != IDX_INVALID) {
1882 config->idx_default = i;
1883 return;
1884 }
1885 }
1886
1887 i = config_find_entry(config, config->entry_oneshot, /* check_assessment= */ false);
1888 if (i != IDX_INVALID) {
1889 config->idx_default = i;
1890 return;
1891 }
1892
1893 /* Try to match the preferred entry pattern */
1894
1895 i = config_find_entry(config, config->use_saved_entry_preferred_efivar ? config->entry_saved : config->entry_preferred_efivar, /* check_assessment= */ true);
1896 if (i != IDX_INVALID) {
1897 config->idx_default = i;
1898 config->idx_default_efivar = i;
1899 return;
1900 }
1901
1902 i = config_find_entry(config, config->entry_preferred_config, /* check_assessment= */ true);
1903 if (i != IDX_INVALID) {
1904 config->idx_default = i;
1905 return;
1906 }
1907
1908 if (config->use_saved_entry_preferred)
1909 /* No need to do the same thing twice. */
1910 i = config->use_saved_entry_preferred_efivar ? IDX_INVALID : config_find_entry(config, config->entry_saved, /* check_assessment= */ true);
1911 else
1912 i = config_find_entry(config, config->entry_preferred_config, /* check_assessment= */ true);
1913 if (i != IDX_INVALID) {
1914 config->idx_default = i;
1915 return;
1916 }
1917
1918 /* Try to match the default pattern */
1919
1920 i = config_find_entry(config, config->use_saved_entry_efivar ? config->entry_saved : config->entry_default_efivar, /* check_assessment= */ false);
1921 if (i != IDX_INVALID) {
1922 config->idx_default = i;
1923 config->idx_default_efivar = i;
1924 return;
1925 }
1926
1927 if (config->use_saved_entry)
1928 /* No need to do the same thing twice. */
1929 i = config->use_saved_entry_efivar ? IDX_INVALID : config_find_entry(config, config->entry_saved, /* check_assessment= */ false);
1930 else
1931 i = config_find_entry(config, config->entry_default_config, /* check_assessment= */ false);
1932 if (i != IDX_INVALID) {
1933 config->idx_default = i;
1934 return;
1935 }
1936
1937 /* select the first suitable entry */
1938 for (i = 0; i < config->n_entries; i++) {
1939 if (config->entries[i]->profile > 0)
1940 continue; /* For now, never select any non-default profile */
1941
1942 if (LOADER_TYPE_MAY_AUTO_SELECT(config->entries[i]->type)) {
1943 config->idx_default = i;
1944 return;
1945 }
1946 }
1947
1948 /* If no configured entry to select from was found, enable the menu. */
1949 config->idx_default = 0;
1950 if (config->timeout_sec == 0)
1951 config->timeout_sec = 10;
1952 }
1953
1954 static bool entries_unique(BootEntry **entries, bool *unique, size_t n_entries) {
1955 bool is_unique = true;
1956
1957 assert(entries);
1958 assert(unique);
1959
1960 for (size_t i = 0; i < n_entries; i++)
1961 for (size_t k = i + 1; k < n_entries; k++) {
1962 if (!streq16(entries[i]->title_show, entries[k]->title_show))
1963 continue;
1964
1965 is_unique = unique[i] = unique[k] = false;
1966 }
1967
1968 return is_unique;
1969 }
1970
1971 /* generate unique titles, avoiding non-distinguishable menu entries */
1972 static void generate_boot_entry_titles(Config *config) {
1973 assert(config);
1974
1975 bool unique[config->n_entries];
1976
1977 /* set title */
1978 for (size_t i = 0; i < config->n_entries; i++) {
1979 assert(!config->entries[i]->title_show);
1980 unique[i] = true;
1981 config->entries[i]->title_show = xstrdup16(config->entries[i]->title ?: config->entries[i]->id);
1982 }
1983
1984 if (entries_unique(config->entries, unique, config->n_entries))
1985 return;
1986
1987 /* add version to non-unique titles */
1988 for (size_t i = 0; i < config->n_entries; i++) {
1989 if (unique[i])
1990 continue;
1991
1992 unique[i] = true;
1993
1994 if (!config->entries[i]->version)
1995 continue;
1996
1997 _cleanup_free_ char16_t *t = config->entries[i]->title_show;
1998 config->entries[i]->title_show = xasprintf("%ls (%ls)", t, config->entries[i]->version);
1999 }
2000
2001 if (entries_unique(config->entries, unique, config->n_entries))
2002 return;
2003
2004 /* add machine-id to non-unique titles */
2005 for (size_t i = 0; i < config->n_entries; i++) {
2006 if (unique[i])
2007 continue;
2008
2009 unique[i] = true;
2010
2011 if (!config->entries[i]->machine_id)
2012 continue;
2013
2014 _cleanup_free_ char16_t *t = config->entries[i]->title_show;
2015 config->entries[i]->title_show = xasprintf("%ls (%.8ls)", t, config->entries[i]->machine_id);
2016 }
2017
2018 if (entries_unique(config->entries, unique, config->n_entries))
2019 return;
2020
2021 /* add file name to non-unique titles */
2022 for (size_t i = 0; i < config->n_entries; i++) {
2023 if (unique[i])
2024 continue;
2025
2026 _cleanup_free_ char16_t *t = config->entries[i]->title_show;
2027 config->entries[i]->title_show = xasprintf("%ls (%ls)", t, config->entries[i]->id);
2028 }
2029 }
2030
2031 static bool is_sd_boot(EFI_FILE *root_dir, const char16_t *loader_path) {
2032 static const char * const section_names[] = {
2033 ".sdmagic",
2034 NULL
2035 };
2036 _cleanup_free_ char *content = NULL;
2037 EFI_STATUS err;
2038 size_t read;
2039
2040 assert(root_dir);
2041 assert(loader_path);
2042
2043 _cleanup_file_close_ EFI_FILE *handle = NULL;
2044 err = root_dir->Open(root_dir, &handle, (char16_t *) loader_path, EFI_FILE_MODE_READ, 0ULL);
2045 if (err != EFI_SUCCESS)
2046 return false;
2047
2048 _cleanup_free_ PeSectionHeader *section_table = NULL;
2049 size_t n_section_table;
2050 err = pe_section_table_from_file(handle, &section_table, &n_section_table);
2051 if (err != EFI_SUCCESS)
2052 return false;
2053
2054 PeSectionVector vector[1] = {};
2055 pe_locate_profile_sections(
2056 section_table,
2057 n_section_table,
2058 section_names,
2059 /* profile= */ UINT_MAX,
2060 /* validate_base= */ 0,
2061 vector);
2062 if (vector[0].memory_size != STRLEN(SD_MAGIC))
2063 return false;
2064
2065 err = file_handle_read(handle, vector[0].file_offset, vector[0].file_size, &content, &read);
2066 if (err != EFI_SUCCESS || vector[0].file_size != read)
2067 return false;
2068
2069 return memcmp(content, SD_MAGIC, STRLEN(SD_MAGIC)) == 0;
2070 }
2071
2072 static BootEntry* config_add_entry_loader_auto(
2073 Config *config,
2074 EFI_HANDLE *device,
2075 EFI_FILE *root_dir,
2076 const char16_t *loaded_image_path,
2077 const char16_t *id,
2078 char16_t key,
2079 const char16_t *title,
2080 const char16_t *loader) {
2081
2082 assert(config);
2083 assert(device);
2084 assert(root_dir);
2085 assert(id);
2086 assert(title);
2087
2088 if (!config->auto_entries)
2089 return NULL;
2090
2091 if (!loader) {
2092 loader = u"\\EFI\\BOOT\\BOOT" EFI_MACHINE_TYPE_NAME ".efi";
2093
2094 /* We are trying to add the default EFI loader here,
2095 * but we do not want to do that if that would be us.
2096 *
2097 * If the default loader is not us, it might be shim. It would
2098 * chainload GRUBX64.EFI in that case, which might be us. */
2099 if (strcaseeq16(loader, loaded_image_path) ||
2100 is_sd_boot(root_dir, loader) ||
2101 is_sd_boot(root_dir, u"\\EFI\\BOOT\\GRUB" EFI_MACHINE_TYPE_NAME u".EFI"))
2102 return NULL;
2103 }
2104
2105 /* check existence */
2106 _cleanup_file_close_ EFI_FILE *handle = NULL;
2107 EFI_STATUS err = root_dir->Open(root_dir, &handle, (char16_t *) loader, EFI_FILE_MODE_READ, 0ULL);
2108 if (err != EFI_SUCCESS)
2109 return NULL;
2110
2111 BootEntry *entry = xnew(BootEntry, 1);
2112 *entry = (BootEntry) {
2113 .id = xstrdup16(id),
2114 .type = LOADER_AUTO,
2115 .title = xstrdup16(title),
2116 .device = device,
2117 .loader = xstrdup16(loader),
2118 .key = key,
2119 .tries_done = -1,
2120 .tries_left = -1,
2121 .call = call_image_start,
2122 };
2123
2124 config_add_entry(config, entry);
2125 return entry;
2126 }
2127
2128 static void config_add_entry_osx(Config *config) {
2129 EFI_STATUS err;
2130 size_t n_handles = 0;
2131 _cleanup_free_ EFI_HANDLE *handles = NULL;
2132
2133 assert(config);
2134
2135 if (!config->auto_entries)
2136 return;
2137
2138 err = BS->LocateHandleBuffer(
2139 ByProtocol, MAKE_GUID_PTR(EFI_SIMPLE_FILE_SYSTEM_PROTOCOL), NULL, &n_handles, &handles);
2140 if (err != EFI_SUCCESS)
2141 return;
2142
2143 for (size_t i = 0; i < n_handles; i++) {
2144 _cleanup_file_close_ EFI_FILE *root = NULL;
2145
2146 if (open_volume(handles[i], &root) != EFI_SUCCESS)
2147 continue;
2148
2149 if (config_add_entry_loader_auto(
2150 config,
2151 handles[i],
2152 root,
2153 /* loaded_image_path= */ NULL,
2154 u"auto-osx",
2155 'a',
2156 u"macOS",
2157 u"\\System\\Library\\CoreServices\\boot.efi"))
2158 break;
2159 }
2160 }
2161
2162 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
2163 static EFI_STATUS call_boot_windows_bitlocker(const BootEntry *entry, EFI_FILE *root_dir, EFI_HANDLE parent_image) {
2164 _cleanup_free_ EFI_HANDLE *handles = NULL;
2165 size_t n_handles;
2166 EFI_STATUS err;
2167
2168 assert(entry);
2169
2170 // FIXME: Experimental for now. Should be generalized, and become a per-entry option that can be
2171 // enabled independently of BitLocker, and without a BootXXXX entry pre-existing.
2172
2173 /* BitLocker key cannot be sealed without a TPM present. */
2174 if (!tpm_present())
2175 return EFI_NOT_FOUND;
2176
2177 err = BS->LocateHandleBuffer(
2178 ByProtocol, MAKE_GUID_PTR(EFI_BLOCK_IO_PROTOCOL), NULL, &n_handles, &handles);
2179 if (err != EFI_SUCCESS)
2180 return err;
2181
2182 /* Look for BitLocker magic string on all block drives. */
2183 bool found = false;
2184 for (size_t i = 0; i < n_handles; i++) {
2185 EFI_BLOCK_IO_PROTOCOL *block_io;
2186 err = BS->HandleProtocol(handles[i], MAKE_GUID_PTR(EFI_BLOCK_IO_PROTOCOL), (void **) &block_io);
2187 if (err != EFI_SUCCESS || block_io->Media->BlockSize < 512 || block_io->Media->BlockSize > 4096)
2188 continue;
2189
2190 EFI_DISK_IO_PROTOCOL *disk_io;
2191 err = BS->HandleProtocol(handles[i], MAKE_GUID_PTR(EFI_DISK_IO_PROTOCOL), (void **) &disk_io);
2192 if (err != EFI_SUCCESS) {
2193 log_debug_status(err, "Failed to get disk I/O protocol: %m");
2194 continue;
2195 }
2196
2197 char buf[STRLEN("-FVE-FS-")];
2198 err = disk_io->ReadDisk(disk_io, block_io->Media->MediaId, /* Offset= */ 3, sizeof(buf), buf);
2199 if (err != EFI_SUCCESS)
2200 continue;
2201
2202 if (memcmp(buf, "-FVE-FS-", STRLEN("-FVE-FS-")) == 0) {
2203 found = true;
2204 break;
2205 }
2206 }
2207
2208 /* If no BitLocker drive was found, we can just chainload bootmgfw.efi directly. */
2209 if (!found)
2210 return EFI_NOT_FOUND;
2211
2212 _cleanup_free_ uint16_t *boot_order = NULL;
2213 size_t boot_order_size;
2214
2215 /* There can be gaps in Boot#### entries. Instead of iterating over the full
2216 * EFI var list or uint16_t namespace, just look for "Windows Boot Manager" in BootOrder. */
2217 err = efivar_get_raw(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"BootOrder", (void**) &boot_order, &boot_order_size);
2218 if (err != EFI_SUCCESS || boot_order_size % sizeof(uint16_t) != 0)
2219 return err;
2220
2221 for (size_t i = 0; i < boot_order_size / sizeof(uint16_t); i++) {
2222 _cleanup_free_ char *buf = NULL;
2223 size_t buf_size;
2224
2225 _cleanup_free_ char16_t *name = xasprintf("Boot%04x", boot_order[i]);
2226 err = efivar_get_raw(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), name, (void**) &buf, &buf_size);
2227 if (err != EFI_SUCCESS)
2228 continue;
2229
2230 /* Boot#### are EFI_LOAD_OPTION. But we really are only interested
2231 * for the description, which is at this offset. */
2232 size_t offset = sizeof(uint32_t) + sizeof(uint16_t);
2233 if (buf_size < offset + sizeof(char16_t))
2234 continue;
2235
2236 if (streq16((char16_t *) (buf + offset), u"Windows Boot Manager")) {
2237 err = efivar_set_raw(
2238 MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE),
2239 u"BootNext",
2240 boot_order + i,
2241 sizeof(boot_order[i]),
2242 EFI_VARIABLE_NON_VOLATILE);
2243 if (err != EFI_SUCCESS)
2244 return err;
2245 RT->ResetSystem(EfiResetWarm, EFI_SUCCESS, 0, NULL);
2246 assert_not_reached();
2247 }
2248 }
2249
2250 return EFI_NOT_FOUND;
2251 }
2252 #endif
2253
2254 static void config_add_entry_windows(Config *config, EFI_HANDLE *device, EFI_FILE *root) {
2255 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
2256 _cleanup_free_ char *bcd = NULL;
2257 char16_t *title = NULL;
2258 EFI_STATUS err;
2259 size_t len;
2260
2261 assert(config);
2262 assert(device);
2263 assert(root);
2264
2265 if (!config->auto_entries)
2266 return;
2267
2268 /* Try to find a better title. */
2269 err = file_read(root, u"\\EFI\\Microsoft\\Boot\\BCD", 0, 100*1024, &bcd, &len);
2270 if (err == EFI_SUCCESS)
2271 title = get_bcd_title((uint8_t *) bcd, len);
2272
2273 BootEntry *e = config_add_entry_loader_auto(
2274 config,
2275 device,
2276 root,
2277 NULL,
2278 u"auto-windows",
2279 'w',
2280 title ?: u"Windows Boot Manager",
2281 u"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
2282
2283 if (config->reboot_for_bitlocker)
2284 e->call = call_boot_windows_bitlocker;
2285 #endif
2286 }
2287
2288 static void boot_entry_add_type2(
2289 Config *config,
2290 EFI_HANDLE *device,
2291 EFI_FILE *dir,
2292 const uint16_t *path,
2293 const uint16_t *filename) {
2294
2295 enum {
2296 SECTION_CMDLINE,
2297 SECTION_OSREL,
2298 SECTION_PROFILE,
2299 _SECTION_MAX,
2300 };
2301 static const char * const section_names[_SECTION_MAX + 1] = {
2302 [SECTION_CMDLINE] = ".cmdline",
2303 [SECTION_OSREL] = ".osrel",
2304 [SECTION_PROFILE] = ".profile",
2305 NULL,
2306 };
2307
2308 EFI_STATUS err;
2309
2310 assert(config);
2311 assert(device);
2312 assert(dir);
2313 assert(path);
2314 assert(filename);
2315
2316 _cleanup_file_close_ EFI_FILE *handle = NULL;
2317 err = dir->Open(dir, &handle, (char16_t *) filename, EFI_FILE_MODE_READ, 0ULL);
2318 if (err != EFI_SUCCESS)
2319 return;
2320
2321 /* Load section table once */
2322 _cleanup_free_ PeSectionHeader *section_table = NULL;
2323 size_t n_section_table;
2324 err = pe_section_table_from_file(handle, &section_table, &n_section_table);
2325 if (err != EFI_SUCCESS)
2326 return;
2327
2328 /* Find base profile */
2329 PeSectionVector base_sections[_SECTION_MAX] = {};
2330 pe_locate_profile_sections(
2331 section_table,
2332 n_section_table,
2333 section_names,
2334 /* profile= */ UINT_MAX,
2335 /* validate_base= */ 0,
2336 base_sections);
2337
2338 /* and now iterate through possible profiles, and create a menu item for each profile we find */
2339 for (unsigned profile = 0; profile < UNIFIED_PROFILES_MAX; profile ++) {
2340 PeSectionVector sections[_SECTION_MAX] = {};
2341
2342 /* Start out with the base sections */
2343 memcpy(sections, base_sections, sizeof(sections));
2344
2345 err = pe_locate_profile_sections(
2346 section_table,
2347 n_section_table,
2348 section_names,
2349 profile,
2350 /* validate_base= */ 0,
2351 sections);
2352 if (err != EFI_SUCCESS && profile > 0) /* It's fine if there's no .profile for the first
2353 profile */
2354 break;
2355
2356 if (!PE_SECTION_VECTOR_IS_SET(sections + SECTION_OSREL))
2357 continue;
2358
2359 _cleanup_free_ char *content = NULL;
2360 err = file_handle_read(
2361 handle,
2362 sections[SECTION_OSREL].file_offset,
2363 sections[SECTION_OSREL].file_size,
2364 &content,
2365 /* ret_size= */ NULL);
2366 if (err != EFI_SUCCESS)
2367 continue;
2368
2369 _cleanup_free_ char16_t *os_pretty_name = NULL, *os_image_id = NULL, *os_name = NULL, *os_id = NULL,
2370 *os_image_version = NULL, *os_version = NULL, *os_version_id = NULL, *os_build_id = NULL;
2371 char *line, *key, *value;
2372 size_t pos = 0;
2373
2374 /* read properties from the embedded os-release file */
2375 while ((line = line_get_key_value(content, "=", &pos, &key, &value)))
2376 if (streq8(key, "PRETTY_NAME")) {
2377 free(os_pretty_name);
2378 os_pretty_name = xstr8_to_16(value);
2379
2380 } else if (streq8(key, "IMAGE_ID")) {
2381 free(os_image_id);
2382 os_image_id = xstr8_to_16(value);
2383
2384 } else if (streq8(key, "NAME")) {
2385 free(os_name);
2386 os_name = xstr8_to_16(value);
2387
2388 } else if (streq8(key, "ID")) {
2389 free(os_id);
2390 os_id = xstr8_to_16(value);
2391
2392 } else if (streq8(key, "IMAGE_VERSION")) {
2393 free(os_image_version);
2394 os_image_version = xstr8_to_16(value);
2395
2396 } else if (streq8(key, "VERSION")) {
2397 free(os_version);
2398 os_version = xstr8_to_16(value);
2399
2400 } else if (streq8(key, "VERSION_ID")) {
2401 free(os_version_id);
2402 os_version_id = xstr8_to_16(value);
2403
2404 } else if (streq8(key, "BUILD_ID")) {
2405 free(os_build_id);
2406 os_build_id = xstr8_to_16(value);
2407 }
2408
2409 const char16_t *good_name, *good_version, *good_sort_key;
2410 if (!bootspec_pick_name_version_sort_key(
2411 os_pretty_name,
2412 os_image_id,
2413 os_name,
2414 os_id,
2415 os_image_version,
2416 os_version,
2417 os_version_id,
2418 os_build_id,
2419 &good_name,
2420 &good_version,
2421 &good_sort_key))
2422 continue;
2423
2424 _cleanup_free_ char16_t *profile_id = NULL, *profile_title = NULL;
2425
2426 if (PE_SECTION_VECTOR_IS_SET(sections + SECTION_PROFILE)) {
2427 content = mfree(content);
2428
2429 /* Read any .profile data from the file, if we have it */
2430
2431 err = file_handle_read(
2432 handle,
2433 sections[SECTION_PROFILE].file_offset,
2434 sections[SECTION_PROFILE].file_size,
2435 &content,
2436 /* ret_size= */ NULL);
2437 if (err != EFI_SUCCESS)
2438 continue;
2439
2440 /* read properties from the embedded os-release file */
2441 pos = 0;
2442 while ((line = line_get_key_value(content, "=", &pos, &key, &value)))
2443 if (streq8(key, "ID")) {
2444 free(profile_id);
2445 profile_id = xstr8_to_16(value);
2446 } else if (streq8(key, "TITLE")) {
2447 free(profile_title);
2448 profile_title = xstr8_to_16(value);
2449 }
2450 }
2451
2452 _cleanup_free_ char16_t *title = NULL;
2453 if (profile_title)
2454 title = xasprintf("%ls (%ls)", good_name, profile_title);
2455 else if (profile > 0) {
2456 if (profile_id)
2457 title = xasprintf("%ls (%ls)", good_name, profile_id);
2458 else
2459 title = xasprintf("%ls (Profile #%u)", good_name, profile + 1);
2460 } else
2461 title = xstrdup16(good_name);
2462
2463 BootEntry *entry = xnew(BootEntry, 1);
2464 *entry = (BootEntry) {
2465 .type = LOADER_TYPE2_UKI,
2466 .title = TAKE_PTR(title),
2467 .version = xstrdup16(good_version),
2468 .device = device,
2469 .loader = xasprintf("%ls\\%ls", path, filename),
2470 .sort_key = xstrdup16(good_sort_key),
2471 .key = 'l',
2472 .tries_done = -1,
2473 .tries_left = -1,
2474 .profile = profile,
2475 .call = call_image_start,
2476 };
2477
2478 boot_entry_parse_tries(entry, path, filename, u".efi");
2479
2480 /* If the filename had no tries suffixes then the id won't be set by the above call, do it now */
2481 if (!entry->id)
2482 entry->id = strtolower16(xstrdup16(filename));
2483
2484 /* Ensure the secondary profiles IDs also have the tries suffix stripped, to match the primary */
2485 if (profile > 0) {
2486 entry->id_without_profile = TAKE_PTR(entry->id);
2487
2488 if (profile_id)
2489 entry->id = xasprintf("%ls@%ls", entry->id_without_profile, profile_id);
2490 else
2491 entry->id = xasprintf("%ls@%u", entry->id_without_profile, profile);
2492
2493 }
2494
2495 config_add_entry(config, entry);
2496
2497 if (!PE_SECTION_VECTOR_IS_SET(sections + SECTION_CMDLINE))
2498 continue;
2499
2500 content = mfree(content);
2501
2502 /* Read the embedded cmdline file for display purposes */
2503 size_t cmdline_len;
2504 err = file_handle_read(
2505 handle,
2506 sections[SECTION_CMDLINE].file_offset,
2507 sections[SECTION_CMDLINE].file_size,
2508 &content,
2509 &cmdline_len);
2510 if (err == EFI_SUCCESS) {
2511 entry->options = mangle_stub_cmdline(xstrn8_to_16(content, cmdline_len));
2512 entry->options_implied = true;
2513 }
2514 }
2515 }
2516
2517 static void config_load_type2_entries(
2518 Config *config,
2519 EFI_HANDLE *device,
2520 EFI_FILE *root_dir) {
2521
2522 _cleanup_file_close_ EFI_FILE *linux_dir = NULL;
2523 _cleanup_free_ EFI_FILE_INFO *f = NULL;
2524 size_t f_size = 0;
2525 EFI_STATUS err;
2526
2527 /* Adds Boot Loader Type #2 entries (i.e. /EFI/Linux/….efi) */
2528
2529 assert(config);
2530 assert(device);
2531 assert(root_dir);
2532
2533 const uint16_t dropin_path[] = u"\\EFI\\Linux";
2534
2535 err = open_directory(root_dir, dropin_path, &linux_dir);
2536 if (err != EFI_SUCCESS)
2537 return;
2538
2539 for (;;) {
2540 err = readdir(linux_dir, &f, &f_size);
2541 if (err != EFI_SUCCESS || !f)
2542 break;
2543
2544 if (f->FileName[0] == '.')
2545 continue;
2546 if (FLAGS_SET(f->Attribute, EFI_FILE_DIRECTORY))
2547 continue;
2548 if (!endswith_no_case(f->FileName, u".efi"))
2549 continue;
2550 if (startswith_no_case(f->FileName, u"auto-"))
2551 continue;
2552
2553 boot_entry_add_type2(config, device, linux_dir, dropin_path, f->FileName);
2554 }
2555 }
2556
2557 static void config_load_xbootldr(
2558 Config *config,
2559 EFI_HANDLE *device) {
2560
2561 _cleanup_file_close_ EFI_FILE *root_dir = NULL;
2562 EFI_HANDLE new_device = NULL; /* avoid false maybe-uninitialized warning */
2563 EFI_STATUS err;
2564
2565 assert(config);
2566 assert(device);
2567
2568 err = partition_open(MAKE_GUID_PTR(XBOOTLDR), device, &new_device, &root_dir);
2569 if (err != EFI_SUCCESS)
2570 return;
2571
2572 config_load_type2_entries(config, new_device, root_dir);
2573 config_load_type1_entries(config, new_device, root_dir, NULL);
2574 }
2575
2576 static EFI_STATUS initrd_prepare(
2577 EFI_FILE *root,
2578 const BootEntry *entry,
2579 char16_t **ret_options,
2580 Pages *ret_initrd_pages,
2581 size_t *ret_initrd_size) {
2582
2583 assert(root);
2584 assert(entry);
2585 assert(ret_options);
2586 assert(ret_initrd_pages);
2587 assert(ret_initrd_size);
2588
2589 assert(entry->type == LOADER_LINUX);
2590
2591 if (strv_isempty(entry->initrd)) {
2592 *ret_options = NULL;
2593 *ret_initrd_pages = (Pages) {};
2594 *ret_initrd_size = 0;
2595 return EFI_SUCCESS;
2596 }
2597
2598 /* Note that order of initrds matters. The kernel will only look for microcode updates in the very
2599 * first one it sees. */
2600
2601 /* Add initrd= to options for older kernels that do not support LINUX_INITRD_MEDIA. Should be dropped
2602 * if linux_x86.c is dropped. */
2603 _cleanup_free_ char16_t *options = NULL;
2604
2605 EFI_STATUS err;
2606 size_t size = 0, padded_size = 0;
2607
2608 STRV_FOREACH(i, entry->initrd) {
2609 _cleanup_file_close_ EFI_FILE *handle = NULL;
2610 err = root->Open(root, &handle, *i, EFI_FILE_MODE_READ, 0);
2611 if (err != EFI_SUCCESS)
2612 return err;
2613
2614 _cleanup_free_ EFI_FILE_INFO *info = NULL;
2615 err = get_file_info(handle, &info, NULL);
2616 if (err != EFI_SUCCESS)
2617 return err;
2618
2619 if (info->FileSize == 0) /* Automatically skip over empty files */
2620 continue;
2621
2622 _cleanup_free_ char16_t *o = options;
2623 if (o)
2624 options = xasprintf("%ls initrd=%ls", o, *i);
2625 else
2626 options = xasprintf("initrd=%ls", *i);
2627
2628 size_t inc = info->FileSize;
2629
2630 if (!INC_SAFE(&padded_size, ALIGN4(inc)))
2631 return EFI_OUT_OF_RESOURCES;
2632 assert_se(INC_SAFE(&size, *(i + 1) ? ALIGN4(inc) : inc));
2633 }
2634
2635 /* Skip if no valid initrd files */
2636 if (padded_size == 0) {
2637 *ret_options = NULL;
2638 *ret_initrd_pages = (Pages) {};
2639 *ret_initrd_size = 0;
2640 return EFI_SUCCESS;
2641 }
2642
2643 _cleanup_pages_ Pages pages = xmalloc_initrd_pages(padded_size);
2644 uint8_t *p = PHYSICAL_ADDRESS_TO_POINTER(pages.addr);
2645
2646 STRV_FOREACH(i, entry->initrd) {
2647 _cleanup_file_close_ EFI_FILE *handle = NULL;
2648 err = root->Open(root, &handle, *i, EFI_FILE_MODE_READ, 0);
2649 if (err != EFI_SUCCESS)
2650 return err;
2651
2652 _cleanup_free_ EFI_FILE_INFO *info = NULL;
2653 err = get_file_info(handle, &info, NULL);
2654 if (err != EFI_SUCCESS)
2655 return err;
2656
2657 if (info->FileSize == 0) /* Automatically skip over empty files */
2658 continue;
2659
2660 size_t read_size = info->FileSize;
2661 err = chunked_read(handle, &read_size, p);
2662 if (err != EFI_SUCCESS)
2663 return err;
2664
2665 /* Make sure the actual read size is what we expected. */
2666 assert(read_size == info->FileSize);
2667 p += read_size;
2668
2669 size_t pad;
2670 pad = ALIGN4(read_size) - read_size;
2671 if (pad == 0)
2672 continue;
2673
2674 memzero(p, pad);
2675 /* Exclude the trailing pad from size calculations. This would change the
2676 * calculated hash, see https://github.com/systemd/systemd/issues/35439
2677 * and https://bugzilla.suse.com/show_bug.cgi?id=1233752. */
2678 if (*(i + 1))
2679 p += pad;
2680 }
2681
2682 assert(PHYSICAL_ADDRESS_TO_POINTER(pages.addr + size) == p);
2683
2684 if (entry->options) {
2685 _cleanup_free_ char16_t *o = options;
2686 options = xasprintf("%ls %ls", o, entry->options);
2687 }
2688
2689 *ret_options = TAKE_PTR(options);
2690 *ret_initrd_pages = TAKE_STRUCT(pages);
2691 *ret_initrd_size = size;
2692 return EFI_SUCCESS;
2693 }
2694
2695 static EFI_STATUS load_extras(
2696 EFI_FILE *root,
2697 const BootEntry *entry,
2698 Pages *ret_initrd_pages,
2699 size_t *ret_initrd_size) {
2700
2701 EFI_STATUS err;
2702
2703 assert(root);
2704 assert(entry);
2705 assert(ret_initrd_pages);
2706 assert(ret_initrd_size);
2707
2708 assert(IN_SET(entry->type, LOADER_UKI, LOADER_UKI_URL));
2709
2710 _cleanup_(iovec_done) struct iovec previous_initrd = {}, confext_initrd = {}, sysext_initrd = {}, credential_initrd = {};
2711
2712 const struct ExtraResourceInfo {
2713 const char16_t *suffix;
2714 const CpioTarget *target;
2715 struct iovec *iovec;
2716 const char16_t *tpm_description;
2717 } table[] = {
2718 { u".cred", &cpio_target_credentials, &credential_initrd, u"Entry credentials initrd" },
2719 { u".sysext.raw", &cpio_target_sysext, &sysext_initrd, u"Entry system extension initrd" },
2720 { u".confext.raw", &cpio_target_confext, &confext_initrd, u"Entry configuration extension initrd" },
2721 };
2722
2723 if (strv_isempty(entry->extras))
2724 goto nothing;
2725
2726 uint32_t inode = 1; /* inode counter, so that each item gets a new inode */
2727 unsigned n = 0;
2728
2729 STRV_FOREACH(i, entry->extras) {
2730 _cleanup_file_close_ EFI_FILE *handle = NULL;
2731 err = root->Open(root, &handle, *i, EFI_FILE_MODE_READ, /* Attributes= */ 0);
2732 if (err != EFI_SUCCESS) {
2733 log_warning_status(err, "Failed to open extra file '%ls', ignoring: %m", *i);
2734 continue;
2735 }
2736
2737 _cleanup_free_ EFI_FILE_INFO *info = NULL;
2738 err = get_file_info(handle, &info, /* ret_size= */ NULL);
2739 if (err != EFI_SUCCESS) {
2740 log_warning_status(err, "Failed to get information about file '%ls', ignoring: %m", *i);
2741 continue;
2742 }
2743
2744 if (FLAGS_SET(info->Attribute, EFI_FILE_DIRECTORY)) {
2745 log_warning("Extra file '%ls' is a directory, ignoring.", *i);
2746 continue;
2747 }
2748
2749 if (info->FileSize == 0) {
2750 log_warning("Extra file '%ls' is empty, ignoring.", *i);
2751 continue;
2752 }
2753 if (info->FileSize > EXTRA_SIZE_MAX) {
2754 log_warning("Extra file '%ls' is larger than allowed extra file size, ignoring.", *i);
2755 continue;
2756 }
2757
2758 if (!is_ascii(info->FileName)) {
2759 log_warning("Extra file name '%ls' is not valid ASCII, ignoring.", *i);
2760 continue;
2761 }
2762 if (strlen16(info->FileName) > 255) { /* Max filename size on Linux */
2763 log_warning("Filename '%ls' too long, ignoring.", *i);
2764 continue;
2765 }
2766
2767 const struct ExtraResourceInfo *x = NULL;
2768 FOREACH_ELEMENT(j, table)
2769 if (endswith_no_case(info->FileName, j->suffix)) {
2770 x = j;
2771 break;
2772 }
2773 if (!x) {
2774 log_warning("Unrecognized type of extra file '%ls', ignoring.", info->FileName);
2775 continue;
2776 }
2777
2778 _cleanup_free_ char *content = NULL;
2779 size_t contentsize = 0; /* avoid false maybe-uninitialized warning */
2780 err = file_handle_read(handle, /* offset= */ 0, info->FileSize, &content, &contentsize);
2781 if (err != EFI_SUCCESS) {
2782 log_warning_status(err, "Failed to read '%ls', ignoring: %m", *i);
2783 continue;
2784 }
2785
2786 /* Generate the leading directory inodes right before adding the first files to the
2787 * archive. Otherwise the cpio archive cannot be unpacked, since the leading dirs won't
2788 * exist. Note that we potentially do redundant work here: a prior iteration might already
2789 * have created the prefix for us, but to simplify this we regenerate it anyway. It's very
2790 * little data, and simplifies the implementation here a lot. */
2791 err = pack_cpio_prefix(x->target, &inode, &x->iovec->iov_base, &x->iovec->iov_len);
2792 if (err != EFI_SUCCESS)
2793 return log_error_status(err, "Failed to pack cpio prefix '%s': %m", x->target->directory);
2794
2795 err = pack_cpio_one(
2796 info->FileName,
2797 content, contentsize,
2798 x->target,
2799 &inode,
2800 &x->iovec->iov_base, &x->iovec->iov_len);
2801 if (err != EFI_SUCCESS)
2802 return log_error_status(err, "Failed to pack cpio file '%ls': %m", info->FileName);
2803
2804 n++;
2805 }
2806
2807 if (n == 0) /* Nothing actually loaded */
2808 goto nothing;
2809
2810 FOREACH_ELEMENT(x, table) {
2811 if (x->iovec->iov_len <= 0)
2812 continue;
2813
2814 err = pack_cpio_trailer(&x->iovec->iov_base, &x->iovec->iov_len);
2815 if (err != EFI_SUCCESS)
2816 return log_error_status(err, "Failed to pack cpio trailer: %m");
2817
2818 err = tpm_log_ipl_event(
2819 x->target->tpm_pcr,
2820 POINTER_TO_PHYSICAL_ADDRESS(x->iovec->iov_base),
2821 x->iovec->iov_len,
2822 x->tpm_description,
2823 /* ret_measured= */ NULL);
2824 if (err != EFI_SUCCESS)
2825 return log_error_status(
2826 err,
2827 "Unable to add cpio TPM measurement for PCR %u (%ls): %m",
2828 x->target->tpm_pcr,
2829 x->tpm_description);
2830 }
2831
2832 /* Be nice: pick up any previously registered initrds and prepend them to what we are generating here */
2833 err = initrd_read_previous(&previous_initrd);
2834 if (err == EFI_NOT_FOUND)
2835 log_debug_status(err, "No previous initrd installed.");
2836 else if (err != EFI_SUCCESS)
2837 log_warning_status(err, "Failed to read previously registered initrd, ignoring.");
2838 else
2839 log_debug("Successfully loaded previously installed initrd (%zu bytes).", previous_initrd.iov_len);
2840
2841 err = combine_initrds(
2842 (const struct iovec[]) {
2843 previous_initrd,
2844 credential_initrd,
2845 sysext_initrd,
2846 confext_initrd,
2847 },
2848 /* n_initrds= */ 4,
2849 ret_initrd_pages,
2850 ret_initrd_size);
2851 if (err != EFI_SUCCESS)
2852 return log_error_status(err, "Failed to combine previous with extra initrds: %m");
2853
2854 return EFI_SUCCESS;
2855
2856 nothing:
2857 *ret_initrd_pages = (Pages) {};
2858 *ret_initrd_size = 0;
2859 return EFI_SUCCESS;
2860 }
2861
2862 static EFI_STATUS expand_path(
2863 EFI_HANDLE parent_image,
2864 EFI_DEVICE_PATH *path,
2865 EFI_DEVICE_PATH **ret_expanded_path) {
2866
2867 EFI_STATUS err;
2868
2869 assert(parent_image);
2870 assert(path);
2871 assert(ret_expanded_path);
2872
2873 _cleanup_free_ EFI_HANDLE *handles = NULL;
2874 size_t n_handles = 0;
2875 err = BS->LocateHandleBuffer(
2876 ByProtocol,
2877 MAKE_GUID_PTR(EFI_LOAD_FILE_PROTOCOL),
2878 /* SearchKey= */ NULL,
2879 &n_handles,
2880 &handles);
2881 if (!IN_SET(err, EFI_SUCCESS, EFI_NOT_FOUND))
2882 return log_error_status(err, "Failed to get list of LoadFile protocol handles: %m");
2883
2884 FOREACH_ARRAY(h, handles, n_handles) {
2885 EFI_LOAD_FILE_PROTOCOL *load_file = NULL;
2886 err = BS->OpenProtocol(
2887 *h,
2888 MAKE_GUID_PTR(EFI_LOAD_FILE_PROTOCOL),
2889 (void**) &load_file,
2890 parent_image,
2891 /* ControllerHandler= */ NULL,
2892 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
2893 if (IN_SET(err, EFI_NOT_FOUND, EFI_INVALID_PARAMETER))
2894 continue; /* Skip over LoadFile() handles that are not suitable for this kind of device path */
2895 if (err != EFI_SUCCESS) {
2896 log_warning_status(err, "Failed to get LoadFile() protocol, ignoring: %m");
2897 continue;
2898 }
2899
2900 /* Issue a LoadFile() request without interest in the actual data (i.e. size is zero and
2901 * buffer pointer is NULL), but with BootPolicy set to true, this has the effect of
2902 * downloading the URL and establishing a handle for it. */
2903 size_t size = 0;
2904 err = load_file->LoadFile(load_file, path, /* BootPolicy= */ true, &size, /* Buffer= */ NULL);
2905 if (IN_SET(err, EFI_NOT_FOUND, EFI_INVALID_PARAMETER))
2906 continue; /* Skip over LoadFile() handles that after all don't consider themselves
2907 * appropriate for this kind of path */
2908 if (!IN_SET(err, EFI_SUCCESS, EFI_BUFFER_TOO_SMALL)) {
2909 /* NB: firmwares are supposed to return EFI_BUFFER_TOO_SMALL whenever we pass a NULL
2910 * buffer. But for compatibility with quirky firmwares let's be lenient for the
2911 * special case of a zero sized file: the firmware might return EFI_SUCCESS here and
2912 * initialize the size to zero, as a buffer is not actually necessary for that
2913 * case. */
2914 log_warning_status(err, "Failed to get file via LoadFile() protocol, ignoring: %m");
2915 continue;
2916 }
2917
2918 /* Now read the updated file path */
2919 EFI_DEVICE_PATH *load_file_path = NULL;
2920 err = BS->HandleProtocol(*h, MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), (void **) &load_file_path);
2921 if (err != EFI_SUCCESS)
2922 return log_error_status(err, "Failed to get LoadFile() device path: %m");
2923
2924 /* And return a copy */
2925 *ret_expanded_path = device_path_dup(load_file_path);
2926 return EFI_SUCCESS;
2927 }
2928
2929 return EFI_NOT_FOUND;
2930 }
2931
2932 static EFI_STATUS call_image_start(
2933 const BootEntry *entry,
2934 EFI_FILE *root_dir,
2935 EFI_HANDLE parent_image) {
2936
2937 _cleanup_(devicetree_cleanup) struct devicetree_state dtstate = {};
2938 _cleanup_(unload_imagep) EFI_HANDLE image = NULL;
2939 EFI_STATUS err;
2940
2941 assert(entry);
2942
2943 _cleanup_file_close_ EFI_FILE *image_root = NULL;
2944 _cleanup_free_ EFI_DEVICE_PATH *path = NULL;
2945 bool boot_policy;
2946 if (entry->url) {
2947 /* Generate a device path that only contains the URL */
2948 err = make_url_device_path(entry->url, &path);
2949 if (err != EFI_SUCCESS)
2950 return log_error_status(err, "Error making URL device path: %m");
2951
2952 /* Try to expand this path on all available NICs and IP protocols */
2953 _cleanup_free_ EFI_DEVICE_PATH *expanded_path = NULL;
2954 for (unsigned n_attempt = 0;; n_attempt++) {
2955 err = expand_path(parent_image, path, &expanded_path);
2956 if (err == EFI_SUCCESS) {
2957 /* If this worked then let's try to boot with the expanded path. */
2958 free(path);
2959 path = TAKE_PTR(expanded_path);
2960 break;
2961 }
2962 if (err != EFI_NOT_FOUND || n_attempt > 5) {
2963 log_warning_status(err, "Failed to expand device path, ignoring: %m");
2964 break;
2965 }
2966
2967 /* Maybe the network devices have been configured for this yet (because we are the
2968 * first piece of code trying to do networking)? Then let's connect them, and try
2969 * again. */
2970 reconnect_all_drivers();
2971 }
2972
2973 /* Note: if the path expansion doesn't work, we'll continue with the unexpanded path. Which
2974 * will probably fail on many (most?) firmwares, but it's worth a try. */
2975
2976 boot_policy = true; /* Set BootPolicy parameter to LoadImage() to true, which ultimately
2977 * controls whether the LoadFile (and thus HTTP boot) or LoadFile2 (which
2978 * does not set up HTTP boot) protocol shall be used. */
2979 } else {
2980 assert(entry->device);
2981 assert(entry->loader);
2982
2983 err = open_volume(entry->device, &image_root);
2984 if (err != EFI_SUCCESS)
2985 return log_error_status(err, "Error opening root path: %m");
2986
2987 err = make_file_device_path(entry->device, entry->loader, &path);
2988 if (err != EFI_SUCCESS)
2989 return log_error_status(err, "Error making file device path: %m");
2990
2991 boot_policy = false;
2992 }
2993
2994 /* Authenticate the image before we continue with initrd or DT stuff */
2995 err = shim_load_image(parent_image, path, boot_policy, &image);
2996 if (err != EFI_SUCCESS) {
2997 if (entry->url) {
2998 /* EFI_NOT_FOUND typically indicates that no network stack or NIC was available, let's give the user a hint. */
2999 if (err == EFI_NOT_FOUND) {
3000 log_info("Unable to boot remote UKI %ls, is networking available?", entry->url);
3001 return err;
3002 }
3003
3004 return log_error_status(err, "Error loading loading remote UKI %ls: %m", entry->url);
3005 }
3006
3007 return log_error_status(err, "Error loading EFI binary %ls: %m", entry->loader);
3008 }
3009
3010 _cleanup_free_ char16_t *options_initrd = NULL;
3011 _cleanup_pages_ Pages initrd_pages = {}; /* Note: please keep order intact: these pages should be released after the initrd handle is released */
3012 _cleanup_(cleanup_initrd) EFI_HANDLE initrd_handle = NULL;
3013 size_t initrd_size = 0;
3014 if (image_root) {
3015 /* DTBs are loaded by the kernel before ExitBootServices(), and they can be used to map and
3016 * assign arbitrary memory ranges, so skip them when secure boot is enabled as the DTB here
3017 * is unverified. */
3018 if (entry->devicetree && !secure_boot_enabled()) {
3019 err = devicetree_install(&dtstate, image_root, entry->devicetree);
3020 if (err != EFI_SUCCESS)
3021 return log_error_status(err, "Error loading %ls: %m", entry->devicetree);
3022 }
3023
3024 switch (entry->type) {
3025
3026 case LOADER_LINUX:
3027 /* For traditional Linux we follow 'initrd' links, because that's how things worked in the good old days */
3028 err = initrd_prepare(image_root, entry, &options_initrd, &initrd_pages, &initrd_size);
3029 if (err != EFI_SUCCESS)
3030 return log_error_status(err, "Error preparing initrd: %m");
3031
3032 break;
3033
3034 case LOADER_UKI:
3035 case LOADER_UKI_URL:
3036 /* For modern UKIs we'll not bother with 'initrd', but we'll instead support 'extra'
3037 * for loading credentials, sysexts, and confexts. */
3038
3039 err = load_extras(image_root, entry, &initrd_pages, &initrd_size);
3040 if (err != EFI_SUCCESS)
3041 return err; /* load_extras() logs on its own */
3042 break;
3043
3044 default:
3045 ;
3046 }
3047
3048 err = initrd_register(&IOVEC_MAKE(PHYSICAL_ADDRESS_TO_POINTER(initrd_pages.addr), initrd_size), &initrd_handle);
3049 if (err != EFI_SUCCESS)
3050 return log_error_status(err, "Error registering initrd: %m");
3051
3052 /* NB: the initrd pages remain in our possession, we will free them if executing the image fails below */
3053 }
3054
3055 EFI_LOADED_IMAGE_PROTOCOL *loaded_image;
3056 err = BS->HandleProtocol(image, MAKE_GUID_PTR(EFI_LOADED_IMAGE_PROTOCOL), (void **) &loaded_image);
3057 if (err != EFI_SUCCESS)
3058 return log_error_status(err, "Error getting LoadedImageProtocol handle: %m");
3059
3060 /* If we had to append an initrd= entry to the command line, we have to pass it, and measure it.
3061 * Otherwise, only pass/measure it if it is not implicit anyway (i.e. embedded into the UKI or
3062 * so). */
3063 _cleanup_free_ char16_t *options = xstrdup16(options_initrd ?: entry->options_implied ? NULL : entry->options);
3064
3065 if (entry->type == LOADER_LINUX && !is_confidential_vm()) {
3066 const char *extra = smbios_find_oem_string("io.systemd.boot.kernel-cmdline-extra=", /* after= */ NULL);
3067 if (extra) {
3068 _cleanup_free_ char16_t *tmp = TAKE_PTR(options), *extra16 = xstr8_to_16(extra);
3069 if (isempty(tmp))
3070 options = TAKE_PTR(extra16);
3071 else
3072 options = xasprintf("%ls %ls", tmp, extra16);
3073 }
3074 }
3075
3076 /* Prefix profile if it's non-zero */
3077 if (entry->profile > 0) {
3078 _cleanup_free_ char16_t *tmp = TAKE_PTR(options);
3079 if (isempty(tmp))
3080 options = xasprintf("@%u", entry->profile);
3081 else
3082 options = xasprintf("@%u %ls", entry->profile, tmp);
3083 }
3084
3085 if (options) {
3086 loaded_image->LoadOptions = options;
3087 loaded_image->LoadOptionsSize = strsize16(options);
3088
3089 /* Try to log any options to the TPM, especially to catch manually edited options */
3090 (void) tpm_log_load_options(options, NULL);
3091 }
3092
3093 efivar_set_time_usec(MAKE_GUID_PTR(LOADER), u"LoaderTimeExecUSec", 0);
3094 err = BS->StartImage(image, NULL, NULL);
3095 graphics_mode(false);
3096 if (err == EFI_SUCCESS)
3097 return EFI_SUCCESS;
3098
3099 /* Try calling the kernel compat entry point if one exists. */
3100 if (err == EFI_UNSUPPORTED && entry->type == LOADER_LINUX) {
3101 uint32_t compat_address;
3102
3103 err = pe_kernel_info(loaded_image->ImageBase, /* ret_entry_point= */ NULL, &compat_address,
3104 /* ret_size_in_memory= */ NULL);
3105 if (err != EFI_SUCCESS) {
3106 if (err != EFI_UNSUPPORTED)
3107 return log_error_status(err, "Error finding kernel compat entry address: %m");
3108 } else if (compat_address > 0) {
3109 EFI_IMAGE_ENTRY_POINT kernel_entry =
3110 (EFI_IMAGE_ENTRY_POINT) ((uint8_t *) loaded_image->ImageBase + compat_address);
3111
3112 err = kernel_entry(image, ST);
3113 graphics_mode(false);
3114 if (err == EFI_SUCCESS)
3115 return EFI_SUCCESS;
3116 } else
3117 err = EFI_UNSUPPORTED;
3118 }
3119
3120 return log_error_status(err, "Failed to execute %ls (%ls): %m", entry->title_show, entry->loader ?: entry->url);
3121 }
3122
3123 static void config_free(Config *config) {
3124 assert(config);
3125 for (size_t i = 0; i < config->n_entries; i++)
3126 boot_entry_free(config->entries[i]);
3127 free(config->entries);
3128 free(config->entry_default_config);
3129 free(config->entry_default_efivar);
3130 free(config->entry_preferred_config);
3131 free(config->entry_preferred_efivar);
3132 free(config->entry_oneshot);
3133 free(config->entry_saved);
3134 free(config->entry_sysfail);
3135 }
3136
3137 static void config_write_entries_to_variable(Config *config) {
3138 _cleanup_free_ char *buffer = NULL;
3139 size_t sz = 0;
3140 char *p;
3141
3142 assert(config);
3143
3144 for (size_t i = 0; i < config->n_entries; i++)
3145 sz += strsize16(config->entries[i]->id);
3146
3147 p = buffer = xmalloc(sz);
3148
3149 for (size_t i = 0; i < config->n_entries; i++)
3150 p = mempcpy(p, config->entries[i]->id, strsize16(config->entries[i]->id));
3151
3152 assert(p == buffer + sz);
3153
3154 /* Store the full list of discovered entries. */
3155 (void) efivar_set_raw(MAKE_GUID_PTR(LOADER), u"LoaderEntries", buffer, sz, 0);
3156 }
3157
3158 static void save_selected_entry(const Config *config, const BootEntry *entry) {
3159 assert(config);
3160 assert(entry);
3161
3162 if (!LOADER_TYPE_SAVE_ENTRY(entry->type))
3163 return;
3164
3165 /* Always export the selected boot entry to the system in a volatile var. */
3166 (void) efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntrySelected", entry->id, 0);
3167
3168 /* Do not save or delete if this was a oneshot boot. */
3169 if (streq16(config->entry_oneshot, entry->id))
3170 return;
3171
3172 if (config->use_saved_entry_efivar || (!config->entry_default_efivar && config->use_saved_entry)) {
3173 /* Avoid unnecessary NVRAM writes. */
3174 if (streq16(config->entry_saved, entry->id))
3175 return;
3176
3177 (void) efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderEntryLastBooted", entry->id, EFI_VARIABLE_NON_VOLATILE);
3178 } else
3179 /* Delete the non-volatile var if not needed. */
3180 (void) efivar_unset(MAKE_GUID_PTR(LOADER), u"LoaderEntryLastBooted", EFI_VARIABLE_NON_VOLATILE);
3181 }
3182
3183 static EFI_STATUS call_secure_boot_enroll(const BootEntry *entry, EFI_FILE *root_dir, EFI_HANDLE parent_image) {
3184 assert(entry);
3185
3186 return secure_boot_enroll_at(root_dir, entry->directory, /* force= */ true, /* action= */ ENROLL_ACTION_REBOOT,
3187 ENROLL_TIMEOUT_DEFAULT);
3188 }
3189
3190 static EFI_STATUS secure_boot_discover_keys(Config *config, EFI_FILE *root_dir) {
3191 EFI_STATUS err;
3192 _cleanup_file_close_ EFI_FILE *keys_basedir = NULL;
3193
3194 if (config->secure_boot_enroll == ENROLL_OFF)
3195 return EFI_SUCCESS;
3196
3197 if (!IN_SET(secure_boot_mode(), SECURE_BOOT_SETUP, SECURE_BOOT_AUDIT))
3198 return EFI_SUCCESS;
3199
3200 /* the lack of a 'keys' directory is not fatal and is silently ignored */
3201 err = open_directory(root_dir, u"\\loader\\keys", &keys_basedir);
3202 if (err == EFI_NOT_FOUND)
3203 return EFI_SUCCESS;
3204 if (err != EFI_SUCCESS)
3205 return err;
3206
3207 for (;;) {
3208 _cleanup_free_ EFI_FILE_INFO *dirent = NULL;
3209 size_t dirent_size = 0;
3210 BootEntry *entry = NULL;
3211
3212 err = readdir(keys_basedir, &dirent, &dirent_size);
3213 if (err != EFI_SUCCESS || !dirent)
3214 return err;
3215
3216 if (dirent->FileName[0] == '.')
3217 continue;
3218
3219 if (!FLAGS_SET(dirent->Attribute, EFI_FILE_DIRECTORY))
3220 continue;
3221
3222 entry = xnew(BootEntry, 1);
3223 *entry = (BootEntry) {
3224 .id = xasprintf("secure-boot-keys-%ls", dirent->FileName),
3225 .title = xasprintf("Enroll Secure Boot keys: %ls", dirent->FileName),
3226 .directory = xasprintf("\\loader\\keys\\%ls", dirent->FileName),
3227 .type = LOADER_SECURE_BOOT_KEYS,
3228 .tries_done = -1,
3229 .tries_left = -1,
3230 .call = call_secure_boot_enroll,
3231 };
3232 config_add_entry(config, entry);
3233
3234 if (IN_SET(config->secure_boot_enroll, ENROLL_IF_SAFE, ENROLL_FORCE) &&
3235 strcaseeq16(dirent->FileName, u"auto"))
3236 /* If we auto enroll successfully this call does not return.
3237 * If it fails we still want to add other potential entries to the menu. */
3238 secure_boot_enroll_at(root_dir, entry->directory, config->secure_boot_enroll == ENROLL_FORCE,
3239 config->secure_boot_enroll_action, config->secure_boot_enroll_timeout_sec);
3240 }
3241
3242 return EFI_SUCCESS;
3243 }
3244
3245 static void export_loader_variables(
3246 EFI_LOADED_IMAGE_PROTOCOL *loaded_image,
3247 uint64_t init_usec) {
3248
3249 static const uint64_t loader_features =
3250 EFI_LOADER_FEATURE_CONFIG_TIMEOUT |
3251 EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT |
3252 EFI_LOADER_FEATURE_ENTRY_DEFAULT |
3253 EFI_LOADER_FEATURE_ENTRY_PREFERRED |
3254 EFI_LOADER_FEATURE_ENTRY_ONESHOT |
3255 EFI_LOADER_FEATURE_BOOT_COUNTING |
3256 EFI_LOADER_FEATURE_XBOOTLDR |
3257 EFI_LOADER_FEATURE_RANDOM_SEED |
3258 EFI_LOADER_FEATURE_LOAD_DRIVER |
3259 EFI_LOADER_FEATURE_SORT_KEY |
3260 EFI_LOADER_FEATURE_SAVED_ENTRY |
3261 EFI_LOADER_FEATURE_DEVICETREE |
3262 EFI_LOADER_FEATURE_SECUREBOOT_ENROLL |
3263 EFI_LOADER_FEATURE_RETAIN_SHIM |
3264 EFI_LOADER_FEATURE_MENU_DISABLE |
3265 EFI_LOADER_FEATURE_MULTI_PROFILE_UKI |
3266 EFI_LOADER_FEATURE_REPORT_URL |
3267 EFI_LOADER_FEATURE_TYPE1_UKI |
3268 EFI_LOADER_FEATURE_TYPE1_UKI_URL |
3269 EFI_LOADER_FEATURE_TPM2_ACTIVE_PCR_BANKS |
3270 EFI_LOADER_FEATURE_KEYBOARD_LAYOUT |
3271 EFI_LOADER_FEATURE_SMBIOS_MEASURED |
3272 0;
3273
3274 assert(loaded_image);
3275
3276 efivar_set_time_usec(MAKE_GUID_PTR(LOADER), u"LoaderTimeInitUSec", init_usec);
3277 (void) efivar_set_str16(MAKE_GUID_PTR(LOADER), u"LoaderInfo", u"systemd-boot " GIT_VERSION, 0);
3278 (void) efivar_set_uint64_le(MAKE_GUID_PTR(LOADER), u"LoaderFeatures", loader_features, 0);
3279 }
3280
3281 static void config_add_system_entries(Config *config) {
3282 assert(config);
3283
3284 if (config->auto_firmware && FLAGS_SET(get_os_indications_supported(), EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
3285 BootEntry *entry = xnew(BootEntry, 1);
3286 *entry = (BootEntry) {
3287 .type = LOADER_FWSETUP,
3288 .id = xstrdup16(u"auto-reboot-to-firmware-setup"),
3289 .title = xstrdup16(u"Reboot Into Firmware Interface"),
3290 .call = call_reboot_into_firmware,
3291 .tries_done = -1,
3292 .tries_left = -1,
3293 };
3294 config_add_entry(config, entry);
3295 }
3296
3297 if (config->auto_poweroff) {
3298 BootEntry *entry = xnew(BootEntry, 1);
3299 *entry = (BootEntry) {
3300 .type = LOADER_POWEROFF,
3301 .id = xstrdup16(u"auto-poweroff"),
3302 .title = xstrdup16(u"Power Off The System"),
3303 .call = call_poweroff_system,
3304 .tries_done = -1,
3305 .tries_left = -1,
3306 };
3307 config_add_entry(config, entry);
3308 }
3309
3310 if (config->auto_reboot) {
3311 BootEntry *entry = xnew(BootEntry, 1);
3312 *entry = (BootEntry) {
3313 .type = LOADER_REBOOT,
3314 .id = xstrdup16(u"auto-reboot"),
3315 .title = xstrdup16(u"Reboot The System"),
3316 .call = call_reboot_system,
3317 .tries_done = -1,
3318 .tries_left = -1,
3319 };
3320 config_add_entry(config, entry);
3321 }
3322
3323 }
3324
3325 static void config_load_all_entries(
3326 Config *config,
3327 EFI_LOADED_IMAGE_PROTOCOL *loaded_image,
3328 const char16_t *loaded_image_path,
3329 EFI_FILE *root_dir) {
3330
3331 assert(config);
3332 assert(loaded_image);
3333 assert(root_dir);
3334
3335 config_load_defaults(config, root_dir);
3336
3337 /* Scan /EFI/Linux/ directory */
3338 config_load_type2_entries(config, loaded_image->DeviceHandle, root_dir);
3339
3340 /* Scan /loader/entries/\*.conf files */
3341 config_load_type1_entries(config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
3342
3343 /* Similar, but on any XBOOTLDR partition */
3344 config_load_xbootldr(config, loaded_image->DeviceHandle);
3345
3346 /* Pick up entries defined via SMBIOS Type #11 */
3347 config_load_smbios_entries(config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
3348
3349 /* Sort entries after version number */
3350 sort_pointer_array((void **) config->entries, config->n_entries, (compare_pointer_func_t) boot_entry_compare);
3351
3352 /* If we find some well-known loaders, add them to the end of the list */
3353 config_add_entry_osx(config);
3354 config_add_entry_windows(config, loaded_image->DeviceHandle, root_dir);
3355 config_add_entry_loader_auto(
3356 config,
3357 loaded_image->DeviceHandle,
3358 root_dir,
3359 /* loaded_image_path= */ NULL,
3360 u"auto-efi-shell",
3361 's',
3362 u"EFI Shell",
3363 u"\\shell" EFI_MACHINE_TYPE_NAME ".efi");
3364 config_add_entry_loader_auto(
3365 config,
3366 loaded_image->DeviceHandle,
3367 root_dir,
3368 loaded_image_path,
3369 u"auto-efi-default",
3370 '\0',
3371 u"EFI Default Loader",
3372 /* loader= */ NULL);
3373
3374 config_add_system_entries(config);
3375
3376 /* Using the rules defined by the `secure-boot-enroll` variable, find secure boot signing keys
3377 * and perform operations like autoloading them or create menu entries if configured. */
3378 (void) secure_boot_discover_keys(config, root_dir);
3379
3380 if (config->n_entries == 0)
3381 return;
3382
3383 config_write_entries_to_variable(config);
3384
3385 generate_boot_entry_titles(config);
3386
3387 /* Select entry by configured pattern or EFI LoaderDefaultEntry= variable */
3388 config_select_default_entry(config);
3389 }
3390
3391 static EFI_STATUS discover_root_dir(EFI_LOADED_IMAGE_PROTOCOL *loaded_image, EFI_FILE **ret_dir) {
3392 if (is_direct_boot(loaded_image->DeviceHandle))
3393 return vmm_open(&loaded_image->DeviceHandle, ret_dir);
3394 else
3395 return open_volume(loaded_image->DeviceHandle, ret_dir);
3396 }
3397
3398 static EFI_STATUS run(EFI_HANDLE image) {
3399 EFI_LOADED_IMAGE_PROTOCOL *loaded_image;
3400 _cleanup_file_close_ EFI_FILE *root_dir = NULL;
3401 _cleanup_(config_free) Config config = {};
3402 EFI_STATUS err;
3403 uint64_t init_usec;
3404 bool menu = false;
3405
3406 /* set loglevel early to simplify debugging before loader.conf is loaded */
3407 log_set_max_level_from_smbios();
3408
3409 init_usec = time_usec();
3410
3411 err = BS->HandleProtocol(image, MAKE_GUID_PTR(EFI_LOADED_IMAGE_PROTOCOL), (void **) &loaded_image);
3412 if (err != EFI_SUCCESS)
3413 return log_error_status(err, "Error getting a LoadedImageProtocol handle: %m");
3414
3415 err = discover_root_dir(loaded_image, &root_dir);
3416 if (err != EFI_SUCCESS) {
3417 log_error_status(err, "Unable to open root directory: %m");
3418
3419 /* If opening the root directory fails this typically means someone is trying to boot our
3420 * systemd-boot EFI PE binary as network boot NBP. That cannot work however, since we
3421 * wouldn't find any menu entries. Provide a helpful message what to try instead. */
3422
3423 if (err == EFI_UNSUPPORTED)
3424 log_info("| Note that invoking systemd-boot directly as UEFI network boot NBP is not\n"
3425 "| supported. Instead of booting the systemd-boot PE binary (i.e. an .efi file)\n"
3426 "| via the network, use an EFI GPT disk image (i.e. a file with .img suffix)\n"
3427 "| containing systemd-boot instead.");
3428
3429 return err;
3430 }
3431
3432 /* Ask Shim to leave its protocol around, so that the stub can use it to validate PEs.
3433 * By default, Shim uninstalls its protocol when calling StartImage(). */
3434 shim_retain_protocol();
3435
3436 export_common_variables(loaded_image);
3437 export_loader_variables(loaded_image, init_usec);
3438
3439 /* Measure SMBIOS data into PCR 1. This is done early, and suppressed if sd-stub later runs in
3440 * the same boot (and vice versa), via the LoaderPcrSMBIOS EFI variable. */
3441 measure_smbios();
3442
3443 (void) load_drivers(image, loaded_image, root_dir);
3444
3445 _cleanup_free_ char16_t *loaded_image_path = NULL;
3446 (void) device_path_to_str(loaded_image->FilePath, &loaded_image_path);
3447 config_load_all_entries(&config, loaded_image, loaded_image_path, root_dir);
3448 (void) sysfail_process(&config);
3449
3450 if (config.n_entries == 0)
3451 return log_error_status(
3452 EFI_NOT_FOUND,
3453 "No loader found. Configuration files in \\loader\\entries\\*.conf are needed.");
3454
3455 /* select entry or show menu when key is pressed or timeout is set */
3456 if (config.force_menu || !IN_SET(config.timeout_sec, TIMEOUT_MENU_HIDDEN, TIMEOUT_MENU_DISABLED))
3457 menu = true;
3458 else if (config.timeout_sec != TIMEOUT_MENU_DISABLED) {
3459 uint64_t key;
3460
3461 /* Block up to 100ms to give firmware time to get input working. */
3462 err = console_key_read(&key, 100 * 1000);
3463 if (err == EFI_SUCCESS) {
3464 /* find matching key in boot entries */
3465 size_t idx = entry_lookup_key(&config, config.idx_default, KEYCHAR(key));
3466 if (idx != IDX_INVALID)
3467 config.idx_default = idx;
3468 else
3469 menu = true;
3470 }
3471 }
3472
3473 for (;;) {
3474 BootEntry *entry;
3475
3476 entry = config.entries[config.idx_default];
3477 if (menu) {
3478 efivar_set_time_usec(MAKE_GUID_PTR(LOADER), u"LoaderTimeMenuUSec", 0);
3479 if (!menu_run(&config, &entry, loaded_image_path))
3480 return EFI_SUCCESS;
3481 }
3482
3483 (void) boot_entry_bump_counters(entry);
3484 save_selected_entry(&config, entry);
3485
3486 /* Optionally, read a random seed off the ESP and pass it to the OS */
3487 if (LOADER_TYPE_PROCESS_RANDOM_SEED(entry->type))
3488 (void) process_random_seed(root_dir);
3489
3490 err = ASSERT_PTR(entry->call)(entry, root_dir, image);
3491 if (err != EFI_SUCCESS) {
3492 if (config.reboot_on_error == REBOOT_YES || (config.reboot_on_error == REBOOT_AUTO && entry->tries_left > 0)) {
3493 printf("Failed to start boot entry. Rebooting in 5s.\n");
3494 BS->Stall(5 * 1000 * 1000);
3495 (void) call_reboot_system(/* entry= */ NULL, /* root_dir= */ NULL, /* parent_image= */ NULL);
3496 }
3497 return err;
3498 }
3499
3500 menu = true;
3501 config.timeout_sec = 0;
3502 }
3503 }
3504
3505 // NOLINTNEXTLINE(misc-use-internal-linkage)
3506 DEFINE_EFI_MAIN_FUNCTION(run, "systemd-boot", /* wait_for_debugger= */ false);