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