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