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