]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/boot/efi/boot.c
sd-boot: Skip adding boot entries when the loader does not exist
[thirdparty/systemd.git] / src / boot / efi / boot.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <efi.h>
4 #include <efigpt.h>
5 #include <efilib.h>
6
7 #include "console.h"
8 #include "crc32.h"
9 #include "disk.h"
10 #include "graphics.h"
11 #include "linux.h"
12 #include "loader-features.h"
13 #include "measure.h"
14 #include "pe.h"
15 #include "random-seed.h"
16 #include "shim.h"
17 #include "util.h"
18
19 #ifndef EFI_OS_INDICATIONS_BOOT_TO_FW_UI
20 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001ULL
21 #endif
22
23 /* magic string to find in the binary image */
24 static const char __attribute__((used)) magic[] = "#### LoaderInfo: systemd-boot " GIT_VERSION " ####";
25
26 static const EFI_GUID global_guid = EFI_GLOBAL_VARIABLE;
27
28 enum loader_type {
29 LOADER_UNDEFINED,
30 LOADER_EFI,
31 LOADER_LINUX,
32 };
33
34 typedef struct {
35 CHAR16 *id; /* The identifier for this entry (note that this id is not necessarily unique though!) */
36 CHAR16 *title_show;
37 CHAR16 *title;
38 CHAR16 *version;
39 CHAR16 *machine_id;
40 EFI_HANDLE *device;
41 enum loader_type type;
42 CHAR16 *loader;
43 CHAR16 *options;
44 CHAR16 key;
45 EFI_STATUS (*call)(VOID);
46 BOOLEAN no_autoselect;
47 BOOLEAN non_unique;
48 UINTN tries_done;
49 UINTN tries_left;
50 CHAR16 *path;
51 CHAR16 *current_name;
52 CHAR16 *next_name;
53 } ConfigEntry;
54
55 typedef struct {
56 ConfigEntry **entries;
57 UINTN entry_count;
58 INTN idx_default;
59 INTN idx_default_efivar;
60 UINTN timeout_sec;
61 UINTN timeout_sec_config;
62 INTN timeout_sec_efivar;
63 CHAR16 *entry_default_pattern;
64 CHAR16 *entry_oneshot;
65 CHAR16 *options_edit;
66 BOOLEAN editor;
67 BOOLEAN auto_entries;
68 BOOLEAN auto_firmware;
69 BOOLEAN force_menu;
70 UINTN console_mode;
71 enum console_mode_change_type console_mode_change;
72 RandomSeedMode random_seed_mode;
73 } Config;
74
75 static VOID cursor_left(UINTN *cursor, UINTN *first) {
76 if ((*cursor) > 0)
77 (*cursor)--;
78 else if ((*first) > 0)
79 (*first)--;
80 }
81
82 static VOID cursor_right(
83 UINTN *cursor,
84 UINTN *first,
85 UINTN x_max,
86 UINTN len) {
87
88 if ((*cursor)+1 < x_max)
89 (*cursor)++;
90 else if ((*first) + (*cursor) < len)
91 (*first)++;
92 }
93
94 static BOOLEAN line_edit(
95 CHAR16 *line_in,
96 CHAR16 **line_out,
97 UINTN x_max,
98 UINTN y_pos) {
99
100 _cleanup_freepool_ CHAR16 *line = NULL, *print = NULL;
101 UINTN size, len, first, cursor, clear;
102 BOOLEAN exit, enter;
103
104 if (!line_in)
105 line_in = L"";
106 size = StrLen(line_in) + 1024;
107 line = AllocatePool(size * sizeof(CHAR16));
108 StrCpy(line, line_in);
109 len = StrLen(line);
110 print = AllocatePool((x_max+1) * sizeof(CHAR16));
111
112 uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, TRUE);
113
114 first = 0;
115 cursor = 0;
116 clear = 0;
117 enter = FALSE;
118 exit = FALSE;
119 while (!exit) {
120 EFI_STATUS err;
121 UINT64 key;
122 UINTN i;
123
124 i = len - first;
125 if (i >= x_max-1)
126 i = x_max-1;
127 CopyMem(print, line + first, i * sizeof(CHAR16));
128 while (clear > 0 && i < x_max-1) {
129 clear--;
130 print[i++] = ' ';
131 }
132 print[i] = '\0';
133
134 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_pos);
135 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, print);
136 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
137
138 err = console_key_read(&key, TRUE);
139 if (EFI_ERROR(err))
140 continue;
141
142 switch (key) {
143 case KEYPRESS(0, SCAN_ESC, 0):
144 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'c'):
145 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'g'):
146 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('c')):
147 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('g')):
148 exit = TRUE;
149 break;
150
151 case KEYPRESS(0, SCAN_HOME, 0):
152 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'a'):
153 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('a')):
154 /* beginning-of-line */
155 cursor = 0;
156 first = 0;
157 continue;
158
159 case KEYPRESS(0, SCAN_END, 0):
160 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'e'):
161 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('e')):
162 /* end-of-line */
163 cursor = len - first;
164 if (cursor+1 >= x_max) {
165 cursor = x_max-1;
166 first = len - (x_max-1);
167 }
168 continue;
169
170 case KEYPRESS(0, SCAN_DOWN, 0):
171 case KEYPRESS(EFI_ALT_PRESSED, 0, 'f'):
172 case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_RIGHT, 0):
173 /* forward-word */
174 while (line[first + cursor] == ' ')
175 cursor_right(&cursor, &first, x_max, len);
176 while (line[first + cursor] && line[first + cursor] != ' ')
177 cursor_right(&cursor, &first, x_max, len);
178 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
179 continue;
180
181 case KEYPRESS(0, SCAN_UP, 0):
182 case KEYPRESS(EFI_ALT_PRESSED, 0, 'b'):
183 case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_LEFT, 0):
184 /* backward-word */
185 if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
186 cursor_left(&cursor, &first);
187 while ((first + cursor) > 0 && line[first + cursor] == ' ')
188 cursor_left(&cursor, &first);
189 }
190 while ((first + cursor) > 0 && line[first + cursor-1] != ' ')
191 cursor_left(&cursor, &first);
192 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
193 continue;
194
195 case KEYPRESS(0, SCAN_RIGHT, 0):
196 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'f'):
197 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('f')):
198 /* forward-char */
199 if (first + cursor == len)
200 continue;
201 cursor_right(&cursor, &first, x_max, len);
202 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
203 continue;
204
205 case KEYPRESS(0, SCAN_LEFT, 0):
206 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'b'):
207 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('b')):
208 /* backward-char */
209 cursor_left(&cursor, &first);
210 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
211 continue;
212
213 case KEYPRESS(EFI_ALT_PRESSED, 0, 'd'):
214 /* kill-word */
215 clear = 0;
216 for (i = first + cursor; i < len && line[i] == ' '; i++)
217 clear++;
218 for (; i < len && line[i] != ' '; i++)
219 clear++;
220
221 for (i = first + cursor; i + clear < len; i++)
222 line[i] = line[i + clear];
223 len -= clear;
224 line[len] = '\0';
225 continue;
226
227 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'w'):
228 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('w')):
229 case KEYPRESS(EFI_ALT_PRESSED, 0, CHAR_BACKSPACE):
230 /* backward-kill-word */
231 clear = 0;
232 if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
233 cursor_left(&cursor, &first);
234 clear++;
235 while ((first + cursor) > 0 && line[first + cursor] == ' ') {
236 cursor_left(&cursor, &first);
237 clear++;
238 }
239 }
240 while ((first + cursor) > 0 && line[first + cursor-1] != ' ') {
241 cursor_left(&cursor, &first);
242 clear++;
243 }
244 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
245
246 for (i = first + cursor; i + clear < len; i++)
247 line[i] = line[i + clear];
248 len -= clear;
249 line[len] = '\0';
250 continue;
251
252 case KEYPRESS(0, SCAN_DELETE, 0):
253 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'd'):
254 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('d')):
255 if (len == 0)
256 continue;
257 if (first + cursor == len)
258 continue;
259 for (i = first + cursor; i < len; i++)
260 line[i] = line[i+1];
261 clear = 1;
262 len--;
263 continue;
264
265 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'k'):
266 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('k')):
267 /* kill-line */
268 line[first + cursor] = '\0';
269 clear = len - (first + cursor);
270 len = first + cursor;
271 continue;
272
273 case KEYPRESS(0, 0, CHAR_LINEFEED):
274 case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
275 if (StrCmp(line, line_in) != 0)
276 *line_out = TAKE_PTR(line);
277 enter = TRUE;
278 exit = TRUE;
279 break;
280
281 case KEYPRESS(0, 0, CHAR_BACKSPACE):
282 if (len == 0)
283 continue;
284 if (first == 0 && cursor == 0)
285 continue;
286 for (i = first + cursor-1; i < len; i++)
287 line[i] = line[i+1];
288 clear = 1;
289 len--;
290 if (cursor > 0)
291 cursor--;
292 if (cursor > 0 || first == 0)
293 continue;
294 /* show full line if it fits */
295 if (len < x_max) {
296 cursor = first;
297 first = 0;
298 continue;
299 }
300 /* jump left to see what we delete */
301 if (first > 10) {
302 first -= 10;
303 cursor = 10;
304 } else {
305 cursor = first;
306 first = 0;
307 }
308 continue;
309
310 case KEYPRESS(0, 0, ' ') ... KEYPRESS(0, 0, '~'):
311 case KEYPRESS(0, 0, 0x80) ... KEYPRESS(0, 0, 0xffff):
312 if (len+1 == size)
313 continue;
314 for (i = len; i > first + cursor; i--)
315 line[i] = line[i-1];
316 line[first + cursor] = KEYCHAR(key);
317 len++;
318 line[len] = '\0';
319 if (cursor+1 < x_max)
320 cursor++;
321 else if (first + cursor < len)
322 first++;
323 continue;
324 }
325 }
326
327 uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, FALSE);
328 return enter;
329 }
330
331 static UINTN entry_lookup_key(Config *config, UINTN start, CHAR16 key) {
332 UINTN i;
333
334 if (key == 0)
335 return -1;
336
337 /* select entry by number key */
338 if (key >= '1' && key <= '9') {
339 i = key - '0';
340 if (i > config->entry_count)
341 i = config->entry_count;
342 return i-1;
343 }
344
345 /* find matching key in config entries */
346 for (i = start; i < config->entry_count; i++)
347 if (config->entries[i]->key == key)
348 return i;
349
350 for (i = 0; i < start; i++)
351 if (config->entries[i]->key == key)
352 return i;
353
354 return -1;
355 }
356
357 static VOID print_status(Config *config, CHAR16 *loaded_image_path) {
358 UINT64 key;
359 UINTN i;
360 _cleanup_freepool_ CHAR8 *bootvar = NULL, *modevar = NULL, *indvar = NULL;
361 _cleanup_freepool_ CHAR16 *partstr = NULL, *defaultstr = NULL;
362 UINTN x, y, size;
363
364 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
365 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
366
367 Print(L"systemd-boot version: " GIT_VERSION "\n");
368 Print(L"architecture: " EFI_MACHINE_TYPE_NAME "\n");
369 Print(L"loaded image: %s\n", loaded_image_path);
370 Print(L"UEFI specification: %d.%02d\n", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
371 Print(L"firmware vendor: %s\n", ST->FirmwareVendor);
372 Print(L"firmware version: %d.%02d\n", ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
373
374 if (uefi_call_wrapper(ST->ConOut->QueryMode, 4, ST->ConOut, ST->ConOut->Mode->Mode, &x, &y) == EFI_SUCCESS)
375 Print(L"console size: %d x %d\n", x, y);
376
377 if (efivar_get_raw(&global_guid, L"SecureBoot", &bootvar, &size) == EFI_SUCCESS)
378 Print(L"SecureBoot: %s\n", yes_no(*bootvar > 0));
379
380 if (efivar_get_raw(&global_guid, L"SetupMode", &modevar, &size) == EFI_SUCCESS)
381 Print(L"SetupMode: %s\n", *modevar > 0 ? L"setup" : L"user");
382
383 if (shim_loaded())
384 Print(L"Shim: present\n");
385
386 if (efivar_get_raw(&global_guid, L"OsIndicationsSupported", &indvar, &size) == EFI_SUCCESS)
387 Print(L"OsIndicationsSupported: %d\n", (UINT64)*indvar);
388
389 Print(L"\n--- press key ---\n\n");
390 console_key_read(&key, TRUE);
391
392 Print(L"timeout: %u\n", config->timeout_sec);
393 if (config->timeout_sec_efivar >= 0)
394 Print(L"timeout (EFI var): %d\n", config->timeout_sec_efivar);
395 Print(L"timeout (config): %u\n", config->timeout_sec_config);
396 if (config->entry_default_pattern)
397 Print(L"default pattern: '%s'\n", config->entry_default_pattern);
398 Print(L"editor: %s\n", yes_no(config->editor));
399 Print(L"auto-entries: %s\n", yes_no(config->auto_entries));
400 Print(L"auto-firmware: %s\n", yes_no(config->auto_firmware));
401
402 switch (config->random_seed_mode) {
403 case RANDOM_SEED_OFF:
404 Print(L"random-seed-mode: off\n");
405 break;
406 case RANDOM_SEED_WITH_SYSTEM_TOKEN:
407 Print(L"random-seed-node: with-system-token\n");
408 break;
409 case RANDOM_SEED_ALWAYS:
410 Print(L"random-seed-node: always\n");
411 break;
412 default:
413 ;
414 }
415
416 Print(L"\n");
417
418 Print(L"config entry count: %d\n", config->entry_count);
419 Print(L"entry selected idx: %d\n", config->idx_default);
420 if (config->idx_default_efivar >= 0)
421 Print(L"entry EFI var idx: %d\n", config->idx_default_efivar);
422 Print(L"\n");
423
424 if (efivar_get_int(L"LoaderConfigTimeout", &i) == EFI_SUCCESS)
425 Print(L"LoaderConfigTimeout: %u\n", i);
426
427 if (config->entry_oneshot)
428 Print(L"LoaderEntryOneShot: %s\n", config->entry_oneshot);
429 if (efivar_get(L"LoaderDevicePartUUID", &partstr) == EFI_SUCCESS)
430 Print(L"LoaderDevicePartUUID: %s\n", partstr);
431 if (efivar_get(L"LoaderEntryDefault", &defaultstr) == EFI_SUCCESS)
432 Print(L"LoaderEntryDefault: %s\n", defaultstr);
433
434 Print(L"\n--- press key ---\n\n");
435 console_key_read(&key, TRUE);
436
437 for (i = 0; i < config->entry_count; i++) {
438 ConfigEntry *entry;
439
440 if (key == KEYPRESS(0, SCAN_ESC, 0) || key == KEYPRESS(0, 0, 'q'))
441 break;
442
443 entry = config->entries[i];
444 Print(L"config entry: %d/%d\n", i+1, config->entry_count);
445 if (entry->id)
446 Print(L"id '%s'\n", entry->id);
447 Print(L"title show '%s'\n", entry->title_show);
448 if (entry->title)
449 Print(L"title '%s'\n", entry->title);
450 if (entry->version)
451 Print(L"version '%s'\n", entry->version);
452 if (entry->machine_id)
453 Print(L"machine-id '%s'\n", entry->machine_id);
454 if (entry->device) {
455 EFI_DEVICE_PATH *device_path;
456
457 device_path = DevicePathFromHandle(entry->device);
458 if (device_path) {
459 _cleanup_freepool_ CHAR16 *str;
460
461 str = DevicePathToStr(device_path);
462 Print(L"device handle '%s'\n", str);
463 }
464 }
465 if (entry->loader)
466 Print(L"loader '%s'\n", entry->loader);
467 if (entry->options)
468 Print(L"options '%s'\n", entry->options);
469 Print(L"auto-select %s\n", yes_no(!entry->no_autoselect));
470 if (entry->call)
471 Print(L"internal call yes\n");
472
473 if (entry->tries_left != (UINTN) -1)
474 Print(L"counting boots yes\n"
475 "tries done %u\n"
476 "tries left %u\n"
477 "current path %s\\%s\n"
478 "next path %s\\%s\n",
479 entry->tries_done,
480 entry->tries_left,
481 entry->path, entry->current_name,
482 entry->path, entry->next_name);
483
484 Print(L"\n--- press key ---\n\n");
485 console_key_read(&key, TRUE);
486 }
487
488 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
489 }
490
491 static BOOLEAN menu_run(
492 Config *config,
493 ConfigEntry **chosen_entry,
494 CHAR16 *loaded_image_path) {
495
496 EFI_STATUS err;
497 UINTN visible_max;
498 UINTN idx_highlight;
499 UINTN idx_highlight_prev;
500 UINTN idx_first;
501 UINTN idx_last;
502 BOOLEAN refresh;
503 BOOLEAN highlight;
504 UINTN i;
505 UINTN line_width;
506 CHAR16 **lines;
507 UINTN x_start;
508 UINTN y_start;
509 UINTN x_max;
510 UINTN y_max;
511 CHAR16 *status;
512 CHAR16 *clearline;
513 INTN timeout_remain;
514 INT16 idx;
515 BOOLEAN exit = FALSE;
516 BOOLEAN run = TRUE;
517 BOOLEAN wait = FALSE;
518
519 graphics_mode(FALSE);
520 uefi_call_wrapper(ST->ConIn->Reset, 2, ST->ConIn, FALSE);
521 uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, FALSE);
522 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
523
524 /* draw a single character to make ClearScreen work on some firmware */
525 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L" ");
526
527 if (config->console_mode_change != CONSOLE_MODE_KEEP) {
528 err = console_set_mode(&config->console_mode, config->console_mode_change);
529 if (EFI_ERROR(err)) {
530 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
531 Print(L"Error switching console mode to %ld: %r.\r", (UINT64)config->console_mode, err);
532 }
533 } else
534 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
535
536 err = uefi_call_wrapper(ST->ConOut->QueryMode, 4, ST->ConOut, ST->ConOut->Mode->Mode, &x_max, &y_max);
537 if (EFI_ERROR(err)) {
538 x_max = 80;
539 y_max = 25;
540 }
541
542 /* we check 10 times per second for a keystroke */
543 if (config->timeout_sec > 0)
544 timeout_remain = config->timeout_sec * 10;
545 else
546 timeout_remain = -1;
547
548 idx_highlight = config->idx_default;
549 idx_highlight_prev = 0;
550
551 visible_max = y_max - 2;
552
553 if ((UINTN)config->idx_default >= visible_max)
554 idx_first = config->idx_default-1;
555 else
556 idx_first = 0;
557
558 idx_last = idx_first + visible_max-1;
559
560 refresh = TRUE;
561 highlight = FALSE;
562
563 /* length of the longest entry */
564 line_width = 5;
565 for (i = 0; i < config->entry_count; i++) {
566 UINTN entry_len;
567
568 entry_len = StrLen(config->entries[i]->title_show);
569 if (line_width < entry_len)
570 line_width = entry_len;
571 }
572 if (line_width > x_max-6)
573 line_width = x_max-6;
574
575 /* offsets to center the entries on the screen */
576 x_start = (x_max - (line_width)) / 2;
577 if (config->entry_count < visible_max)
578 y_start = ((visible_max - config->entry_count) / 2) + 1;
579 else
580 y_start = 0;
581
582 /* menu entries title lines */
583 lines = AllocatePool(sizeof(CHAR16 *) * config->entry_count);
584 for (i = 0; i < config->entry_count; i++) {
585 UINTN j, k;
586
587 lines[i] = AllocatePool(((x_max+1) * sizeof(CHAR16)));
588 for (j = 0; j < x_start; j++)
589 lines[i][j] = ' ';
590
591 for (k = 0; config->entries[i]->title_show[k] != '\0' && j < x_max; j++, k++)
592 lines[i][j] = config->entries[i]->title_show[k];
593
594 for (; j < x_max; j++)
595 lines[i][j] = ' ';
596 lines[i][x_max] = '\0';
597 }
598
599 status = NULL;
600 clearline = AllocatePool((x_max+1) * sizeof(CHAR16));
601 for (i = 0; i < x_max; i++)
602 clearline[i] = ' ';
603 clearline[i] = 0;
604
605 while (!exit) {
606 UINT64 key;
607
608 if (refresh) {
609 for (i = 0; i < config->entry_count; i++) {
610 if (i < idx_first || i > idx_last)
611 continue;
612 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + i - idx_first);
613 if (i == idx_highlight)
614 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut,
615 EFI_BLACK|EFI_BACKGROUND_LIGHTGRAY);
616 else
617 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut,
618 EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
619 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[i]);
620 if ((INTN)i == config->idx_default_efivar) {
621 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + i - idx_first);
622 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
623 }
624 }
625 refresh = FALSE;
626 } else if (highlight) {
627 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + idx_highlight_prev - idx_first);
628 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
629 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[idx_highlight_prev]);
630 if ((INTN)idx_highlight_prev == config->idx_default_efivar) {
631 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + idx_highlight_prev - idx_first);
632 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
633 }
634
635 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + idx_highlight - idx_first);
636 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_BLACK|EFI_BACKGROUND_LIGHTGRAY);
637 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[idx_highlight]);
638 if ((INTN)idx_highlight == config->idx_default_efivar) {
639 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + idx_highlight - idx_first);
640 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
641 }
642 highlight = FALSE;
643 }
644
645 if (timeout_remain > 0) {
646 FreePool(status);
647 status = PoolPrint(L"Boot in %d sec.", (timeout_remain + 5) / 10);
648 }
649
650 /* print status at last line of screen */
651 if (status) {
652 UINTN len;
653 UINTN x;
654
655 /* center line */
656 len = StrLen(status);
657 if (len < x_max)
658 x = (x_max - len) / 2;
659 else
660 x = 0;
661 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
662 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
663 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline + (x_max - x));
664 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, status);
665 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1 + x + len);
666 }
667
668 err = console_key_read(&key, wait);
669 if (EFI_ERROR(err)) {
670 /* timeout reached */
671 if (timeout_remain == 0) {
672 exit = TRUE;
673 break;
674 }
675
676 /* sleep and update status */
677 if (timeout_remain > 0) {
678 uefi_call_wrapper(BS->Stall, 1, 100 * 1000);
679 timeout_remain--;
680 continue;
681 }
682
683 /* timeout disabled, wait for next key */
684 wait = TRUE;
685 continue;
686 }
687
688 timeout_remain = -1;
689
690 /* clear status after keystroke */
691 if (status) {
692 FreePool(status);
693 status = NULL;
694 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
695 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
696 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
697 }
698
699 idx_highlight_prev = idx_highlight;
700
701 switch (key) {
702 case KEYPRESS(0, SCAN_UP, 0):
703 case KEYPRESS(0, 0, 'k'):
704 if (idx_highlight > 0)
705 idx_highlight--;
706 break;
707
708 case KEYPRESS(0, SCAN_DOWN, 0):
709 case KEYPRESS(0, 0, 'j'):
710 if (idx_highlight < config->entry_count-1)
711 idx_highlight++;
712 break;
713
714 case KEYPRESS(0, SCAN_HOME, 0):
715 case KEYPRESS(EFI_ALT_PRESSED, 0, '<'):
716 if (idx_highlight > 0) {
717 refresh = TRUE;
718 idx_highlight = 0;
719 }
720 break;
721
722 case KEYPRESS(0, SCAN_END, 0):
723 case KEYPRESS(EFI_ALT_PRESSED, 0, '>'):
724 if (idx_highlight < config->entry_count-1) {
725 refresh = TRUE;
726 idx_highlight = config->entry_count-1;
727 }
728 break;
729
730 case KEYPRESS(0, SCAN_PAGE_UP, 0):
731 if (idx_highlight > visible_max)
732 idx_highlight -= visible_max;
733 else
734 idx_highlight = 0;
735 break;
736
737 case KEYPRESS(0, SCAN_PAGE_DOWN, 0):
738 idx_highlight += visible_max;
739 if (idx_highlight > config->entry_count-1)
740 idx_highlight = config->entry_count-1;
741 break;
742
743 case KEYPRESS(0, 0, CHAR_LINEFEED):
744 case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
745 exit = TRUE;
746 break;
747
748 case KEYPRESS(0, SCAN_F1, 0):
749 case KEYPRESS(0, 0, 'h'):
750 case KEYPRESS(0, 0, '?'):
751 status = StrDuplicate(L"(d)efault, (t/T)timeout, (e)dit, (v)ersion (Q)uit (P)rint (h)elp");
752 break;
753
754 case KEYPRESS(0, 0, 'Q'):
755 exit = TRUE;
756 run = FALSE;
757 break;
758
759 case KEYPRESS(0, 0, 'd'):
760 if (config->idx_default_efivar != (INTN)idx_highlight) {
761 /* store the selected entry in a persistent EFI variable */
762 efivar_set(L"LoaderEntryDefault", config->entries[idx_highlight]->id, TRUE);
763 config->idx_default_efivar = idx_highlight;
764 status = StrDuplicate(L"Default boot entry selected.");
765 } else {
766 /* clear the default entry EFI variable */
767 efivar_set(L"LoaderEntryDefault", NULL, TRUE);
768 config->idx_default_efivar = -1;
769 status = StrDuplicate(L"Default boot entry cleared.");
770 }
771 refresh = TRUE;
772 break;
773
774 case KEYPRESS(0, 0, '-'):
775 case KEYPRESS(0, 0, 'T'):
776 if (config->timeout_sec_efivar > 0) {
777 config->timeout_sec_efivar--;
778 efivar_set_int(L"LoaderConfigTimeout", config->timeout_sec_efivar, TRUE);
779 if (config->timeout_sec_efivar > 0)
780 status = PoolPrint(L"Menu timeout set to %d sec.", config->timeout_sec_efivar);
781 else
782 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
783 } else if (config->timeout_sec_efivar <= 0){
784 config->timeout_sec_efivar = -1;
785 efivar_set(L"LoaderConfigTimeout", NULL, TRUE);
786 if (config->timeout_sec_config > 0)
787 status = PoolPrint(L"Menu timeout of %d sec is defined by configuration file.",
788 config->timeout_sec_config);
789 else
790 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
791 }
792 break;
793
794 case KEYPRESS(0, 0, '+'):
795 case KEYPRESS(0, 0, 't'):
796 if (config->timeout_sec_efivar == -1 && config->timeout_sec_config == 0)
797 config->timeout_sec_efivar++;
798 config->timeout_sec_efivar++;
799 efivar_set_int(L"LoaderConfigTimeout", config->timeout_sec_efivar, TRUE);
800 if (config->timeout_sec_efivar > 0)
801 status = PoolPrint(L"Menu timeout set to %d sec.",
802 config->timeout_sec_efivar);
803 else
804 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
805 break;
806
807 case KEYPRESS(0, 0, 'e'):
808 /* only the options of configured entries can be edited */
809 if (!config->editor || config->entries[idx_highlight]->type == LOADER_UNDEFINED)
810 break;
811 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
812 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
813 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
814 if (line_edit(config->entries[idx_highlight]->options, &config->options_edit, x_max-1, y_max-1))
815 exit = TRUE;
816 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
817 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
818 break;
819
820 case KEYPRESS(0, 0, 'v'):
821 status = PoolPrint(L"systemd-boot " GIT_VERSION " (" EFI_MACHINE_TYPE_NAME "), UEFI Specification %d.%02d, Vendor %s %d.%02d",
822 ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff,
823 ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
824 break;
825
826 case KEYPRESS(0, 0, 'P'):
827 print_status(config, loaded_image_path);
828 refresh = TRUE;
829 break;
830
831 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'l'):
832 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('l')):
833 refresh = TRUE;
834 break;
835
836 default:
837 /* jump with a hotkey directly to a matching entry */
838 idx = entry_lookup_key(config, idx_highlight+1, KEYCHAR(key));
839 if (idx < 0)
840 break;
841 idx_highlight = idx;
842 refresh = TRUE;
843 }
844
845 if (idx_highlight > idx_last) {
846 idx_last = idx_highlight;
847 idx_first = 1 + idx_highlight - visible_max;
848 refresh = TRUE;
849 } else if (idx_highlight < idx_first) {
850 idx_first = idx_highlight;
851 idx_last = idx_highlight + visible_max-1;
852 refresh = TRUE;
853 }
854
855 if (!refresh && idx_highlight != idx_highlight_prev)
856 highlight = TRUE;
857 }
858
859 *chosen_entry = config->entries[idx_highlight];
860
861 for (i = 0; i < config->entry_count; i++)
862 FreePool(lines[i]);
863 FreePool(lines);
864 FreePool(clearline);
865
866 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_WHITE|EFI_BACKGROUND_BLACK);
867 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
868 return run;
869 }
870
871 static VOID config_add_entry(Config *config, ConfigEntry *entry) {
872 if ((config->entry_count & 15) == 0) {
873 UINTN i;
874
875 i = config->entry_count + 16;
876 if (config->entry_count == 0)
877 config->entries = AllocatePool(sizeof(VOID *) * i);
878 else
879 config->entries = ReallocatePool(config->entries,
880 sizeof(VOID *) * config->entry_count, sizeof(VOID *) * i);
881 }
882 config->entries[config->entry_count++] = entry;
883 }
884
885 static VOID config_entry_free(ConfigEntry *entry) {
886 if (!entry)
887 return;
888
889 FreePool(entry->id);
890 FreePool(entry->title_show);
891 FreePool(entry->title);
892 FreePool(entry->version);
893 FreePool(entry->machine_id);
894 FreePool(entry->loader);
895 FreePool(entry->options);
896 FreePool(entry->path);
897 FreePool(entry->current_name);
898 FreePool(entry->next_name);
899 FreePool(entry);
900 }
901
902 static BOOLEAN is_digit(CHAR16 c) {
903 return (c >= '0') && (c <= '9');
904 }
905
906 static UINTN c_order(CHAR16 c) {
907 if (c == '\0')
908 return 0;
909 if (is_digit(c))
910 return 0;
911 else if ((c >= 'a') && (c <= 'z'))
912 return c;
913 else
914 return c + 0x10000;
915 }
916
917 static INTN str_verscmp(CHAR16 *s1, CHAR16 *s2) {
918 CHAR16 *os1 = s1;
919 CHAR16 *os2 = s2;
920
921 while (*s1 || *s2) {
922 INTN first;
923
924 while ((*s1 && !is_digit(*s1)) || (*s2 && !is_digit(*s2))) {
925 INTN order;
926
927 order = c_order(*s1) - c_order(*s2);
928 if (order != 0)
929 return order;
930 s1++;
931 s2++;
932 }
933
934 while (*s1 == '0')
935 s1++;
936 while (*s2 == '0')
937 s2++;
938
939 first = 0;
940 while (is_digit(*s1) && is_digit(*s2)) {
941 if (first == 0)
942 first = *s1 - *s2;
943 s1++;
944 s2++;
945 }
946
947 if (is_digit(*s1))
948 return 1;
949 if (is_digit(*s2))
950 return -1;
951
952 if (first != 0)
953 return first;
954 }
955
956 return StrCmp(os1, os2);
957 }
958
959 static CHAR8 *line_get_key_value(
960 CHAR8 *content,
961 CHAR8 *sep,
962 UINTN *pos,
963 CHAR8 **key_ret,
964 CHAR8 **value_ret) {
965
966 CHAR8 *line;
967 UINTN linelen;
968 CHAR8 *value;
969
970 skip:
971 line = content + *pos;
972 if (*line == '\0')
973 return NULL;
974
975 linelen = 0;
976 while (line[linelen] && !strchra((CHAR8 *)"\n\r", line[linelen]))
977 linelen++;
978
979 /* move pos to next line */
980 *pos += linelen;
981 if (content[*pos])
982 (*pos)++;
983
984 /* empty line */
985 if (linelen == 0)
986 goto skip;
987
988 /* terminate line */
989 line[linelen] = '\0';
990
991 /* remove leading whitespace */
992 while (strchra((CHAR8 *)" \t", *line)) {
993 line++;
994 linelen--;
995 }
996
997 /* remove trailing whitespace */
998 while (linelen > 0 && strchra((CHAR8 *)" \t", line[linelen-1]))
999 linelen--;
1000 line[linelen] = '\0';
1001
1002 if (*line == '#')
1003 goto skip;
1004
1005 /* split key/value */
1006 value = line;
1007 while (*value && !strchra(sep, *value))
1008 value++;
1009 if (*value == '\0')
1010 goto skip;
1011 *value = '\0';
1012 value++;
1013 while (*value && strchra(sep, *value))
1014 value++;
1015
1016 /* unquote */
1017 if (value[0] == '"' && line[linelen-1] == '"') {
1018 value++;
1019 line[linelen-1] = '\0';
1020 }
1021
1022 *key_ret = line;
1023 *value_ret = value;
1024 return line;
1025 }
1026
1027 static VOID config_defaults_load_from_file(Config *config, CHAR8 *content) {
1028 CHAR8 *line;
1029 UINTN pos = 0;
1030 CHAR8 *key, *value;
1031
1032 while ((line = line_get_key_value(content, (CHAR8 *)" \t", &pos, &key, &value))) {
1033 if (strcmpa((CHAR8 *)"timeout", key) == 0) {
1034 _cleanup_freepool_ CHAR16 *s = NULL;
1035
1036 s = stra_to_str(value);
1037 config->timeout_sec_config = Atoi(s);
1038 config->timeout_sec = config->timeout_sec_config;
1039 continue;
1040 }
1041
1042 if (strcmpa((CHAR8 *)"default", key) == 0) {
1043 FreePool(config->entry_default_pattern);
1044 config->entry_default_pattern = stra_to_str(value);
1045 StrLwr(config->entry_default_pattern);
1046 continue;
1047 }
1048
1049 if (strcmpa((CHAR8 *)"editor", key) == 0) {
1050 BOOLEAN on;
1051
1052 if (EFI_ERROR(parse_boolean(value, &on)))
1053 continue;
1054
1055 config->editor = on;
1056 continue;
1057 }
1058
1059 if (strcmpa((CHAR8 *)"auto-entries", key) == 0) {
1060 BOOLEAN on;
1061
1062 if (EFI_ERROR(parse_boolean(value, &on)))
1063 continue;
1064
1065 config->auto_entries = on;
1066 continue;
1067 }
1068
1069 if (strcmpa((CHAR8 *)"auto-firmware", key) == 0) {
1070 BOOLEAN on;
1071
1072 if (EFI_ERROR(parse_boolean(value, &on)))
1073 continue;
1074
1075 config->auto_firmware = on;
1076 continue;
1077 }
1078
1079 if (strcmpa((CHAR8 *)"console-mode", key) == 0) {
1080 if (strcmpa((CHAR8 *)"auto", value) == 0)
1081 config->console_mode_change = CONSOLE_MODE_AUTO;
1082 else if (strcmpa((CHAR8 *)"max", value) == 0)
1083 config->console_mode_change = CONSOLE_MODE_MAX;
1084 else if (strcmpa((CHAR8 *)"keep", value) == 0)
1085 config->console_mode_change = CONSOLE_MODE_KEEP;
1086 else {
1087 _cleanup_freepool_ CHAR16 *s = NULL;
1088
1089 s = stra_to_str(value);
1090 config->console_mode = Atoi(s);
1091 config->console_mode_change = CONSOLE_MODE_SET;
1092 }
1093
1094 continue;
1095 }
1096
1097 if (strcmpa((CHAR8*) "random-seed-mode", key) == 0) {
1098 if (strcmpa((CHAR8*) "off", value) == 0)
1099 config->random_seed_mode = RANDOM_SEED_OFF;
1100 else if (strcmpa((CHAR8*) "with-system-token", value) == 0)
1101 config->random_seed_mode = RANDOM_SEED_WITH_SYSTEM_TOKEN;
1102 else if (strcmpa((CHAR8*) "always", value) == 0)
1103 config->random_seed_mode = RANDOM_SEED_ALWAYS;
1104 else {
1105 BOOLEAN on;
1106
1107 if (EFI_ERROR(parse_boolean(value, &on)))
1108 continue;
1109
1110 config->random_seed_mode = on ? RANDOM_SEED_ALWAYS : RANDOM_SEED_OFF;
1111 }
1112 }
1113 }
1114 }
1115
1116 static VOID config_entry_parse_tries(
1117 ConfigEntry *entry,
1118 CHAR16 *path,
1119 CHAR16 *file,
1120 CHAR16 *suffix) {
1121
1122 UINTN left = (UINTN) -1, done = (UINTN) -1, factor = 1, i, next_left, next_done;
1123 _cleanup_freepool_ CHAR16 *prefix = NULL;
1124
1125 /*
1126 * Parses a suffix of two counters (one going down, one going up) in the form "+LEFT-DONE" from the end of the
1127 * filename (but before the .efi/.conf suffix), where the "-DONE" part is optional and may be left out (in
1128 * which case that counter as assumed to be zero, i.e. the missing part is synonymous to "-0").
1129 *
1130 * Names we grok, and the series they result in:
1131 *
1132 * foobar+3.efi → foobar+2-1.efi → foobar+1-2.efi → foobar+0-3.efi → STOP!
1133 * foobar+4-0.efi → foobar+3-1.efi → foobar+2-2.efi → foobar+1-3.efi → foobar+0-4.efi → STOP!
1134 */
1135
1136 i = StrLen(file);
1137
1138 /* Chop off any suffix such as ".conf" or ".efi" */
1139 if (suffix) {
1140 UINTN suffix_length;
1141
1142 suffix_length = StrLen(suffix);
1143 if (i < suffix_length)
1144 return;
1145
1146 i -= suffix_length;
1147 }
1148
1149 /* Go backwards through the string and parse everything we encounter */
1150 for (;;) {
1151 if (i == 0)
1152 return;
1153
1154 i--;
1155
1156 switch (file[i]) {
1157
1158 case '+':
1159 if (left == (UINTN) -1) /* didn't read at least one digit for 'left'? */
1160 return;
1161
1162 if (done == (UINTN) -1) /* no 'done' counter? If so, it's equivalent to 0 */
1163 done = 0;
1164
1165 goto good;
1166
1167 case '-':
1168 if (left == (UINTN) -1) /* didn't parse any digit yet? */
1169 return;
1170
1171 if (done != (UINTN) -1) /* already encountered a dash earlier? */
1172 return;
1173
1174 /* So we encountered a dash. This means this counter is of the form +LEFT-DONE. Let's assign
1175 * what we already parsed to 'done', and start fresh for the 'left' part. */
1176
1177 done = left;
1178 left = (UINTN) -1;
1179 factor = 1;
1180 break;
1181
1182 case '0'...'9': {
1183 UINTN new_factor;
1184
1185 if (left == (UINTN) -1)
1186 left = file[i] - '0';
1187 else {
1188 UINTN new_left, digit;
1189
1190 digit = file[i] - '0';
1191 if (digit > (UINTN) -1 / factor) /* overflow check */
1192 return;
1193
1194 new_left = left + digit * factor;
1195 if (new_left < left) /* overflow check */
1196 return;
1197
1198 if (new_left == (UINTN) -1) /* don't allow us to be confused */
1199 return;
1200 }
1201
1202 new_factor = factor * 10;
1203 if (new_factor < factor) /* overflow chck */
1204 return;
1205
1206 factor = new_factor;
1207 break;
1208 }
1209
1210 default:
1211 return;
1212 }
1213 }
1214
1215 good:
1216 entry->tries_left = left;
1217 entry->tries_done = done;
1218
1219 entry->path = StrDuplicate(path);
1220 entry->current_name = StrDuplicate(file);
1221
1222 next_left = left <= 0 ? 0 : left - 1;
1223 next_done = done >= (UINTN) -2 ? (UINTN) -2 : done + 1;
1224
1225 prefix = StrDuplicate(file);
1226 prefix[i] = 0;
1227
1228 entry->next_name = PoolPrint(L"%s+%u-%u%s", prefix, next_left, next_done, suffix ?: L"");
1229 }
1230
1231 static VOID config_entry_bump_counters(
1232 ConfigEntry *entry,
1233 EFI_FILE_HANDLE root_dir) {
1234
1235 _cleanup_freepool_ CHAR16* old_path = NULL, *new_path = NULL;
1236 _cleanup_(FileHandleClosep) EFI_FILE_HANDLE handle = NULL;
1237 static EFI_GUID EfiFileInfoGuid = EFI_FILE_INFO_ID;
1238 _cleanup_freepool_ EFI_FILE_INFO *file_info = NULL;
1239 UINTN file_info_size, a, b;
1240 EFI_STATUS r;
1241
1242 if (entry->tries_left == (UINTN) -1)
1243 return;
1244
1245 if (!entry->path || !entry->current_name || !entry->next_name)
1246 return;
1247
1248 old_path = PoolPrint(L"%s\\%s", entry->path, entry->current_name);
1249
1250 r = uefi_call_wrapper(root_dir->Open, 5, root_dir, &handle, old_path, EFI_FILE_MODE_READ|EFI_FILE_MODE_WRITE, 0ULL);
1251 if (EFI_ERROR(r))
1252 return;
1253
1254 a = StrLen(entry->current_name);
1255 b = StrLen(entry->next_name);
1256
1257 file_info_size = OFFSETOF(EFI_FILE_INFO, FileName) + (a > b ? a : b) + 1;
1258
1259 for (;;) {
1260 file_info = AllocatePool(file_info_size);
1261
1262 r = uefi_call_wrapper(handle->GetInfo, 4, handle, &EfiFileInfoGuid, &file_info_size, file_info);
1263 if (!EFI_ERROR(r))
1264 break;
1265
1266 if (r != EFI_BUFFER_TOO_SMALL || file_info_size * 2 < file_info_size) {
1267 Print(L"\nFailed to get file info for '%s': %r\n", old_path, r);
1268 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1269 return;
1270 }
1271
1272 file_info_size *= 2;
1273 FreePool(file_info);
1274 }
1275
1276 /* And rename the file */
1277 StrCpy(file_info->FileName, entry->next_name);
1278 r = uefi_call_wrapper(handle->SetInfo, 4, handle, &EfiFileInfoGuid, file_info_size, file_info);
1279 if (EFI_ERROR(r)) {
1280 Print(L"\nFailed to rename '%s' to '%s', ignoring: %r\n", old_path, entry->next_name, r);
1281 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1282 return;
1283 }
1284
1285 /* Flush everything to disk, just in case… */
1286 (void) uefi_call_wrapper(handle->Flush, 1, handle);
1287
1288 /* Let's tell the OS that we renamed this file, so that it knows what to rename to the counter-less name on
1289 * success */
1290 new_path = PoolPrint(L"%s\\%s", entry->path, entry->next_name);
1291 efivar_set(L"LoaderBootCountPath", new_path, FALSE);
1292
1293 /* If the file we just renamed is the loader path, then let's update that. */
1294 if (StrCmp(entry->loader, old_path) == 0) {
1295 FreePool(entry->loader);
1296 entry->loader = TAKE_PTR(new_path);
1297 }
1298 }
1299
1300 static VOID config_entry_add_from_file(
1301 Config *config,
1302 EFI_HANDLE *device,
1303 EFI_FILE *root_dir,
1304 CHAR16 *path,
1305 CHAR16 *file,
1306 CHAR8 *content,
1307 CHAR16 *loaded_image_path) {
1308
1309 ConfigEntry *entry;
1310 CHAR8 *line;
1311 UINTN pos = 0;
1312 CHAR8 *key, *value;
1313 UINTN len;
1314 EFI_STATUS err;
1315 EFI_FILE_HANDLE handle;
1316 _cleanup_freepool_ CHAR16 *initrd = NULL;
1317
1318 entry = AllocatePool(sizeof(ConfigEntry));
1319
1320 *entry = (ConfigEntry) {
1321 .tries_done = (UINTN) -1,
1322 .tries_left = (UINTN) -1,
1323 };
1324
1325 while ((line = line_get_key_value(content, (CHAR8 *)" \t", &pos, &key, &value))) {
1326 if (strcmpa((CHAR8 *)"title", key) == 0) {
1327 FreePool(entry->title);
1328 entry->title = stra_to_str(value);
1329 continue;
1330 }
1331
1332 if (strcmpa((CHAR8 *)"version", key) == 0) {
1333 FreePool(entry->version);
1334 entry->version = stra_to_str(value);
1335 continue;
1336 }
1337
1338 if (strcmpa((CHAR8 *)"machine-id", key) == 0) {
1339 FreePool(entry->machine_id);
1340 entry->machine_id = stra_to_str(value);
1341 continue;
1342 }
1343
1344 if (strcmpa((CHAR8 *)"linux", key) == 0) {
1345 FreePool(entry->loader);
1346 entry->type = LOADER_LINUX;
1347 entry->loader = stra_to_path(value);
1348 entry->key = 'l';
1349 continue;
1350 }
1351
1352 if (strcmpa((CHAR8 *)"efi", key) == 0) {
1353 entry->type = LOADER_EFI;
1354 FreePool(entry->loader);
1355 entry->loader = stra_to_path(value);
1356
1357 /* do not add an entry for ourselves */
1358 if (loaded_image_path && StriCmp(entry->loader, loaded_image_path) == 0) {
1359 entry->type = LOADER_UNDEFINED;
1360 break;
1361 }
1362 continue;
1363 }
1364
1365 if (strcmpa((CHAR8 *)"architecture", key) == 0) {
1366 /* do not add an entry for an EFI image of architecture not matching with that of the image */
1367 if (strcmpa((CHAR8 *)EFI_MACHINE_TYPE_NAME, value) != 0) {
1368 entry->type = LOADER_UNDEFINED;
1369 break;
1370 }
1371 continue;
1372 }
1373
1374 if (strcmpa((CHAR8 *)"initrd", key) == 0) {
1375 _cleanup_freepool_ CHAR16 *new = NULL;
1376
1377 new = stra_to_path(value);
1378 if (initrd) {
1379 CHAR16 *s;
1380
1381 s = PoolPrint(L"%s initrd=%s", initrd, new);
1382 FreePool(initrd);
1383 initrd = s;
1384 } else
1385 initrd = PoolPrint(L"initrd=%s", new);
1386
1387 continue;
1388 }
1389
1390 if (strcmpa((CHAR8 *)"options", key) == 0) {
1391 _cleanup_freepool_ CHAR16 *new = NULL;
1392
1393 new = stra_to_str(value);
1394 if (entry->options) {
1395 CHAR16 *s;
1396
1397 s = PoolPrint(L"%s %s", entry->options, new);
1398 FreePool(entry->options);
1399 entry->options = s;
1400 } else
1401 entry->options = TAKE_PTR(new);
1402
1403 continue;
1404 }
1405 }
1406
1407 if (entry->type == LOADER_UNDEFINED) {
1408 config_entry_free(entry);
1409 return;
1410 }
1411
1412 /* check existence */
1413 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &handle, entry->loader, EFI_FILE_MODE_READ, 0ULL);
1414 if (EFI_ERROR(err)) {
1415 config_entry_free(entry);
1416 return;
1417 }
1418 uefi_call_wrapper(handle->Close, 1, handle);
1419
1420 /* add initrd= to options */
1421 if (entry->type == LOADER_LINUX && initrd) {
1422 if (entry->options) {
1423 CHAR16 *s;
1424
1425 s = PoolPrint(L"%s %s", initrd, entry->options);
1426 FreePool(entry->options);
1427 entry->options = s;
1428 } else
1429 entry->options = TAKE_PTR(initrd);
1430 }
1431
1432 entry->device = device;
1433 entry->id = StrDuplicate(file);
1434 len = StrLen(entry->id);
1435 /* remove ".conf" */
1436 if (len > 5)
1437 entry->id[len - 5] = '\0';
1438 StrLwr(entry->id);
1439
1440 config_add_entry(config, entry);
1441
1442 config_entry_parse_tries(entry, path, file, L".conf");
1443 }
1444
1445 static VOID config_load_defaults(Config *config, EFI_FILE *root_dir) {
1446 _cleanup_freepool_ CHAR8 *content = NULL;
1447 UINTN sec;
1448 EFI_STATUS err;
1449
1450 *config = (Config) {
1451 .editor = TRUE,
1452 .auto_entries = TRUE,
1453 .auto_firmware = TRUE,
1454 .random_seed_mode = RANDOM_SEED_WITH_SYSTEM_TOKEN,
1455 };
1456
1457 err = file_read(root_dir, L"\\loader\\loader.conf", 0, 0, &content, NULL);
1458 if (!EFI_ERROR(err))
1459 config_defaults_load_from_file(config, content);
1460
1461 err = efivar_get_int(L"LoaderConfigTimeout", &sec);
1462 if (!EFI_ERROR(err)) {
1463 config->timeout_sec_efivar = sec > INTN_MAX ? INTN_MAX : sec;
1464 config->timeout_sec = sec;
1465 } else
1466 config->timeout_sec_efivar = -1;
1467
1468 err = efivar_get_int(L"LoaderConfigTimeoutOneShot", &sec);
1469 if (!EFI_ERROR(err)) {
1470 /* Unset variable now, after all it's "one shot". */
1471 (void) efivar_set(L"LoaderConfigTimeoutOneShot", NULL, TRUE);
1472
1473 config->timeout_sec = sec;
1474 config->force_menu = TRUE; /* force the menu when this is set */
1475 }
1476 }
1477
1478 static VOID config_load_entries(
1479 Config *config,
1480 EFI_HANDLE *device,
1481 EFI_FILE *root_dir,
1482 CHAR16 *loaded_image_path) {
1483
1484 EFI_FILE_HANDLE entries_dir;
1485 EFI_STATUS err;
1486
1487 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &entries_dir, L"\\loader\\entries", EFI_FILE_MODE_READ, 0ULL);
1488 if (!EFI_ERROR(err)) {
1489 for (;;) {
1490 CHAR16 buf[256];
1491 UINTN bufsize;
1492 EFI_FILE_INFO *f;
1493 _cleanup_freepool_ CHAR8 *content = NULL;
1494 UINTN len;
1495
1496 bufsize = sizeof(buf);
1497 err = uefi_call_wrapper(entries_dir->Read, 3, entries_dir, &bufsize, buf);
1498 if (bufsize == 0 || EFI_ERROR(err))
1499 break;
1500
1501 f = (EFI_FILE_INFO *) buf;
1502 if (f->FileName[0] == '.')
1503 continue;
1504 if (f->Attribute & EFI_FILE_DIRECTORY)
1505 continue;
1506
1507 len = StrLen(f->FileName);
1508 if (len < 6)
1509 continue;
1510 if (StriCmp(f->FileName + len - 5, L".conf") != 0)
1511 continue;
1512 if (StrnCmp(f->FileName, L"auto-", 5) == 0)
1513 continue;
1514
1515 err = file_read(entries_dir, f->FileName, 0, 0, &content, NULL);
1516 if (!EFI_ERROR(err))
1517 config_entry_add_from_file(config, device, root_dir, L"\\loader\\entries", f->FileName, content, loaded_image_path);
1518 }
1519 uefi_call_wrapper(entries_dir->Close, 1, entries_dir);
1520 }
1521 }
1522
1523 static INTN config_entry_compare(ConfigEntry *a, ConfigEntry *b) {
1524 INTN r;
1525
1526 /* Order entries that have no tries left to the end of the list */
1527 if (a->tries_left != 0 && b->tries_left == 0)
1528 return -1;
1529 if (a->tries_left == 0 && b->tries_left != 0)
1530 return 1;
1531
1532 r = str_verscmp(a->id, b->id);
1533 if (r != 0)
1534 return r;
1535
1536 if (a->tries_left == (UINTN) -1 ||
1537 b->tries_left == (UINTN) -1)
1538 return 0;
1539
1540 /* If both items have boot counting, and otherwise are identical, put the entry with more tries left first */
1541 if (a->tries_left > b->tries_left)
1542 return -1;
1543 if (a->tries_left < b->tries_left)
1544 return 1;
1545
1546 /* If they have the same number of tries left, then let the one win which was tried fewer times so far */
1547 if (a->tries_done < b->tries_done)
1548 return -1;
1549 if (a->tries_done > b->tries_done)
1550 return 1;
1551
1552 return 0;
1553 }
1554
1555 static VOID config_sort_entries(Config *config) {
1556 UINTN i;
1557
1558 for (i = 1; i < config->entry_count; i++) {
1559 BOOLEAN more;
1560 UINTN k;
1561
1562 more = FALSE;
1563 for (k = 0; k < config->entry_count - i; k++) {
1564 ConfigEntry *entry;
1565
1566 if (config_entry_compare(config->entries[k], config->entries[k+1]) <= 0)
1567 continue;
1568
1569 entry = config->entries[k];
1570 config->entries[k] = config->entries[k+1];
1571 config->entries[k+1] = entry;
1572 more = TRUE;
1573 }
1574 if (!more)
1575 break;
1576 }
1577 }
1578
1579 static INTN config_entry_find(Config *config, CHAR16 *id) {
1580 UINTN i;
1581
1582 for (i = 0; i < config->entry_count; i++)
1583 if (StrCmp(config->entries[i]->id, id) == 0)
1584 return (INTN) i;
1585
1586 return -1;
1587 }
1588
1589 static VOID config_default_entry_select(Config *config) {
1590 _cleanup_freepool_ CHAR16 *entry_oneshot = NULL, *entry_default = NULL;
1591 EFI_STATUS err;
1592 INTN i;
1593
1594 /*
1595 * The EFI variable to specify a boot entry for the next, and only the
1596 * next reboot. The variable is always cleared directly after it is read.
1597 */
1598 err = efivar_get(L"LoaderEntryOneShot", &entry_oneshot);
1599 if (!EFI_ERROR(err)) {
1600
1601 config->entry_oneshot = StrDuplicate(entry_oneshot);
1602 efivar_set(L"LoaderEntryOneShot", NULL, TRUE);
1603
1604 i = config_entry_find(config, entry_oneshot);
1605 if (i >= 0) {
1606 config->idx_default = i;
1607 return;
1608 }
1609 }
1610
1611 /*
1612 * The EFI variable to select the default boot entry overrides the
1613 * configured pattern. The variable can be set and cleared by pressing
1614 * the 'd' key in the loader selection menu, the entry is marked with
1615 * an '*'.
1616 */
1617 err = efivar_get(L"LoaderEntryDefault", &entry_default);
1618 if (!EFI_ERROR(err)) {
1619
1620 i = config_entry_find(config, entry_default);
1621 if (i >= 0) {
1622 config->idx_default = i;
1623 config->idx_default_efivar = i;
1624 return;
1625 }
1626 }
1627 config->idx_default_efivar = -1;
1628
1629 if (config->entry_count == 0)
1630 return;
1631
1632 /*
1633 * Match the pattern from the end of the list to the start, find last
1634 * entry (largest number) matching the given pattern.
1635 */
1636 if (config->entry_default_pattern) {
1637 i = config->entry_count;
1638 while (i--) {
1639 if (config->entries[i]->no_autoselect)
1640 continue;
1641 if (MetaiMatch(config->entries[i]->id, config->entry_default_pattern)) {
1642 config->idx_default = i;
1643 return;
1644 }
1645 }
1646 }
1647
1648 /* select the last suitable entry */
1649 i = config->entry_count;
1650 while (i--) {
1651 if (config->entries[i]->no_autoselect)
1652 continue;
1653 config->idx_default = i;
1654 return;
1655 }
1656
1657 /* no entry found */
1658 config->idx_default = -1;
1659 }
1660
1661 static BOOLEAN find_nonunique(ConfigEntry **entries, UINTN entry_count) {
1662 BOOLEAN non_unique = FALSE;
1663 UINTN i, k;
1664
1665 for (i = 0; i < entry_count; i++)
1666 entries[i]->non_unique = FALSE;
1667
1668 for (i = 0; i < entry_count; i++)
1669 for (k = 0; k < entry_count; k++) {
1670 if (i == k)
1671 continue;
1672 if (StrCmp(entries[i]->title_show, entries[k]->title_show) != 0)
1673 continue;
1674
1675 non_unique = entries[i]->non_unique = entries[k]->non_unique = TRUE;
1676 }
1677
1678 return non_unique;
1679 }
1680
1681 /* generate a unique title, avoiding non-distinguishable menu entries */
1682 static VOID config_title_generate(Config *config) {
1683 UINTN i;
1684
1685 /* set title */
1686 for (i = 0; i < config->entry_count; i++) {
1687 CHAR16 *title;
1688
1689 FreePool(config->entries[i]->title_show);
1690 title = config->entries[i]->title;
1691 if (!title)
1692 title = config->entries[i]->id;
1693 config->entries[i]->title_show = StrDuplicate(title);
1694 }
1695
1696 if (!find_nonunique(config->entries, config->entry_count))
1697 return;
1698
1699 /* add version to non-unique titles */
1700 for (i = 0; i < config->entry_count; i++) {
1701 CHAR16 *s;
1702
1703 if (!config->entries[i]->non_unique)
1704 continue;
1705 if (!config->entries[i]->version)
1706 continue;
1707
1708 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, config->entries[i]->version);
1709 FreePool(config->entries[i]->title_show);
1710 config->entries[i]->title_show = s;
1711 }
1712
1713 if (!find_nonunique(config->entries, config->entry_count))
1714 return;
1715
1716 /* add machine-id to non-unique titles */
1717 for (i = 0; i < config->entry_count; i++) {
1718 CHAR16 *s;
1719 _cleanup_freepool_ CHAR16 *m = NULL;
1720
1721 if (!config->entries[i]->non_unique)
1722 continue;
1723 if (!config->entries[i]->machine_id)
1724 continue;
1725
1726 m = StrDuplicate(config->entries[i]->machine_id);
1727 m[8] = '\0';
1728 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, m);
1729 FreePool(config->entries[i]->title_show);
1730 config->entries[i]->title_show = s;
1731 }
1732
1733 if (!find_nonunique(config->entries, config->entry_count))
1734 return;
1735
1736 /* add file name to non-unique titles */
1737 for (i = 0; i < config->entry_count; i++) {
1738 CHAR16 *s;
1739
1740 if (!config->entries[i]->non_unique)
1741 continue;
1742 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, config->entries[i]->id);
1743 FreePool(config->entries[i]->title_show);
1744 config->entries[i]->title_show = s;
1745 config->entries[i]->non_unique = FALSE;
1746 }
1747 }
1748
1749 static BOOLEAN config_entry_add_call(
1750 Config *config,
1751 CHAR16 *id,
1752 CHAR16 *title,
1753 EFI_STATUS (*call)(VOID)) {
1754
1755 ConfigEntry *entry;
1756
1757 entry = AllocatePool(sizeof(ConfigEntry));
1758 *entry = (ConfigEntry) {
1759 .id = StrDuplicate(id),
1760 .title = StrDuplicate(title),
1761 .call = call,
1762 .no_autoselect = TRUE,
1763 .tries_done = (UINTN) -1,
1764 .tries_left = (UINTN) -1,
1765 };
1766
1767 config_add_entry(config, entry);
1768 return TRUE;
1769 }
1770
1771 static ConfigEntry *config_entry_add_loader(
1772 Config *config,
1773 EFI_HANDLE *device,
1774 enum loader_type type,
1775 CHAR16 *id,
1776 CHAR16 key,
1777 CHAR16 *title,
1778 CHAR16 *loader) {
1779
1780 ConfigEntry *entry;
1781
1782 entry = AllocatePool(sizeof(ConfigEntry));
1783 *entry = (ConfigEntry) {
1784 .type = type,
1785 .title = StrDuplicate(title),
1786 .device = device,
1787 .loader = StrDuplicate(loader),
1788 .id = StrDuplicate(id),
1789 .key = key,
1790 .tries_done = (UINTN) -1,
1791 .tries_left = (UINTN) -1,
1792 };
1793
1794 StrLwr(entry->id);
1795
1796 config_add_entry(config, entry);
1797 return entry;
1798 }
1799
1800 static BOOLEAN config_entry_add_loader_auto(
1801 Config *config,
1802 EFI_HANDLE *device,
1803 EFI_FILE *root_dir,
1804 CHAR16 *loaded_image_path,
1805 CHAR16 *id,
1806 CHAR16 key,
1807 CHAR16 *title,
1808 CHAR16 *loader) {
1809
1810 EFI_FILE_HANDLE handle;
1811 ConfigEntry *entry;
1812 EFI_STATUS err;
1813
1814 if (!config->auto_entries)
1815 return FALSE;
1816
1817 /* do not add an entry for ourselves */
1818 if (loaded_image_path) {
1819 UINTN len;
1820 _cleanup_freepool_ CHAR8 *content = NULL;
1821
1822 if (StriCmp(loader, loaded_image_path) == 0)
1823 return FALSE;
1824
1825 /* look for systemd-boot magic string */
1826 err = file_read(root_dir, loader, 0, 100*1024, &content, &len);
1827 if (!EFI_ERROR(err)) {
1828 CHAR8 *start = content;
1829 CHAR8 *last = content + len - sizeof(magic) - 1;
1830
1831 for (; start <= last; start++)
1832 if (start[0] == magic[0] && CompareMem(start, magic, sizeof(magic) - 1) == 0)
1833 return FALSE;
1834 }
1835 }
1836
1837 /* check existence */
1838 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &handle, loader, EFI_FILE_MODE_READ, 0ULL);
1839 if (EFI_ERROR(err))
1840 return FALSE;
1841 uefi_call_wrapper(handle->Close, 1, handle);
1842
1843 entry = config_entry_add_loader(config, device, LOADER_UNDEFINED, id, key, title, loader);
1844 if (!entry)
1845 return FALSE;
1846
1847 /* do not boot right away into auto-detected entries */
1848 entry->no_autoselect = TRUE;
1849
1850 return TRUE;
1851 }
1852
1853 static VOID config_entry_add_osx(Config *config) {
1854 EFI_STATUS err;
1855 UINTN handle_count = 0;
1856 _cleanup_freepool_ EFI_HANDLE *handles = NULL;
1857
1858 if (!config->auto_entries)
1859 return;
1860
1861 err = LibLocateHandle(ByProtocol, &FileSystemProtocol, NULL, &handle_count, &handles);
1862 if (!EFI_ERROR(err)) {
1863 UINTN i;
1864
1865 for (i = 0; i < handle_count; i++) {
1866 EFI_FILE *root;
1867 BOOLEAN found;
1868
1869 root = LibOpenRoot(handles[i]);
1870 if (!root)
1871 continue;
1872 found = config_entry_add_loader_auto(config, handles[i], root, NULL, L"auto-osx", 'a', L"macOS",
1873 L"\\System\\Library\\CoreServices\\boot.efi");
1874 uefi_call_wrapper(root->Close, 1, root);
1875 if (found)
1876 break;
1877 }
1878 }
1879 }
1880
1881 static VOID config_entry_add_linux(
1882 Config *config,
1883 EFI_HANDLE *device,
1884 EFI_FILE *root_dir) {
1885
1886 EFI_FILE_HANDLE linux_dir;
1887 EFI_STATUS err;
1888 ConfigEntry *entry;
1889
1890 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &linux_dir, L"\\EFI\\Linux", EFI_FILE_MODE_READ, 0ULL);
1891 if (EFI_ERROR(err))
1892 return;
1893
1894 for (;;) {
1895 CHAR16 buf[256];
1896 UINTN bufsize = sizeof buf;
1897 EFI_FILE_INFO *f;
1898 CHAR8 *sections[] = {
1899 (UINT8 *)".osrel",
1900 (UINT8 *)".cmdline",
1901 NULL
1902 };
1903 UINTN offs[ELEMENTSOF(sections)-1] = {};
1904 UINTN szs[ELEMENTSOF(sections)-1] = {};
1905 UINTN addrs[ELEMENTSOF(sections)-1] = {};
1906 CHAR8 *content = NULL;
1907 UINTN len;
1908 CHAR8 *line;
1909 UINTN pos = 0;
1910 CHAR8 *key, *value;
1911 CHAR16 *os_name = NULL;
1912 CHAR16 *os_id = NULL;
1913 CHAR16 *os_version = NULL;
1914 CHAR16 *os_build = NULL;
1915
1916 err = uefi_call_wrapper(linux_dir->Read, 3, linux_dir, &bufsize, buf);
1917 if (bufsize == 0 || EFI_ERROR(err))
1918 break;
1919
1920 f = (EFI_FILE_INFO *) buf;
1921 if (f->FileName[0] == '.')
1922 continue;
1923 if (f->Attribute & EFI_FILE_DIRECTORY)
1924 continue;
1925 len = StrLen(f->FileName);
1926 if (len < 5)
1927 continue;
1928 if (StriCmp(f->FileName + len - 4, L".efi") != 0)
1929 continue;
1930
1931 /* look for .osrel and .cmdline sections in the .efi binary */
1932 err = pe_file_locate_sections(linux_dir, f->FileName, sections, addrs, offs, szs);
1933 if (EFI_ERROR(err))
1934 continue;
1935
1936 err = file_read(linux_dir, f->FileName, offs[0], szs[0], &content, NULL);
1937 if (EFI_ERROR(err))
1938 continue;
1939
1940 /* read properties from the embedded os-release file */
1941 while ((line = line_get_key_value(content, (CHAR8 *)"=", &pos, &key, &value))) {
1942 if (strcmpa((CHAR8 *)"PRETTY_NAME", key) == 0) {
1943 FreePool(os_name);
1944 os_name = stra_to_str(value);
1945 continue;
1946 }
1947
1948 if (strcmpa((CHAR8 *)"ID", key) == 0) {
1949 FreePool(os_id);
1950 os_id = stra_to_str(value);
1951 continue;
1952 }
1953
1954 if (strcmpa((CHAR8 *)"VERSION_ID", key) == 0) {
1955 FreePool(os_version);
1956 os_version = stra_to_str(value);
1957 continue;
1958 }
1959
1960 if (strcmpa((CHAR8 *)"BUILD_ID", key) == 0) {
1961 FreePool(os_build);
1962 os_build = stra_to_str(value);
1963 continue;
1964 }
1965 }
1966
1967 if (os_name && os_id && (os_version || os_build)) {
1968 _cleanup_freepool_ CHAR16 *conf = NULL, *path = NULL;
1969
1970 conf = PoolPrint(L"%s-%s", os_id, os_version ? : os_build);
1971 path = PoolPrint(L"\\EFI\\Linux\\%s", f->FileName);
1972
1973 entry = config_entry_add_loader(config, device, LOADER_LINUX, conf, 'l', os_name, path);
1974
1975 FreePool(content);
1976 content = NULL;
1977
1978 /* read the embedded cmdline file */
1979 err = file_read(linux_dir, f->FileName, offs[1], szs[1], &content, NULL);
1980 if (!EFI_ERROR(err)) {
1981
1982 /* chomp the newline */
1983 if (content[szs[1]-1] == '\n')
1984 content[szs[1]-1] = '\0';
1985
1986 entry->options = stra_to_str(content);
1987 }
1988
1989 config_entry_parse_tries(entry, L"\\EFI\\Linux", f->FileName, L".efi");
1990 }
1991
1992 FreePool(os_name);
1993 FreePool(os_id);
1994 FreePool(os_version);
1995 FreePool(os_build);
1996 FreePool(content);
1997 }
1998
1999 uefi_call_wrapper(linux_dir->Close, 1, linux_dir);
2000 }
2001
2002 /* Note that this is in GUID format, i.e. the first 32bit, and the following pair of 16bit are byteswapped. */
2003 static const UINT8 xbootldr_guid[16] = {
2004 0xff, 0xc2, 0x13, 0xbc, 0xe6, 0x59, 0x62, 0x42, 0xa3, 0x52, 0xb2, 0x75, 0xfd, 0x6f, 0x71, 0x72
2005 };
2006
2007 EFI_DEVICE_PATH *path_parent(EFI_DEVICE_PATH *path, EFI_DEVICE_PATH *node) {
2008 EFI_DEVICE_PATH *parent;
2009 UINTN len;
2010
2011 len = (UINT8*) NextDevicePathNode(node) - (UINT8*) path;
2012 parent = (EFI_DEVICE_PATH*) AllocatePool(len + sizeof(EFI_DEVICE_PATH));
2013 CopyMem(parent, path, len);
2014 CopyMem((UINT8*) parent + len, EndDevicePath, sizeof(EFI_DEVICE_PATH));
2015
2016 return parent;
2017 }
2018
2019 static VOID config_load_xbootldr(
2020 Config *config,
2021 EFI_HANDLE *device) {
2022
2023 EFI_DEVICE_PATH *partition_path, *node, *disk_path, *copy;
2024 UINT32 found_partition_number = (UINT32) -1;
2025 UINT64 found_partition_start = (UINT64) -1;
2026 UINT64 found_partition_size = (UINT64) -1;
2027 UINT8 found_partition_signature[16] = {};
2028 EFI_HANDLE new_device;
2029 EFI_FILE *root_dir;
2030 EFI_STATUS r;
2031
2032 partition_path = DevicePathFromHandle(device);
2033 if (!partition_path)
2034 return;
2035
2036 for (node = partition_path; !IsDevicePathEnd(node); node = NextDevicePathNode(node)) {
2037 EFI_HANDLE disk_handle;
2038 EFI_BLOCK_IO *block_io;
2039 EFI_DEVICE_PATH *p;
2040 UINTN nr;
2041
2042 /* First, Let's look for the SCSI/SATA/USB/… device path node, i.e. one above the media
2043 * devices */
2044 if (DevicePathType(node) != MESSAGING_DEVICE_PATH)
2045 continue;
2046
2047 /* Determine the device path one level up */
2048 disk_path = path_parent(partition_path, node);
2049 p = disk_path;
2050 r = uefi_call_wrapper(BS->LocateDevicePath, 3, &BlockIoProtocol, &p, &disk_handle);
2051 if (EFI_ERROR(r))
2052 continue;
2053
2054 r = uefi_call_wrapper(BS->HandleProtocol, 3, disk_handle, &BlockIoProtocol, (VOID **)&block_io);
2055 if (EFI_ERROR(r))
2056 continue;
2057
2058 /* Filter out some block devices early. (We only care about block devices that aren't
2059 * partitions themselves — we look for GPT partition tables to parse after all —, and only
2060 * those which contain a medium and have at least 2 blocks.) */
2061 if (block_io->Media->LogicalPartition ||
2062 !block_io->Media->MediaPresent ||
2063 block_io->Media->LastBlock <= 1)
2064 continue;
2065
2066 /* Try both copies of the GPT header, in case one is corrupted */
2067 for (nr = 0; nr < 2; nr++) {
2068 _cleanup_freepool_ EFI_PARTITION_ENTRY* entries = NULL;
2069 union {
2070 EFI_PARTITION_TABLE_HEADER gpt_header;
2071 uint8_t space[((sizeof(EFI_PARTITION_TABLE_HEADER) + 511) / 512) * 512];
2072 } gpt_header_buffer;
2073 const EFI_PARTITION_TABLE_HEADER *h = &gpt_header_buffer.gpt_header;
2074 UINT64 where;
2075 UINTN i, sz;
2076 UINT32 c;
2077
2078 if (nr == 0)
2079 /* Read the first copy at LBA 1 */
2080 where = 1;
2081 else
2082 /* Read the second copy at the very last LBA of this block device */
2083 where = block_io->Media->LastBlock;
2084
2085 /* Read the GPT header */
2086 r = uefi_call_wrapper(block_io->ReadBlocks, 5,
2087 block_io,
2088 block_io->Media->MediaId,
2089 where,
2090 sizeof(gpt_header_buffer), &gpt_header_buffer);
2091 if (EFI_ERROR(r))
2092 continue;
2093
2094 /* Some superficial validation of the GPT header */
2095 c = CompareMem(&h->Header.Signature, "EFI PART", sizeof(h->Header.Signature));
2096 if (c != 0)
2097 continue;
2098
2099 if (h->Header.HeaderSize < 92 ||
2100 h->Header.HeaderSize > 512)
2101 continue;
2102
2103 if (h->Header.Revision != 0x00010000U)
2104 continue;
2105
2106 /* Calculate CRC check */
2107 c = ~crc32_exclude_offset((UINT32) -1,
2108 (const UINT8*) &gpt_header_buffer,
2109 h->Header.HeaderSize,
2110 OFFSETOF(EFI_PARTITION_TABLE_HEADER, Header.CRC32),
2111 sizeof(h->Header.CRC32));
2112 if (c != h->Header.CRC32)
2113 continue;
2114
2115 if (h->MyLBA != where)
2116 continue;
2117
2118 if (h->SizeOfPartitionEntry < sizeof(EFI_PARTITION_ENTRY))
2119 continue;
2120
2121 if (h->NumberOfPartitionEntries <= 0 ||
2122 h->NumberOfPartitionEntries > 1024)
2123 continue;
2124
2125 if (h->SizeOfPartitionEntry > UINTN_MAX / h->NumberOfPartitionEntries) /* overflow check */
2126 continue;
2127
2128 /* Now load the GPT entry table */
2129 sz = ALIGN_TO((UINTN) h->SizeOfPartitionEntry * (UINTN) h->NumberOfPartitionEntries, 512);
2130 entries = AllocatePool(sz);
2131
2132 r = uefi_call_wrapper(block_io->ReadBlocks, 5,
2133 block_io,
2134 block_io->Media->MediaId,
2135 h->PartitionEntryLBA,
2136 sz, entries);
2137 if (EFI_ERROR(r))
2138 continue;
2139
2140 /* Calculate CRC of entries array, too */
2141 c = ~crc32((UINT32) -1, entries, sz);
2142 if (c != h->PartitionEntryArrayCRC32)
2143 continue;
2144
2145 for (i = 0; i < h->NumberOfPartitionEntries; i++) {
2146 EFI_PARTITION_ENTRY *entry;
2147
2148 entry = (EFI_PARTITION_ENTRY*) ((UINT8*) entries + h->SizeOfPartitionEntry * i);
2149
2150 if (CompareMem(&entry->PartitionTypeGUID, xbootldr_guid, 16) == 0) {
2151 UINT64 end;
2152
2153 /* Let's use memcpy(), in case the structs are not aligned (they really should be though) */
2154 CopyMem(&found_partition_start, &entry->StartingLBA, sizeof(found_partition_start));
2155 CopyMem(&end, &entry->EndingLBA, sizeof(end));
2156
2157 if (end < found_partition_start) /* Bogus? */
2158 continue;
2159
2160 found_partition_size = end - found_partition_start + 1;
2161 CopyMem(found_partition_signature, &entry->UniquePartitionGUID, sizeof(found_partition_signature));
2162
2163 found_partition_number = i + 1;
2164 goto found;
2165 }
2166 }
2167
2168 break; /* This GPT was fully valid, but we didn't find what we are looking for. This
2169 * means there's no reason to check the second copy of the GPT header */
2170 }
2171 }
2172
2173 return; /* Not found */
2174
2175 found:
2176 copy = DuplicateDevicePath(partition_path);
2177
2178 /* Patch in the data we found */
2179 for (node = copy; !IsDevicePathEnd(node); node = NextDevicePathNode(node)) {
2180 HARDDRIVE_DEVICE_PATH *hd;
2181
2182 if (DevicePathType(node) != MEDIA_DEVICE_PATH)
2183 continue;
2184
2185 if (DevicePathSubType(node) != MEDIA_HARDDRIVE_DP)
2186 continue;
2187
2188 hd = (HARDDRIVE_DEVICE_PATH*) node;
2189 hd->PartitionNumber = found_partition_number;
2190 hd->PartitionStart = found_partition_start;
2191 hd->PartitionSize = found_partition_size;
2192 CopyMem(hd->Signature, found_partition_signature, sizeof(hd->Signature));
2193 hd->MBRType = MBR_TYPE_EFI_PARTITION_TABLE_HEADER;
2194 hd->SignatureType = SIGNATURE_TYPE_GUID;
2195 }
2196
2197 r = uefi_call_wrapper(BS->LocateDevicePath, 3, &BlockIoProtocol, &copy, &new_device);
2198 if (EFI_ERROR(r))
2199 return;
2200
2201 root_dir = LibOpenRoot(new_device);
2202 if (!root_dir)
2203 return;
2204
2205 config_entry_add_linux(config, new_device, root_dir);
2206 config_load_entries(config, new_device, root_dir, NULL);
2207 }
2208
2209 static EFI_STATUS image_start(
2210 EFI_HANDLE parent_image,
2211 const Config *config,
2212 const ConfigEntry *entry) {
2213
2214 EFI_HANDLE image;
2215 _cleanup_freepool_ EFI_DEVICE_PATH *path = NULL;
2216 CHAR16 *options;
2217 EFI_STATUS err;
2218
2219 path = FileDevicePath(entry->device, entry->loader);
2220 if (!path) {
2221 Print(L"Error getting device path.");
2222 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2223 return EFI_INVALID_PARAMETER;
2224 }
2225
2226 err = uefi_call_wrapper(BS->LoadImage, 6, FALSE, parent_image, path, NULL, 0, &image);
2227 if (EFI_ERROR(err)) {
2228 Print(L"Error loading %s: %r", entry->loader, err);
2229 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2230 return err;
2231 }
2232
2233 if (config->options_edit)
2234 options = config->options_edit;
2235 else if (entry->options)
2236 options = entry->options;
2237 else
2238 options = NULL;
2239 if (options) {
2240 EFI_LOADED_IMAGE *loaded_image;
2241
2242 err = uefi_call_wrapper(BS->OpenProtocol, 6, image, &LoadedImageProtocol, (VOID **)&loaded_image,
2243 parent_image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
2244 if (EFI_ERROR(err)) {
2245 Print(L"Error getting LoadedImageProtocol handle: %r", err);
2246 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2247 goto out_unload;
2248 }
2249 loaded_image->LoadOptions = options;
2250 loaded_image->LoadOptionsSize = (StrLen(loaded_image->LoadOptions)+1) * sizeof(CHAR16);
2251
2252 #if ENABLE_TPM
2253 /* Try to log any options to the TPM, especially to catch manually edited options */
2254 err = tpm_log_event(SD_TPM_PCR,
2255 (EFI_PHYSICAL_ADDRESS) (UINTN) loaded_image->LoadOptions,
2256 loaded_image->LoadOptionsSize, loaded_image->LoadOptions);
2257 if (EFI_ERROR(err)) {
2258 Print(L"Unable to add image options measurement: %r", err);
2259 uefi_call_wrapper(BS->Stall, 1, 200 * 1000);
2260 }
2261 #endif
2262 }
2263
2264 efivar_set_time_usec(L"LoaderTimeExecUSec", 0);
2265 err = uefi_call_wrapper(BS->StartImage, 3, image, NULL, NULL);
2266 out_unload:
2267 uefi_call_wrapper(BS->UnloadImage, 1, image);
2268 return err;
2269 }
2270
2271 static EFI_STATUS reboot_into_firmware(VOID) {
2272 _cleanup_freepool_ CHAR8 *b = NULL;
2273 UINTN size;
2274 UINT64 osind;
2275 EFI_STATUS err;
2276
2277 osind = EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
2278
2279 err = efivar_get_raw(&global_guid, L"OsIndications", &b, &size);
2280 if (!EFI_ERROR(err))
2281 osind |= (UINT64)*b;
2282
2283 err = efivar_set_raw(&global_guid, L"OsIndications", &osind, sizeof(UINT64), TRUE);
2284 if (EFI_ERROR(err))
2285 return err;
2286
2287 err = uefi_call_wrapper(RT->ResetSystem, 4, EfiResetCold, EFI_SUCCESS, 0, NULL);
2288 Print(L"Error calling ResetSystem: %r", err);
2289 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2290 return err;
2291 }
2292
2293 static VOID config_free(Config *config) {
2294 UINTN i;
2295
2296 for (i = 0; i < config->entry_count; i++)
2297 config_entry_free(config->entries[i]);
2298 FreePool(config->entries);
2299 FreePool(config->entry_default_pattern);
2300 FreePool(config->options_edit);
2301 FreePool(config->entry_oneshot);
2302 }
2303
2304 static VOID config_write_entries_to_variable(Config *config) {
2305 _cleanup_freepool_ CHAR16 *buffer = NULL;
2306 UINTN i, sz = 0;
2307 CHAR16 *p;
2308
2309 for (i = 0; i < config->entry_count; i++)
2310 sz += StrLen(config->entries[i]->id) + 1;
2311
2312 p = buffer = AllocatePool(sz * sizeof(CHAR16));
2313
2314 for (i = 0; i < config->entry_count; i++) {
2315 UINTN l;
2316
2317 l = StrLen(config->entries[i]->id) + 1;
2318 CopyMem(p, config->entries[i]->id, l * sizeof(CHAR16));
2319
2320 p += l;
2321 }
2322
2323 /* Store the full list of discovered entries. */
2324 (void) efivar_set_raw(&loader_guid, L"LoaderEntries", buffer, (UINT8*) p - (UINT8*) buffer, FALSE);
2325 }
2326
2327 EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *sys_table) {
2328 static const UINT64 loader_features =
2329 EFI_LOADER_FEATURE_CONFIG_TIMEOUT |
2330 EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT |
2331 EFI_LOADER_FEATURE_ENTRY_DEFAULT |
2332 EFI_LOADER_FEATURE_ENTRY_ONESHOT |
2333 EFI_LOADER_FEATURE_BOOT_COUNTING |
2334 EFI_LOADER_FEATURE_XBOOTLDR |
2335 EFI_LOADER_FEATURE_RANDOM_SEED |
2336 0;
2337
2338 _cleanup_freepool_ CHAR16 *infostr = NULL, *typestr = NULL;
2339 CHAR8 *b;
2340 UINTN size;
2341 EFI_LOADED_IMAGE *loaded_image;
2342 EFI_FILE *root_dir;
2343 CHAR16 *loaded_image_path;
2344 EFI_STATUS err;
2345 Config config;
2346 UINT64 init_usec;
2347 BOOLEAN menu = FALSE;
2348 CHAR16 uuid[37];
2349
2350 InitializeLib(image, sys_table);
2351 init_usec = time_usec();
2352 efivar_set_time_usec(L"LoaderTimeInitUSec", init_usec);
2353 efivar_set(L"LoaderInfo", L"systemd-boot " GIT_VERSION, FALSE);
2354
2355 infostr = PoolPrint(L"%s %d.%02d", ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
2356 efivar_set(L"LoaderFirmwareInfo", infostr, FALSE);
2357
2358 typestr = PoolPrint(L"UEFI %d.%02d", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
2359 efivar_set(L"LoaderFirmwareType", typestr, FALSE);
2360
2361 (void) efivar_set_raw(&loader_guid, L"LoaderFeatures", &loader_features, sizeof(loader_features), FALSE);
2362
2363 err = uefi_call_wrapper(BS->OpenProtocol, 6, image, &LoadedImageProtocol, (VOID **)&loaded_image,
2364 image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
2365 if (EFI_ERROR(err)) {
2366 Print(L"Error getting a LoadedImageProtocol handle: %r", err);
2367 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2368 return err;
2369 }
2370
2371 /* export the device path this image is started from */
2372 if (disk_get_part_uuid(loaded_image->DeviceHandle, uuid) == EFI_SUCCESS)
2373 efivar_set(L"LoaderDevicePartUUID", uuid, FALSE);
2374
2375 root_dir = LibOpenRoot(loaded_image->DeviceHandle);
2376 if (!root_dir) {
2377 Print(L"Unable to open root directory.");
2378 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2379 return EFI_LOAD_ERROR;
2380 }
2381
2382 if (secure_boot_enabled() && shim_loaded()) {
2383 err = security_policy_install();
2384 if (EFI_ERROR(err)) {
2385 Print(L"Error installing security policy: %r ", err);
2386 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2387 return err;
2388 }
2389 }
2390
2391 /* the filesystem path to this image, to prevent adding ourselves to the menu */
2392 loaded_image_path = DevicePathToStr(loaded_image->FilePath);
2393 efivar_set(L"LoaderImageIdentifier", loaded_image_path, FALSE);
2394
2395 config_load_defaults(&config, root_dir);
2396
2397 /* scan /EFI/Linux/ directory */
2398 config_entry_add_linux(&config, loaded_image->DeviceHandle, root_dir);
2399
2400 /* scan /loader/entries/\*.conf files */
2401 config_load_entries(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
2402
2403 /* Similar, but on any XBOOTLDR partition */
2404 config_load_xbootldr(&config, loaded_image->DeviceHandle);
2405
2406 /* sort entries after version number */
2407 config_sort_entries(&config);
2408
2409 /* if we find some well-known loaders, add them to the end of the list */
2410 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, NULL,
2411 L"auto-windows", 'w', L"Windows Boot Manager", L"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
2412 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, NULL,
2413 L"auto-efi-shell", 's', L"EFI Shell", L"\\shell" EFI_MACHINE_TYPE_NAME ".efi");
2414 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
2415 L"auto-efi-default", '\0', L"EFI Default Loader", L"\\EFI\\Boot\\boot" EFI_MACHINE_TYPE_NAME ".efi");
2416 config_entry_add_osx(&config);
2417
2418 if (config.auto_firmware && efivar_get_raw(&global_guid, L"OsIndicationsSupported", &b, &size) == EFI_SUCCESS) {
2419 UINT64 osind = (UINT64)*b;
2420
2421 if (osind & EFI_OS_INDICATIONS_BOOT_TO_FW_UI)
2422 config_entry_add_call(&config,
2423 L"auto-reboot-to-firmware-setup",
2424 L"Reboot Into Firmware Interface",
2425 reboot_into_firmware);
2426 FreePool(b);
2427 }
2428
2429 if (config.entry_count == 0) {
2430 Print(L"No loader found. Configuration files in \\loader\\entries\\*.conf are needed.");
2431 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2432 goto out;
2433 }
2434
2435 config_write_entries_to_variable(&config);
2436
2437 config_title_generate(&config);
2438
2439 /* select entry by configured pattern or EFI LoaderDefaultEntry= variable */
2440 config_default_entry_select(&config);
2441
2442 /* if no configured entry to select from was found, enable the menu */
2443 if (config.idx_default == -1) {
2444 config.idx_default = 0;
2445 if (config.timeout_sec == 0)
2446 config.timeout_sec = 10;
2447 }
2448
2449 /* select entry or show menu when key is pressed or timeout is set */
2450 if (config.force_menu || config.timeout_sec > 0)
2451 menu = TRUE;
2452 else {
2453 UINT64 key;
2454
2455 err = console_key_read(&key, FALSE);
2456 if (!EFI_ERROR(err)) {
2457 INT16 idx;
2458
2459 /* find matching key in config entries */
2460 idx = entry_lookup_key(&config, config.idx_default, KEYCHAR(key));
2461 if (idx >= 0)
2462 config.idx_default = idx;
2463 else
2464 menu = TRUE;
2465 }
2466 }
2467
2468 for (;;) {
2469 ConfigEntry *entry;
2470
2471 entry = config.entries[config.idx_default];
2472 if (menu) {
2473 efivar_set_time_usec(L"LoaderTimeMenuUSec", 0);
2474 uefi_call_wrapper(BS->SetWatchdogTimer, 4, 0, 0x10000, 0, NULL);
2475 if (!menu_run(&config, &entry, loaded_image_path))
2476 break;
2477 }
2478
2479 /* run special entry like "reboot" */
2480 if (entry->call) {
2481 entry->call();
2482 continue;
2483 }
2484
2485 config_entry_bump_counters(entry, root_dir);
2486
2487 /* Export the selected boot entry to the system */
2488 (VOID) efivar_set(L"LoaderEntrySelected", entry->id, FALSE);
2489
2490 /* Optionally, read a random seed off the ESP and pass it to the OS */
2491 (VOID) process_random_seed(root_dir, config.random_seed_mode);
2492
2493 uefi_call_wrapper(BS->SetWatchdogTimer, 4, 5 * 60, 0x10000, 0, NULL);
2494 err = image_start(image, &config, entry);
2495 if (EFI_ERROR(err)) {
2496 graphics_mode(FALSE);
2497 Print(L"\nFailed to execute %s (%s): %r\n", entry->title, entry->loader, err);
2498 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2499 goto out;
2500 }
2501
2502 menu = TRUE;
2503 config.timeout_sec = 0;
2504 }
2505 err = EFI_SUCCESS;
2506 out:
2507 FreePool(loaded_image_path);
2508 config_free(&config);
2509 uefi_call_wrapper(root_dir->Close, 1, root_dir);
2510 uefi_call_wrapper(BS->CloseProtocol, 4, image, &LoadedImageProtocol, image, NULL);
2511 return err;
2512 }