]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/boot/efi/boot.c
tree-wide: use '"' instead of '\"'
[thirdparty/systemd.git] / src / boot / efi / boot.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
0fa2cac4
KS
2
3#include <efi.h>
4#include <efilib.h>
5
0fa2cac4 6#include "console.h"
8110e144 7#include "disk.h"
cf0fbc49 8#include "graphics.h"
0fa2cac4 9#include "linux.h"
92ed3bb4 10#include "measure.h"
d4cbada2 11#include "pe.h"
b2bb40ce 12#include "shim.h"
d4cbada2 13#include "util.h"
0fa2cac4
KS
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 */
681bd2c5 20static const char __attribute__((used)) magic[] = "#### LoaderInfo: systemd-boot " GIT_VERSION " ####";
0fa2cac4
KS
21
22static const EFI_GUID global_guid = EFI_GLOBAL_VARIABLE;
23
24enum loader_type {
25 LOADER_UNDEFINED,
26 LOADER_EFI,
f538cc65 27 LOADER_LINUX,
0fa2cac4
KS
28};
29
30typedef struct {
081cc95f 31 CHAR16 *id; /* The identifier for this entry (note that this id is not necessarily unique though!) */
0fa2cac4
KS
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;
0fa2cac4
KS
40 CHAR16 key;
41 EFI_STATUS (*call)(VOID);
42 BOOLEAN no_autoselect;
43 BOOLEAN non_unique;
f538cc65
LP
44 UINTN tries_done;
45 UINTN tries_left;
46 CHAR16 *path;
47 CHAR16 *current_name;
48 CHAR16 *next_name;
0fa2cac4
KS
49} ConfigEntry;
50
51typedef 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;
0fa2cac4
KS
60 CHAR16 *entry_oneshot;
61 CHAR16 *options_edit;
c1d4e298
JJ
62 BOOLEAN editor;
63 BOOLEAN auto_entries;
64 BOOLEAN auto_firmware;
fe2579dd 65 BOOLEAN force_menu;
68d4b8ac
HDA
66 UINTN console_mode;
67 enum console_mode_change_type console_mode_change;
0fa2cac4
KS
68} Config;
69
52efd56a 70static VOID cursor_left(UINTN *cursor, UINTN *first) {
0fa2cac4
KS
71 if ((*cursor) > 0)
72 (*cursor)--;
73 else if ((*first) > 0)
74 (*first)--;
75}
76
580fe4df
LP
77static VOID cursor_right(
78 UINTN *cursor,
79 UINTN *first,
80 UINTN x_max,
81 UINTN len) {
82
0fa2cac4
KS
83 if ((*cursor)+1 < x_max)
84 (*cursor)++;
85 else if ((*first) + (*cursor) < len)
86 (*first)++;
87}
88
580fe4df
LP
89static BOOLEAN line_edit(
90 CHAR16 *line_in,
91 CHAR16 **line_out,
92 UINTN x_max,
93 UINTN y_pos) {
94
a42d7cf1
ZJS
95 _cleanup_freepool_ CHAR16 *line = NULL, *print = NULL;
96 UINTN size, len, first, cursor, clear;
97 BOOLEAN exit, enter;
0fa2cac4
KS
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 */
977f65f0 169 while (line[first + cursor] == ' ')
0fa2cac4
KS
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);
0fa2cac4
KS
325 return enter;
326}
327
328static 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
7361099e 354static VOID print_status(Config *config, CHAR16 *loaded_image_path) {
0fa2cac4
KS
355 UINT64 key;
356 UINTN i;
a42d7cf1
ZJS
357 _cleanup_freepool_ CHAR8 *bootvar = NULL, *modevar = NULL, *indvar = NULL;
358 _cleanup_freepool_ CHAR16 *partstr = NULL, *defaultstr = NULL;
359 UINTN x, y, size;
0fa2cac4
KS
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
681bd2c5 364 Print(L"systemd-boot version: " GIT_VERSION "\n");
0fa2cac4
KS
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
a42d7cf1
ZJS
374 if (efivar_get_raw(&global_guid, L"SecureBoot", &bootvar, &size) == EFI_SUCCESS)
375 Print(L"SecureBoot: %s\n", yes_no(*bootvar > 0));
0fa2cac4 376
a42d7cf1
ZJS
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");
0fa2cac4 379
b2bb40ce
MR
380 if (shim_loaded())
381 Print(L"Shim: present\n");
382
a42d7cf1
ZJS
383 if (efivar_get_raw(&global_guid, L"OsIndicationsSupported", &indvar, &size) == EFI_SUCCESS)
384 Print(L"OsIndicationsSupported: %d\n", (UINT64)*indvar);
c1d4e298
JJ
385
386 Print(L"\n--- press key ---\n\n");
387 console_key_read(&key, TRUE);
0fa2cac4 388
8ac69471 389 Print(L"timeout: %u\n", config->timeout_sec);
0fa2cac4
KS
390 if (config->timeout_sec_efivar >= 0)
391 Print(L"timeout (EFI var): %d\n", config->timeout_sec_efivar);
8ac69471 392 Print(L"timeout (config): %u\n", config->timeout_sec_config);
0fa2cac4
KS
393 if (config->entry_default_pattern)
394 Print(L"default pattern: '%s'\n", config->entry_default_pattern);
c1d4e298
JJ
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));
0fa2cac4
KS
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)
8ac69471
LP
407 Print(L"LoaderConfigTimeout: %u\n", i);
408
0fa2cac4
KS
409 if (config->entry_oneshot)
410 Print(L"LoaderEntryOneShot: %s\n", config->entry_oneshot);
a42d7cf1
ZJS
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);
0fa2cac4
KS
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];
0fa2cac4 426 Print(L"config entry: %d/%d\n", i+1, config->entry_count);
081cc95f
LP
427 if (entry->id)
428 Print(L"id '%s'\n", entry->id);
0fa2cac4
KS
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;
0fa2cac4
KS
438
439 device_path = DevicePathFromHandle(entry->device);
440 if (device_path) {
a42d7cf1
ZJS
441 _cleanup_freepool_ CHAR16 *str;
442
0fa2cac4
KS
443 str = DevicePathToStr(device_path);
444 Print(L"device handle '%s'\n", str);
0fa2cac4
KS
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);
4db7e6d7 451 Print(L"auto-select %s\n", yes_no(!entry->no_autoselect));
0fa2cac4
KS
452 if (entry->call)
453 Print(L"internal call yes\n");
454
f538cc65
LP
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
0fa2cac4
KS
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
580fe4df
LP
473static BOOLEAN menu_run(
474 Config *config,
475 ConfigEntry **chosen_entry,
476 CHAR16 *loaded_image_path) {
477
0fa2cac4
KS
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;
68d4b8ac 500 BOOLEAN cleared_screen = FALSE;
0fa2cac4
KS
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" ");
68d4b8ac
HDA
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);
0fa2cac4
KS
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 */
081cc95f 748 efivar_set(L"LoaderEntryDefault", config->entries[idx_highlight]->id, TRUE);
0fa2cac4
KS
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 */
c1d4e298 795 if (!config->editor || config->entries[idx_highlight]->type == LOADER_UNDEFINED)
0fa2cac4
KS
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'):
681bd2c5 807 status = PoolPrint(L"systemd-boot " GIT_VERSION " (" EFI_MACHINE_TYPE_NAME "), UEFI Specification %d.%02d, Vendor %s %d.%02d",
0fa2cac4
KS
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'):
7361099e 813 print_status(config, loaded_image_path);
0fa2cac4
KS
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;
56c70b32 835 } else if (idx_highlight < idx_first) {
0fa2cac4
KS
836 idx_first = idx_highlight;
837 idx_last = idx_highlight + visible_max-1;
838 refresh = TRUE;
839 }
840
0fa2cac4
KS
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
857static 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
871static VOID config_entry_free(ConfigEntry *entry) {
42cf81c2
LP
872 if (!entry)
873 return;
874
875 FreePool(entry->id);
0fa2cac4
KS
876 FreePool(entry->title_show);
877 FreePool(entry->title);
42cf81c2 878 FreePool(entry->version);
0fa2cac4
KS
879 FreePool(entry->machine_id);
880 FreePool(entry->loader);
881 FreePool(entry->options);
f538cc65
LP
882 FreePool(entry->path);
883 FreePool(entry->current_name);
884 FreePool(entry->next_name);
42cf81c2 885 FreePool(entry);
0fa2cac4
KS
886}
887
52efd56a 888static BOOLEAN is_digit(CHAR16 c) {
0fa2cac4
KS
889 return (c >= '0') && (c <= '9');
890}
891
52efd56a 892static UINTN c_order(CHAR16 c) {
0fa2cac4
KS
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
52efd56a 903static INTN str_verscmp(CHAR16 *s1, CHAR16 *s2) {
0fa2cac4
KS
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);
64e7e27c 914 if (order != 0)
0fa2cac4
KS
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
64e7e27c 938 if (first != 0)
0fa2cac4
KS
939 return first;
940 }
941
942 return StrCmp(os1, os2);
943}
944
580fe4df
LP
945static CHAR8 *line_get_key_value(
946 CHAR8 *content,
947 CHAR8 *sep,
948 UINTN *pos,
949 CHAR8 **key_ret,
950 CHAR8 **value_ret) {
951
0fa2cac4
KS
952 CHAR8 *line;
953 UINTN linelen;
954 CHAR8 *value;
955
956skip:
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 */
d949c467 984 while (linelen > 0 && strchra((CHAR8 *)" \t", line[linelen-1]))
0fa2cac4
KS
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 */
e768a4f0 1003 if (value[0] == '"' && line[linelen-1] == '"') {
0fa2cac4
KS
1004 value++;
1005 line[linelen-1] = '\0';
1006 }
1007
1008 *key_ret = line;
1009 *value_ret = value;
1010 return line;
1011}
1012
1013static VOID config_defaults_load_from_file(Config *config, CHAR8 *content) {
1014 CHAR8 *line;
1015 UINTN pos = 0;
1016 CHAR8 *key, *value;
1017
0fa2cac4
KS
1018 while ((line = line_get_key_value(content, (CHAR8 *)" \t", &pos, &key, &value))) {
1019 if (strcmpa((CHAR8 *)"timeout", key) == 0) {
a42d7cf1 1020 _cleanup_freepool_ CHAR16 *s = NULL;
0fa2cac4
KS
1021
1022 s = stra_to_str(value);
1023 config->timeout_sec_config = Atoi(s);
1024 config->timeout_sec = config->timeout_sec_config;
0fa2cac4
KS
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 }
4db7e6d7
KS
1034
1035 if (strcmpa((CHAR8 *)"editor", key) == 0) {
1036 BOOLEAN on;
1037
1038 if (EFI_ERROR(parse_boolean(value, &on)))
1039 continue;
c1d4e298
JJ
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;
4db7e6d7 1057 }
68d4b8ac
HDA
1058
1059 if (strcmpa((CHAR8 *)"console-mode", key) == 0) {
68d4b8ac
HDA
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 {
a42d7cf1
ZJS
1067 _cleanup_freepool_ CHAR16 *s = NULL;
1068
68d4b8ac
HDA
1069 s = stra_to_str(value);
1070 config->console_mode = Atoi(s);
1071 config->console_mode_change = CONSOLE_MODE_SET;
68d4b8ac
HDA
1072 }
1073
1074 continue;
1075 }
0fa2cac4
KS
1076 }
1077}
1078
f538cc65
LP
1079static 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
1178good:
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
1194static 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
580fe4df
LP
1264static VOID config_entry_add_from_file(
1265 Config *config,
1266 EFI_HANDLE *device,
f538cc65 1267 CHAR16 *path,
580fe4df
LP
1268 CHAR16 *file,
1269 CHAR8 *content,
1270 CHAR16 *loaded_image_path) {
1271
0fa2cac4
KS
1272 ConfigEntry *entry;
1273 CHAR8 *line;
1274 UINTN pos = 0;
1275 CHAR8 *key, *value;
1276 UINTN len;
a42d7cf1 1277 _cleanup_freepool_ CHAR16 *initrd = NULL;
0fa2cac4 1278
f538cc65
LP
1279 entry = AllocatePool(sizeof(ConfigEntry));
1280
1281 *entry = (ConfigEntry) {
1282 .tries_done = (UINTN) -1,
1283 .tries_left = (UINTN) -1,
1284 };
0fa2cac4 1285
0fa2cac4
KS
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) {
a42d7cf1 1336 _cleanup_freepool_ CHAR16 *new = NULL;
0fa2cac4
KS
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);
a42d7cf1 1347
0fa2cac4
KS
1348 continue;
1349 }
1350
1351 if (strcmpa((CHAR8 *)"options", key) == 0) {
a42d7cf1 1352 _cleanup_freepool_ CHAR16 *new = NULL;
0fa2cac4
KS
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 }
a42d7cf1 1365
0fa2cac4
KS
1366 continue;
1367 }
0fa2cac4
KS
1368 }
1369
1370 if (entry->type == LOADER_UNDEFINED) {
1371 config_entry_free(entry);
0fa2cac4
KS
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 }
0fa2cac4 1388
0fa2cac4 1389 entry->device = device;
081cc95f
LP
1390 entry->id = StrDuplicate(file);
1391 len = StrLen(entry->id);
0fa2cac4
KS
1392 /* remove ".conf" */
1393 if (len > 5)
081cc95f
LP
1394 entry->id[len - 5] = '\0';
1395 StrLwr(entry->id);
0fa2cac4
KS
1396
1397 config_add_entry(config, entry);
f538cc65
LP
1398
1399 config_entry_parse_tries(entry, path, file, L".conf");
0fa2cac4
KS
1400}
1401
540536ff 1402static VOID config_load_defaults(Config *config, EFI_FILE *root_dir) {
a42d7cf1 1403 _cleanup_freepool_ CHAR8 *content = NULL;
0fa2cac4 1404 UINTN sec;
540536ff 1405 EFI_STATUS err;
0fa2cac4 1406
aec1443a
LP
1407 *config = (Config) {
1408 .editor = TRUE,
1409 .auto_entries = TRUE,
1410 .auto_firmware = TRUE,
1411 };
c1d4e298 1412
33d4ba32
JJ
1413 err = file_read(root_dir, L"\\loader\\loader.conf", 0, 0, &content, NULL);
1414 if (!EFI_ERROR(err))
0fa2cac4 1415 config_defaults_load_from_file(config, content);
0fa2cac4
KS
1416
1417 err = efivar_get_int(L"LoaderConfigTimeout", &sec);
1418 if (!EFI_ERROR(err)) {
2366d923 1419 config->timeout_sec_efivar = sec > INTN_MAX ? INTN_MAX : sec;
0fa2cac4
KS
1420 config->timeout_sec = sec;
1421 } else
1422 config->timeout_sec_efivar = -1;
fe2579dd
LP
1423
1424 err = efivar_get_int(L"LoaderConfigTimeoutOneShot", &sec);
1425 if (!EFI_ERROR(err)) {
1426 /* Unset variable now, after all it's "one shot". */
1427 (void) efivar_set(L"LoaderConfigTimeoutOneShot", NULL, TRUE);
1428
1429 config->timeout_sec = sec;
1430 config->force_menu = TRUE; /* force the menu when this is set */
1431 }
540536ff
KS
1432}
1433
580fe4df
LP
1434static VOID config_load_entries(
1435 Config *config,
1436 EFI_HANDLE *device,
1437 EFI_FILE *root_dir,
1438 CHAR16 *loaded_image_path) {
1439
540536ff
KS
1440 EFI_FILE_HANDLE entries_dir;
1441 EFI_STATUS err;
0fa2cac4
KS
1442
1443 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &entries_dir, L"\\loader\\entries", EFI_FILE_MODE_READ, 0ULL);
1444 if (!EFI_ERROR(err)) {
1445 for (;;) {
1446 CHAR16 buf[256];
1447 UINTN bufsize;
1448 EFI_FILE_INFO *f;
a42d7cf1 1449 _cleanup_freepool_ CHAR8 *content = NULL;
0fa2cac4
KS
1450 UINTN len;
1451
1452 bufsize = sizeof(buf);
1453 err = uefi_call_wrapper(entries_dir->Read, 3, entries_dir, &bufsize, buf);
1454 if (bufsize == 0 || EFI_ERROR(err))
1455 break;
1456
1457 f = (EFI_FILE_INFO *) buf;
1458 if (f->FileName[0] == '.')
1459 continue;
1460 if (f->Attribute & EFI_FILE_DIRECTORY)
1461 continue;
9d3dec15 1462
0fa2cac4
KS
1463 len = StrLen(f->FileName);
1464 if (len < 6)
1465 continue;
1466 if (StriCmp(f->FileName + len - 5, L".conf") != 0)
1467 continue;
9d3dec15
KS
1468 if (StrnCmp(f->FileName, L"auto-", 5) == 0)
1469 continue;
0fa2cac4 1470
33d4ba32
JJ
1471 err = file_read(entries_dir, f->FileName, 0, 0, &content, NULL);
1472 if (!EFI_ERROR(err))
f538cc65 1473 config_entry_add_from_file(config, device, L"\\loader\\entries", f->FileName, content, loaded_image_path);
0fa2cac4
KS
1474 }
1475 uefi_call_wrapper(entries_dir->Close, 1, entries_dir);
1476 }
540536ff
KS
1477}
1478
f538cc65
LP
1479static INTN config_entry_compare(ConfigEntry *a, ConfigEntry *b) {
1480 INTN r;
1481
1482 /* Order entries that have no tries left to the end of the list */
1483 if (a->tries_left != 0 && b->tries_left == 0)
1484 return -1;
1485 if (a->tries_left == 0 && b->tries_left != 0)
1486 return 1;
1487
1488 r = str_verscmp(a->id, b->id);
1489 if (r != 0)
1490 return r;
1491
1492 if (a->tries_left == (UINTN) -1 ||
1493 b->tries_left == (UINTN) -1)
1494 return 0;
1495
1496 /* If both items have boot counting, and otherwise are identical, put the entry with more tries left first */
1497 if (a->tries_left > b->tries_left)
1498 return -1;
1499 if (a->tries_left < b->tries_left)
1500 return 1;
1501
1502 /* If they have the same number of tries left, then let the one win which was tried fewer times so far */
1503 if (a->tries_done < b->tries_done)
1504 return -1;
1505 if (a->tries_done > b->tries_done)
1506 return 1;
1507
1508 return 0;
1509}
1510
540536ff
KS
1511static VOID config_sort_entries(Config *config) {
1512 UINTN i;
0fa2cac4 1513
0fa2cac4
KS
1514 for (i = 1; i < config->entry_count; i++) {
1515 BOOLEAN more;
1516 UINTN k;
1517
1518 more = FALSE;
1519 for (k = 0; k < config->entry_count - i; k++) {
1520 ConfigEntry *entry;
1521
f538cc65 1522 if (config_entry_compare(config->entries[k], config->entries[k+1]) <= 0)
0fa2cac4 1523 continue;
f538cc65 1524
0fa2cac4
KS
1525 entry = config->entries[k];
1526 config->entries[k] = config->entries[k+1];
1527 config->entries[k+1] = entry;
1528 more = TRUE;
1529 }
1530 if (!more)
1531 break;
1532 }
1533}
1534
535610b5
LP
1535static INTN config_entry_find(Config *config, CHAR16 *id) {
1536 UINTN i;
1537
1538 for (i = 0; i < config->entry_count; i++)
1539 if (StrCmp(config->entries[i]->id, id) == 0)
1540 return (INTN) i;
1541
1542 return -1;
1543}
1544
0fa2cac4 1545static VOID config_default_entry_select(Config *config) {
a42d7cf1 1546 _cleanup_freepool_ CHAR16 *entry_oneshot = NULL, *entry_default = NULL;
0fa2cac4 1547 EFI_STATUS err;
535610b5 1548 INTN i;
0fa2cac4
KS
1549
1550 /*
1551 * The EFI variable to specify a boot entry for the next, and only the
1552 * next reboot. The variable is always cleared directly after it is read.
1553 */
a42d7cf1 1554 err = efivar_get(L"LoaderEntryOneShot", &entry_oneshot);
0fa2cac4 1555 if (!EFI_ERROR(err)) {
0fa2cac4 1556
a42d7cf1 1557 config->entry_oneshot = StrDuplicate(entry_oneshot);
0fa2cac4 1558 efivar_set(L"LoaderEntryOneShot", NULL, TRUE);
535610b5
LP
1559
1560 i = config_entry_find(config, entry_oneshot);
1561 if (i >= 0) {
1562 config->idx_default = i;
0fa2cac4 1563 return;
535610b5 1564 }
0fa2cac4
KS
1565 }
1566
1567 /*
1568 * The EFI variable to select the default boot entry overrides the
1569 * configured pattern. The variable can be set and cleared by pressing
1570 * the 'd' key in the loader selection menu, the entry is marked with
1571 * an '*'.
1572 */
a42d7cf1 1573 err = efivar_get(L"LoaderEntryDefault", &entry_default);
0fa2cac4 1574 if (!EFI_ERROR(err)) {
535610b5
LP
1575
1576 i = config_entry_find(config, entry_default);
1577 if (i >= 0) {
1578 config->idx_default = i;
1579 config->idx_default_efivar = i;
1580 return;
1581 }
0fa2cac4
KS
1582 }
1583 config->idx_default_efivar = -1;
1584
1585 if (config->entry_count == 0)
1586 return;
1587
1588 /*
1589 * Match the pattern from the end of the list to the start, find last
1590 * entry (largest number) matching the given pattern.
1591 */
1592 if (config->entry_default_pattern) {
1593 i = config->entry_count;
1594 while (i--) {
1595 if (config->entries[i]->no_autoselect)
1596 continue;
081cc95f 1597 if (MetaiMatch(config->entries[i]->id, config->entry_default_pattern)) {
0fa2cac4
KS
1598 config->idx_default = i;
1599 return;
1600 }
1601 }
1602 }
1603
1604 /* select the last suitable entry */
1605 i = config->entry_count;
1606 while (i--) {
1607 if (config->entries[i]->no_autoselect)
1608 continue;
1609 config->idx_default = i;
1610 return;
1611 }
1612
1613 /* no entry found */
1614 config->idx_default = -1;
1615}
1616
a2fa605a
ZJS
1617static BOOLEAN find_nonunique(ConfigEntry **entries, UINTN entry_count) {
1618 BOOLEAN non_unique = FALSE;
1619 UINTN i, k;
1620
1621 for (i = 0; i < entry_count; i++)
1622 entries[i]->non_unique = FALSE;
1623
1624 for (i = 0; i < entry_count; i++)
1625 for (k = 0; k < entry_count; k++) {
1626 if (i == k)
1627 continue;
1628 if (StrCmp(entries[i]->title_show, entries[k]->title_show) != 0)
1629 continue;
1630
1631 non_unique = entries[i]->non_unique = entries[k]->non_unique = TRUE;
1632 }
1633
1634 return non_unique;
1635}
1636
0fa2cac4
KS
1637/* generate a unique title, avoiding non-distinguishable menu entries */
1638static VOID config_title_generate(Config *config) {
a2fa605a 1639 UINTN i;
0fa2cac4
KS
1640
1641 /* set title */
1642 for (i = 0; i < config->entry_count; i++) {
1643 CHAR16 *title;
1644
1645 FreePool(config->entries[i]->title_show);
1646 title = config->entries[i]->title;
1647 if (!title)
081cc95f 1648 title = config->entries[i]->id;
0fa2cac4
KS
1649 config->entries[i]->title_show = StrDuplicate(title);
1650 }
1651
a2fa605a 1652 if (!find_nonunique(config->entries, config->entry_count))
0fa2cac4
KS
1653 return;
1654
1655 /* add version to non-unique titles */
1656 for (i = 0; i < config->entry_count; i++) {
1657 CHAR16 *s;
1658
1659 if (!config->entries[i]->non_unique)
1660 continue;
1661 if (!config->entries[i]->version)
1662 continue;
1663
1664 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, config->entries[i]->version);
1665 FreePool(config->entries[i]->title_show);
1666 config->entries[i]->title_show = s;
0fa2cac4
KS
1667 }
1668
a2fa605a 1669 if (!find_nonunique(config->entries, config->entry_count))
0fa2cac4
KS
1670 return;
1671
1672 /* add machine-id to non-unique titles */
1673 for (i = 0; i < config->entry_count; i++) {
1674 CHAR16 *s;
a42d7cf1 1675 _cleanup_freepool_ CHAR16 *m = NULL;
0fa2cac4
KS
1676
1677 if (!config->entries[i]->non_unique)
1678 continue;
1679 if (!config->entries[i]->machine_id)
1680 continue;
1681
1682 m = StrDuplicate(config->entries[i]->machine_id);
1683 m[8] = '\0';
1684 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, m);
1685 FreePool(config->entries[i]->title_show);
1686 config->entries[i]->title_show = s;
0fa2cac4
KS
1687 }
1688
a2fa605a 1689 if (!find_nonunique(config->entries, config->entry_count))
0fa2cac4
KS
1690 return;
1691
1692 /* add file name to non-unique titles */
1693 for (i = 0; i < config->entry_count; i++) {
1694 CHAR16 *s;
1695
1696 if (!config->entries[i]->non_unique)
1697 continue;
081cc95f 1698 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, config->entries[i]->id);
0fa2cac4
KS
1699 FreePool(config->entries[i]->title_show);
1700 config->entries[i]->title_show = s;
1701 config->entries[i]->non_unique = FALSE;
1702 }
1703}
1704
580fe4df
LP
1705static BOOLEAN config_entry_add_call(
1706 Config *config,
7f1ef125 1707 CHAR16 *id,
580fe4df
LP
1708 CHAR16 *title,
1709 EFI_STATUS (*call)(VOID)) {
1710
0fa2cac4
KS
1711 ConfigEntry *entry;
1712
f538cc65
LP
1713 entry = AllocatePool(sizeof(ConfigEntry));
1714 *entry = (ConfigEntry) {
7f1ef125 1715 .id = StrDuplicate(id),
f538cc65
LP
1716 .title = StrDuplicate(title),
1717 .call = call,
1718 .no_autoselect = TRUE,
1719 .tries_done = (UINTN) -1,
1720 .tries_left = (UINTN) -1,
1721 };
1722
0fa2cac4
KS
1723 config_add_entry(config, entry);
1724 return TRUE;
1725}
1726
580fe4df
LP
1727static ConfigEntry *config_entry_add_loader(
1728 Config *config,
1729 EFI_HANDLE *device,
1730 enum loader_type type,
081cc95f 1731 CHAR16 *id,
580fe4df
LP
1732 CHAR16 key,
1733 CHAR16 *title,
1734 CHAR16 *loader) {
1735
0fa2cac4
KS
1736 ConfigEntry *entry;
1737
f538cc65
LP
1738 entry = AllocatePool(sizeof(ConfigEntry));
1739 *entry = (ConfigEntry) {
1740 .type = type,
1741 .title = StrDuplicate(title),
1742 .device = device,
1743 .loader = StrDuplicate(loader),
1744 .id = StrDuplicate(id),
1745 .key = key,
1746 .tries_done = (UINTN) -1,
1747 .tries_left = (UINTN) -1,
1748 };
1749
081cc95f 1750 StrLwr(entry->id);
0fa2cac4 1751
f538cc65 1752 config_add_entry(config, entry);
0fa2cac4
KS
1753 return entry;
1754}
1755
580fe4df
LP
1756static BOOLEAN config_entry_add_loader_auto(
1757 Config *config,
1758 EFI_HANDLE *device,
1759 EFI_FILE *root_dir,
1760 CHAR16 *loaded_image_path,
081cc95f 1761 CHAR16 *id,
580fe4df
LP
1762 CHAR16 key,
1763 CHAR16 *title,
1764 CHAR16 *loader) {
1765
0fa2cac4
KS
1766 EFI_FILE_HANDLE handle;
1767 ConfigEntry *entry;
1768 EFI_STATUS err;
1769
c1d4e298
JJ
1770 if (!config->auto_entries)
1771 return FALSE;
1772
0fa2cac4 1773 /* do not add an entry for ourselves */
4c8c9f9f
JJ
1774 if (loaded_image_path) {
1775 UINTN len;
a42d7cf1 1776 _cleanup_freepool_ CHAR8 *content = NULL;
4c8c9f9f
JJ
1777
1778 if (StriCmp(loader, loaded_image_path) == 0)
1779 return FALSE;
1780
1781 /* look for systemd-boot magic string */
1782 err = file_read(root_dir, loader, 0, 100*1024, &content, &len);
1783 if (!EFI_ERROR(err)) {
1784 CHAR8 *start = content;
1785 CHAR8 *last = content + len - sizeof(magic) - 1;
1786
1787 for (; start <= last; start++)
a42d7cf1 1788 if (start[0] == magic[0] && CompareMem(start, magic, sizeof(magic) - 1) == 0)
4c8c9f9f 1789 return FALSE;
4c8c9f9f
JJ
1790 }
1791 }
0fa2cac4
KS
1792
1793 /* check existence */
1794 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &handle, loader, EFI_FILE_MODE_READ, 0ULL);
1795 if (EFI_ERROR(err))
1796 return FALSE;
1797 uefi_call_wrapper(handle->Close, 1, handle);
1798
081cc95f 1799 entry = config_entry_add_loader(config, device, LOADER_UNDEFINED, id, key, title, loader);
0fa2cac4
KS
1800 if (!entry)
1801 return FALSE;
1802
1803 /* do not boot right away into auto-detected entries */
1804 entry->no_autoselect = TRUE;
1805
0fa2cac4
KS
1806 return TRUE;
1807}
1808
1809static VOID config_entry_add_osx(Config *config) {
1810 EFI_STATUS err;
1811 UINTN handle_count = 0;
a42d7cf1 1812 _cleanup_freepool_ EFI_HANDLE *handles = NULL;
0fa2cac4 1813
c1d4e298
JJ
1814 if (!config->auto_entries)
1815 return;
1816
0fa2cac4
KS
1817 err = LibLocateHandle(ByProtocol, &FileSystemProtocol, NULL, &handle_count, &handles);
1818 if (!EFI_ERROR(err)) {
1819 UINTN i;
1820
1821 for (i = 0; i < handle_count; i++) {
1822 EFI_FILE *root;
1823 BOOLEAN found;
1824
1825 root = LibOpenRoot(handles[i]);
1826 if (!root)
1827 continue;
b3f76b0d 1828 found = config_entry_add_loader_auto(config, handles[i], root, NULL, L"auto-osx", 'a', L"macOS",
0fa2cac4
KS
1829 L"\\System\\Library\\CoreServices\\boot.efi");
1830 uefi_call_wrapper(root->Close, 1, root);
1831 if (found)
1832 break;
1833 }
0fa2cac4
KS
1834 }
1835}
1836
580fe4df
LP
1837static VOID config_entry_add_linux(
1838 Config *config,
1839 EFI_LOADED_IMAGE *loaded_image,
1840 EFI_FILE *root_dir) {
1841
0fa2cac4
KS
1842 EFI_FILE_HANDLE linux_dir;
1843 EFI_STATUS err;
b1da143f 1844 ConfigEntry *entry;
0fa2cac4
KS
1845
1846 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &linux_dir, L"\\EFI\\Linux", EFI_FILE_MODE_READ, 0ULL);
12643e7c
ZJS
1847 if (EFI_ERROR(err))
1848 return;
0fa2cac4 1849
12643e7c
ZJS
1850 for (;;) {
1851 CHAR16 buf[256];
1852 UINTN bufsize = sizeof buf;
1853 EFI_FILE_INFO *f;
1854 CHAR8 *sections[] = {
1855 (UINT8 *)".osrel",
1856 (UINT8 *)".cmdline",
1857 NULL
1858 };
1859 UINTN offs[ELEMENTSOF(sections)-1] = {};
1860 UINTN szs[ELEMENTSOF(sections)-1] = {};
1861 UINTN addrs[ELEMENTSOF(sections)-1] = {};
1862 CHAR8 *content = NULL;
1863 UINTN len;
1864 CHAR8 *line;
1865 UINTN pos = 0;
1866 CHAR8 *key, *value;
1867 CHAR16 *os_name = NULL;
1868 CHAR16 *os_id = NULL;
1869 CHAR16 *os_version = NULL;
1870 CHAR16 *os_build = NULL;
1871
1872 err = uefi_call_wrapper(linux_dir->Read, 3, linux_dir, &bufsize, buf);
1873 if (bufsize == 0 || EFI_ERROR(err))
1874 break;
0fa2cac4 1875
12643e7c
ZJS
1876 f = (EFI_FILE_INFO *) buf;
1877 if (f->FileName[0] == '.')
1878 continue;
1879 if (f->Attribute & EFI_FILE_DIRECTORY)
1880 continue;
1881 len = StrLen(f->FileName);
1882 if (len < 5)
1883 continue;
1884 if (StriCmp(f->FileName + len - 4, L".efi") != 0)
1885 continue;
0fa2cac4 1886
12643e7c
ZJS
1887 /* look for .osrel and .cmdline sections in the .efi binary */
1888 err = pe_file_locate_sections(linux_dir, f->FileName, sections, addrs, offs, szs);
1889 if (EFI_ERROR(err))
1890 continue;
0fa2cac4 1891
12643e7c
ZJS
1892 err = file_read(linux_dir, f->FileName, offs[0], szs[0], &content, NULL);
1893 if (EFI_ERROR(err))
1894 continue;
0fa2cac4 1895
12643e7c 1896 /* read properties from the embedded os-release file */
12643e7c
ZJS
1897 while ((line = line_get_key_value(content, (CHAR8 *)"=", &pos, &key, &value))) {
1898 if (strcmpa((CHAR8 *)"PRETTY_NAME", key) == 0) {
1899 FreePool(os_name);
1900 os_name = stra_to_str(value);
1901 continue;
1902 }
0fa2cac4 1903
12643e7c
ZJS
1904 if (strcmpa((CHAR8 *)"ID", key) == 0) {
1905 FreePool(os_id);
1906 os_id = stra_to_str(value);
1907 continue;
1908 }
59658d19 1909
12643e7c
ZJS
1910 if (strcmpa((CHAR8 *)"VERSION_ID", key) == 0) {
1911 FreePool(os_version);
1912 os_version = stra_to_str(value);
1913 continue;
0fa2cac4
KS
1914 }
1915
12643e7c
ZJS
1916 if (strcmpa((CHAR8 *)"BUILD_ID", key) == 0) {
1917 FreePool(os_build);
1918 os_build = stra_to_str(value);
1919 continue;
0fa2cac4 1920 }
12643e7c
ZJS
1921 }
1922
1923 if (os_name && os_id && (os_version || os_build)) {
2214cfbf 1924 _cleanup_freepool_ CHAR16 *conf = NULL, *path = NULL;
12643e7c
ZJS
1925
1926 conf = PoolPrint(L"%s-%s", os_id, os_version ? : os_build);
1927 path = PoolPrint(L"\\EFI\\Linux\\%s", f->FileName);
2214cfbf 1928
12643e7c 1929 entry = config_entry_add_loader(config, loaded_image->DeviceHandle, LOADER_LINUX, conf, 'l', os_name, path);
0fa2cac4
KS
1930
1931 FreePool(content);
12643e7c 1932 content = NULL;
2214cfbf 1933
12643e7c 1934 /* read the embedded cmdline file */
d3a27ed4 1935 err = file_read(linux_dir, f->FileName, offs[1], szs[1], &content, NULL);
12643e7c 1936 if (!EFI_ERROR(err)) {
d3a27ed4
ZJS
1937
1938 /* chomp the newline */
1939 if (content[szs[1]-1] == '\n')
1940 content[szs[1]-1] = '\0';
1941
1942 entry->options = stra_to_str(content);
12643e7c 1943 }
f538cc65
LP
1944
1945 config_entry_parse_tries(entry, L"\\EFI\\Linux", f->FileName, L".efi");
0fa2cac4 1946 }
12643e7c
ZJS
1947
1948 FreePool(os_name);
1949 FreePool(os_id);
1950 FreePool(os_version);
1951 FreePool(os_build);
1952 FreePool(content);
0fa2cac4 1953 }
12643e7c
ZJS
1954
1955 uefi_call_wrapper(linux_dir->Close, 1, linux_dir);
0fa2cac4
KS
1956}
1957
580fe4df
LP
1958static EFI_STATUS image_start(
1959 EFI_HANDLE parent_image,
1960 const Config *config,
1961 const ConfigEntry *entry) {
1962
0fa2cac4 1963 EFI_HANDLE image;
a42d7cf1 1964 _cleanup_freepool_ EFI_DEVICE_PATH *path = NULL;
0fa2cac4
KS
1965 CHAR16 *options;
1966 EFI_STATUS err;
1967
1968 path = FileDevicePath(entry->device, entry->loader);
1969 if (!path) {
1970 Print(L"Error getting device path.");
1971 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1972 return EFI_INVALID_PARAMETER;
1973 }
1974
1975 err = uefi_call_wrapper(BS->LoadImage, 6, FALSE, parent_image, path, NULL, 0, &image);
1976 if (EFI_ERROR(err)) {
1977 Print(L"Error loading %s: %r", entry->loader, err);
1978 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
a42d7cf1 1979 return err;
0fa2cac4
KS
1980 }
1981
1982 if (config->options_edit)
1983 options = config->options_edit;
1984 else if (entry->options)
1985 options = entry->options;
1986 else
1987 options = NULL;
1988 if (options) {
1989 EFI_LOADED_IMAGE *loaded_image;
1990
1991 err = uefi_call_wrapper(BS->OpenProtocol, 6, image, &LoadedImageProtocol, (VOID **)&loaded_image,
1992 parent_image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
1993 if (EFI_ERROR(err)) {
1994 Print(L"Error getting LoadedImageProtocol handle: %r", err);
1995 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1996 goto out_unload;
1997 }
1998 loaded_image->LoadOptions = options;
1999 loaded_image->LoadOptionsSize = (StrLen(loaded_image->LoadOptions)+1) * sizeof(CHAR16);
92ed3bb4 2000
349cc4a5 2001#if ENABLE_TPM
7db5706e 2002 /* Try to log any options to the TPM, especially to catch manually edited options */
92ed3bb4 2003 err = tpm_log_event(SD_TPM_PCR,
33de6b57 2004 (EFI_PHYSICAL_ADDRESS) (UINTN) loaded_image->LoadOptions,
92ed3bb4
HH
2005 loaded_image->LoadOptionsSize, loaded_image->LoadOptions);
2006 if (EFI_ERROR(err)) {
2007 Print(L"Unable to add image options measurement: %r", err);
522aa9f5 2008 uefi_call_wrapper(BS->Stall, 1, 200 * 1000);
92ed3bb4
HH
2009 }
2010#endif
0fa2cac4
KS
2011 }
2012
2013 efivar_set_time_usec(L"LoaderTimeExecUSec", 0);
2014 err = uefi_call_wrapper(BS->StartImage, 3, image, NULL, NULL);
2015out_unload:
2016 uefi_call_wrapper(BS->UnloadImage, 1, image);
0fa2cac4
KS
2017 return err;
2018}
2019
2020static EFI_STATUS reboot_into_firmware(VOID) {
a42d7cf1 2021 _cleanup_freepool_ CHAR8 *b = NULL;
0fa2cac4
KS
2022 UINTN size;
2023 UINT64 osind;
2024 EFI_STATUS err;
2025
2026 osind = EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
2027
2028 err = efivar_get_raw(&global_guid, L"OsIndications", &b, &size);
2029 if (!EFI_ERROR(err))
2030 osind |= (UINT64)*b;
0fa2cac4 2031
f82ecab0 2032 err = efivar_set_raw(&global_guid, L"OsIndications", &osind, sizeof(UINT64), TRUE);
0fa2cac4
KS
2033 if (EFI_ERROR(err))
2034 return err;
2035
2036 err = uefi_call_wrapper(RT->ResetSystem, 4, EfiResetCold, EFI_SUCCESS, 0, NULL);
2037 Print(L"Error calling ResetSystem: %r", err);
2038 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2039 return err;
2040}
2041
2042static VOID config_free(Config *config) {
2043 UINTN i;
2044
2045 for (i = 0; i < config->entry_count; i++)
2046 config_entry_free(config->entries[i]);
2047 FreePool(config->entries);
2048 FreePool(config->entry_default_pattern);
2049 FreePool(config->options_edit);
2050 FreePool(config->entry_oneshot);
0fa2cac4
KS
2051}
2052
0e2bc732
LP
2053static VOID config_write_entries_to_variable(Config *config) {
2054 _cleanup_freepool_ CHAR16 *buffer = NULL;
2055 UINTN i, sz = 0;
2056 CHAR16 *p;
2057
2058 for (i = 0; i < config->entry_count; i++)
2059 sz += StrLen(config->entries[i]->id) + 1;
2060
2061 p = buffer = AllocatePool(sz * sizeof(CHAR16));
2062
2063 for (i = 0; i < config->entry_count; i++) {
2064 UINTN l;
2065
2066 l = StrLen(config->entries[i]->id) + 1;
2067 CopyMem(p, config->entries[i]->id, l * sizeof(CHAR16));
2068
2069 p += l;
2070 }
2071
2072 /* Store the full list of discovered entries. */
2073 (void) efivar_set_raw(&loader_guid, L"LoaderEntries", buffer, (UINT8*) p - (UINT8*) buffer, FALSE);
2074}
2075
0fa2cac4 2076EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *sys_table) {
5dd5f7cf
LP
2077 static const UINT64 loader_features =
2078 (1ULL << 0) | /* I honour the LoaderConfigTimeout variable */
2079 (1ULL << 1) | /* I honour the LoaderConfigTimeoutOneShot variable */
2080 (1ULL << 2) | /* I honour the LoaderEntryDefault variable */
2081 (1ULL << 3) | /* I honour the LoaderEntryOneShot variable */
2082 (1ULL << 4) | /* I support boot counting */
2083 0;
2084
a42d7cf1 2085 _cleanup_freepool_ CHAR16 *infostr = NULL, *typestr = NULL;
0fa2cac4
KS
2086 CHAR8 *b;
2087 UINTN size;
2088 EFI_LOADED_IMAGE *loaded_image;
2089 EFI_FILE *root_dir;
2090 CHAR16 *loaded_image_path;
0fa2cac4
KS
2091 EFI_STATUS err;
2092 Config config;
2093 UINT64 init_usec;
2094 BOOLEAN menu = FALSE;
8110e144 2095 CHAR16 uuid[37];
0fa2cac4
KS
2096
2097 InitializeLib(image, sys_table);
2098 init_usec = time_usec();
2099 efivar_set_time_usec(L"LoaderTimeInitUSec", init_usec);
681bd2c5 2100 efivar_set(L"LoaderInfo", L"systemd-boot " GIT_VERSION, FALSE);
a42d7cf1
ZJS
2101
2102 infostr = PoolPrint(L"%s %d.%02d", ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
2103 efivar_set(L"LoaderFirmwareInfo", infostr, FALSE);
2104
2105 typestr = PoolPrint(L"UEFI %d.%02d", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
2106 efivar_set(L"LoaderFirmwareType", typestr, FALSE);
0fa2cac4 2107
5dd5f7cf
LP
2108 (void) efivar_set_raw(&loader_guid, L"LoaderFeatures", &loader_features, sizeof(loader_features), FALSE);
2109
0fa2cac4
KS
2110 err = uefi_call_wrapper(BS->OpenProtocol, 6, image, &LoadedImageProtocol, (VOID **)&loaded_image,
2111 image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
2112 if (EFI_ERROR(err)) {
2113 Print(L"Error getting a LoadedImageProtocol handle: %r ", err);
2114 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2115 return err;
2116 }
2117
2118 /* export the device path this image is started from */
8110e144
KS
2119 if (disk_get_part_uuid(loaded_image->DeviceHandle, uuid) == EFI_SUCCESS)
2120 efivar_set(L"LoaderDevicePartUUID", uuid, FALSE);
0fa2cac4
KS
2121
2122 root_dir = LibOpenRoot(loaded_image->DeviceHandle);
2123 if (!root_dir) {
2124 Print(L"Unable to open root directory: %r ", err);
2125 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2126 return EFI_LOAD_ERROR;
2127 }
2128
b2bb40ce
MR
2129 if (secure_boot_enabled() && shim_loaded()) {
2130 err = security_policy_install();
2131 if (EFI_ERROR(err)) {
2132 Print(L"Error installing security policy: %r ", err);
2133 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2134 return err;
2135 }
2136 }
0fa2cac4
KS
2137
2138 /* the filesystem path to this image, to prevent adding ourselves to the menu */
2139 loaded_image_path = DevicePathToStr(loaded_image->FilePath);
2140 efivar_set(L"LoaderImageIdentifier", loaded_image_path, FALSE);
2141
540536ff 2142 config_load_defaults(&config, root_dir);
0fa2cac4 2143
540536ff 2144 /* scan /EFI/Linux/ directory */
0fa2cac4 2145 config_entry_add_linux(&config, loaded_image, root_dir);
540536ff
KS
2146
2147 /* scan /loader/entries/\*.conf files */
2148 config_load_entries(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
2149
2150 /* sort entries after version number */
2151 config_sort_entries(&config);
2152
2153 /* if we find some well-known loaders, add them to the end of the list */
4c8c9f9f 2154 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, NULL,
0fa2cac4 2155 L"auto-windows", 'w', L"Windows Boot Manager", L"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
4c8c9f9f 2156 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, NULL,
0fa2cac4
KS
2157 L"auto-efi-shell", 's', L"EFI Shell", L"\\shell" EFI_MACHINE_TYPE_NAME ".efi");
2158 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
2159 L"auto-efi-default", '\0', L"EFI Default Loader", L"\\EFI\\Boot\\boot" EFI_MACHINE_TYPE_NAME ".efi");
2160 config_entry_add_osx(&config);
0fa2cac4 2161
c1d4e298 2162 if (config.auto_firmware && efivar_get_raw(&global_guid, L"OsIndicationsSupported", &b, &size) == EFI_SUCCESS) {
0fa2cac4
KS
2163 UINT64 osind = (UINT64)*b;
2164
2165 if (osind & EFI_OS_INDICATIONS_BOOT_TO_FW_UI)
b58c7351 2166 config_entry_add_call(&config, L"auto-reboot-to-firmware-setup", L"Reboot Into Firmware Interface", reboot_into_firmware);
0fa2cac4
KS
2167 FreePool(b);
2168 }
2169
2170 if (config.entry_count == 0) {
2171 Print(L"No loader found. Configuration files in \\loader\\entries\\*.conf are needed.");
2172 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2173 goto out;
2174 }
2175
0e2bc732
LP
2176 config_write_entries_to_variable(&config);
2177
0fa2cac4
KS
2178 config_title_generate(&config);
2179
13e785f7 2180 /* select entry by configured pattern or EFI LoaderDefaultEntry= variable */
0fa2cac4
KS
2181 config_default_entry_select(&config);
2182
2183 /* if no configured entry to select from was found, enable the menu */
2184 if (config.idx_default == -1) {
2185 config.idx_default = 0;
2186 if (config.timeout_sec == 0)
2187 config.timeout_sec = 10;
2188 }
2189
2190 /* select entry or show menu when key is pressed or timeout is set */
fe2579dd
LP
2191 if (config.force_menu || config.timeout_sec > 0)
2192 menu = TRUE;
2193 else {
0fa2cac4
KS
2194 UINT64 key;
2195
2196 err = console_key_read(&key, FALSE);
2197 if (!EFI_ERROR(err)) {
2198 INT16 idx;
2199
2200 /* find matching key in config entries */
2201 idx = entry_lookup_key(&config, config.idx_default, KEYCHAR(key));
2202 if (idx >= 0)
2203 config.idx_default = idx;
2204 else
2205 menu = TRUE;
2206 }
fe2579dd 2207 }
0fa2cac4
KS
2208
2209 for (;;) {
2210 ConfigEntry *entry;
2211
2212 entry = config.entries[config.idx_default];
2213 if (menu) {
2214 efivar_set_time_usec(L"LoaderTimeMenuUSec", 0);
2215 uefi_call_wrapper(BS->SetWatchdogTimer, 4, 0, 0x10000, 0, NULL);
7361099e 2216 if (!menu_run(&config, &entry, loaded_image_path))
0fa2cac4 2217 break;
996daf2f 2218 }
0fa2cac4 2219
996daf2f
LP
2220 /* run special entry like "reboot" */
2221 if (entry->call) {
2222 entry->call();
2223 continue;
0fa2cac4
KS
2224 }
2225
f538cc65
LP
2226 config_entry_bump_counters(entry, root_dir);
2227
0fa2cac4 2228 /* export the selected boot entry to the system */
081cc95f 2229 efivar_set(L"LoaderEntrySelected", entry->id, FALSE);
0fa2cac4
KS
2230
2231 uefi_call_wrapper(BS->SetWatchdogTimer, 4, 5 * 60, 0x10000, 0, NULL);
2232 err = image_start(image, &config, entry);
20b1538d 2233 if (EFI_ERROR(err)) {
37fa3690 2234 graphics_mode(FALSE);
20b1538d 2235 Print(L"\nFailed to execute %s (%s): %r\n", entry->title, entry->loader, err);
0fa2cac4
KS
2236 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2237 goto out;
2238 }
2239
2240 menu = TRUE;
2241 config.timeout_sec = 0;
2242 }
2243 err = EFI_SUCCESS;
2244out:
2245 FreePool(loaded_image_path);
2246 config_free(&config);
2247 uefi_call_wrapper(root_dir->Close, 1, root_dir);
2248 uefi_call_wrapper(BS->CloseProtocol, 4, image, &LoadedImageProtocol, image, NULL);
2249 return err;
2250}