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