]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/boot/efi/boot.c
Merge pull request #5708 from vcatechnology/arm-cross-compile
[thirdparty/systemd.git] / src / boot / efi / boot.c
1 /*
2 * This program is free software; you can redistribute it and/or modify it
3 * under the terms of the GNU Lesser General Public License as published by
4 * the Free Software Foundation; either version 2.1 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful, but
8 * WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * Lesser General Public License for more details.
11 *
12 * Copyright (C) 2012-2015 Kay Sievers <kay@vrfy.org>
13 * Copyright (C) 2012-2015 Harald Hoyer <harald@redhat.com>
14 */
15
16 #include <efi.h>
17 #include <efilib.h>
18
19 #include "console.h"
20 #include "disk.h"
21 #include "graphics.h"
22 #include "linux.h"
23 #include "pefile.h"
24 #include "util.h"
25 #include "measure.h"
26
27 #ifndef EFI_OS_INDICATIONS_BOOT_TO_FW_UI
28 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001ULL
29 #endif
30
31 /* magic string to find in the binary image */
32 static const char __attribute__((used)) magic[] = "#### LoaderInfo: systemd-boot " PACKAGE_VERSION " ####";
33
34 static const EFI_GUID global_guid = EFI_GLOBAL_VARIABLE;
35
36 enum loader_type {
37 LOADER_UNDEFINED,
38 LOADER_EFI,
39 LOADER_LINUX
40 };
41
42 typedef struct {
43 CHAR16 *file;
44 CHAR16 *title_show;
45 CHAR16 *title;
46 CHAR16 *version;
47 CHAR16 *machine_id;
48 EFI_HANDLE *device;
49 enum loader_type type;
50 CHAR16 *loader;
51 CHAR16 *options;
52 CHAR16 key;
53 EFI_STATUS (*call)(VOID);
54 BOOLEAN no_autoselect;
55 BOOLEAN non_unique;
56 } ConfigEntry;
57
58 typedef struct {
59 ConfigEntry **entries;
60 UINTN entry_count;
61 INTN idx_default;
62 INTN idx_default_efivar;
63 UINTN timeout_sec;
64 UINTN timeout_sec_config;
65 INTN timeout_sec_efivar;
66 CHAR16 *entry_default_pattern;
67 CHAR16 *entry_oneshot;
68 CHAR16 *options_edit;
69 BOOLEAN no_editor;
70 } Config;
71
72 static VOID cursor_left(UINTN *cursor, UINTN *first) {
73 if ((*cursor) > 0)
74 (*cursor)--;
75 else if ((*first) > 0)
76 (*first)--;
77 }
78
79 static VOID cursor_right(UINTN *cursor, UINTN *first, UINTN x_max, UINTN len) {
80 if ((*cursor)+1 < x_max)
81 (*cursor)++;
82 else if ((*first) + (*cursor) < len)
83 (*first)++;
84 }
85
86 static BOOLEAN line_edit(CHAR16 *line_in, CHAR16 **line_out, UINTN x_max, UINTN y_pos) {
87 CHAR16 *line;
88 UINTN size;
89 UINTN len;
90 UINTN first;
91 CHAR16 *print;
92 UINTN cursor;
93 UINTN clear;
94 BOOLEAN exit;
95 BOOLEAN enter;
96
97 if (!line_in)
98 line_in = L"";
99 size = StrLen(line_in) + 1024;
100 line = AllocatePool(size * sizeof(CHAR16));
101 StrCpy(line, line_in);
102 len = StrLen(line);
103 print = AllocatePool((x_max+1) * sizeof(CHAR16));
104
105 uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, TRUE);
106
107 first = 0;
108 cursor = 0;
109 clear = 0;
110 enter = FALSE;
111 exit = FALSE;
112 while (!exit) {
113 EFI_STATUS err;
114 UINT64 key;
115 UINTN i;
116
117 i = len - first;
118 if (i >= x_max-1)
119 i = x_max-1;
120 CopyMem(print, line + first, i * sizeof(CHAR16));
121 while (clear > 0 && i < x_max-1) {
122 clear--;
123 print[i++] = ' ';
124 }
125 print[i] = '\0';
126
127 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_pos);
128 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, print);
129 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
130
131 err = console_key_read(&key, TRUE);
132 if (EFI_ERROR(err))
133 continue;
134
135 switch (key) {
136 case KEYPRESS(0, SCAN_ESC, 0):
137 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'c'):
138 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'g'):
139 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('c')):
140 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('g')):
141 exit = TRUE;
142 break;
143
144 case KEYPRESS(0, SCAN_HOME, 0):
145 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'a'):
146 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('a')):
147 /* beginning-of-line */
148 cursor = 0;
149 first = 0;
150 continue;
151
152 case KEYPRESS(0, SCAN_END, 0):
153 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'e'):
154 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('e')):
155 /* end-of-line */
156 cursor = len - first;
157 if (cursor+1 >= x_max) {
158 cursor = x_max-1;
159 first = len - (x_max-1);
160 }
161 continue;
162
163 case KEYPRESS(0, SCAN_DOWN, 0):
164 case KEYPRESS(EFI_ALT_PRESSED, 0, 'f'):
165 case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_RIGHT, 0):
166 /* forward-word */
167 while (line[first + cursor] && line[first + cursor] == ' ')
168 cursor_right(&cursor, &first, x_max, len);
169 while (line[first + cursor] && line[first + cursor] != ' ')
170 cursor_right(&cursor, &first, x_max, len);
171 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
172 continue;
173
174 case KEYPRESS(0, SCAN_UP, 0):
175 case KEYPRESS(EFI_ALT_PRESSED, 0, 'b'):
176 case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_LEFT, 0):
177 /* backward-word */
178 if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
179 cursor_left(&cursor, &first);
180 while ((first + cursor) > 0 && line[first + cursor] == ' ')
181 cursor_left(&cursor, &first);
182 }
183 while ((first + cursor) > 0 && line[first + cursor-1] != ' ')
184 cursor_left(&cursor, &first);
185 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
186 continue;
187
188 case KEYPRESS(0, SCAN_RIGHT, 0):
189 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'f'):
190 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('f')):
191 /* forward-char */
192 if (first + cursor == len)
193 continue;
194 cursor_right(&cursor, &first, x_max, len);
195 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
196 continue;
197
198 case KEYPRESS(0, SCAN_LEFT, 0):
199 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'b'):
200 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('b')):
201 /* backward-char */
202 cursor_left(&cursor, &first);
203 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
204 continue;
205
206 case KEYPRESS(EFI_ALT_PRESSED, 0, 'd'):
207 /* kill-word */
208 clear = 0;
209 for (i = first + cursor; i < len && line[i] == ' '; i++)
210 clear++;
211 for (; i < len && line[i] != ' '; i++)
212 clear++;
213
214 for (i = first + cursor; i + clear < len; i++)
215 line[i] = line[i + clear];
216 len -= clear;
217 line[len] = '\0';
218 continue;
219
220 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'w'):
221 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('w')):
222 case KEYPRESS(EFI_ALT_PRESSED, 0, CHAR_BACKSPACE):
223 /* backward-kill-word */
224 clear = 0;
225 if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
226 cursor_left(&cursor, &first);
227 clear++;
228 while ((first + cursor) > 0 && line[first + cursor] == ' ') {
229 cursor_left(&cursor, &first);
230 clear++;
231 }
232 }
233 while ((first + cursor) > 0 && line[first + cursor-1] != ' ') {
234 cursor_left(&cursor, &first);
235 clear++;
236 }
237 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
238
239 for (i = first + cursor; i + clear < len; i++)
240 line[i] = line[i + clear];
241 len -= clear;
242 line[len] = '\0';
243 continue;
244
245 case KEYPRESS(0, SCAN_DELETE, 0):
246 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'd'):
247 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('d')):
248 if (len == 0)
249 continue;
250 if (first + cursor == len)
251 continue;
252 for (i = first + cursor; i < len; i++)
253 line[i] = line[i+1];
254 clear = 1;
255 len--;
256 continue;
257
258 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'k'):
259 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('k')):
260 /* kill-line */
261 line[first + cursor] = '\0';
262 clear = len - (first + cursor);
263 len = first + cursor;
264 continue;
265
266 case KEYPRESS(0, 0, CHAR_LINEFEED):
267 case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
268 if (StrCmp(line, line_in) != 0) {
269 *line_out = line;
270 line = NULL;
271 }
272 enter = TRUE;
273 exit = TRUE;
274 break;
275
276 case KEYPRESS(0, 0, CHAR_BACKSPACE):
277 if (len == 0)
278 continue;
279 if (first == 0 && cursor == 0)
280 continue;
281 for (i = first + cursor-1; i < len; i++)
282 line[i] = line[i+1];
283 clear = 1;
284 len--;
285 if (cursor > 0)
286 cursor--;
287 if (cursor > 0 || first == 0)
288 continue;
289 /* show full line if it fits */
290 if (len < x_max) {
291 cursor = first;
292 first = 0;
293 continue;
294 }
295 /* jump left to see what we delete */
296 if (first > 10) {
297 first -= 10;
298 cursor = 10;
299 } else {
300 cursor = first;
301 first = 0;
302 }
303 continue;
304
305 case KEYPRESS(0, 0, ' ') ... KEYPRESS(0, 0, '~'):
306 case KEYPRESS(0, 0, 0x80) ... KEYPRESS(0, 0, 0xffff):
307 if (len+1 == size)
308 continue;
309 for (i = len; i > first + cursor; i--)
310 line[i] = line[i-1];
311 line[first + cursor] = KEYCHAR(key);
312 len++;
313 line[len] = '\0';
314 if (cursor+1 < x_max)
315 cursor++;
316 else if (first + cursor < len)
317 first++;
318 continue;
319 }
320 }
321
322 uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, FALSE);
323 FreePool(print);
324 FreePool(line);
325 return enter;
326 }
327
328 static UINTN entry_lookup_key(Config *config, UINTN start, CHAR16 key) {
329 UINTN i;
330
331 if (key == 0)
332 return -1;
333
334 /* select entry by number key */
335 if (key >= '1' && key <= '9') {
336 i = key - '0';
337 if (i > config->entry_count)
338 i = config->entry_count;
339 return i-1;
340 }
341
342 /* find matching key in config entries */
343 for (i = start; i < config->entry_count; i++)
344 if (config->entries[i]->key == key)
345 return i;
346
347 for (i = 0; i < start; i++)
348 if (config->entries[i]->key == key)
349 return i;
350
351 return -1;
352 }
353
354 static VOID print_status(Config *config, CHAR16 *loaded_image_path) {
355 UINT64 key;
356 UINTN i;
357 CHAR16 *s;
358 CHAR8 *b;
359 UINTN x;
360 UINTN y;
361 UINTN size;
362
363 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
364 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
365
366 Print(L"systemd-boot version: " PACKAGE_VERSION "\n");
367 Print(L"architecture: " EFI_MACHINE_TYPE_NAME "\n");
368 Print(L"loaded image: %s\n", loaded_image_path);
369 Print(L"UEFI specification: %d.%02d\n", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
370 Print(L"firmware vendor: %s\n", ST->FirmwareVendor);
371 Print(L"firmware version: %d.%02d\n", ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
372
373 if (uefi_call_wrapper(ST->ConOut->QueryMode, 4, ST->ConOut, ST->ConOut->Mode->Mode, &x, &y) == EFI_SUCCESS)
374 Print(L"console size: %d x %d\n", x, y);
375
376 if (efivar_get_raw(&global_guid, L"SecureBoot", &b, &size) == EFI_SUCCESS) {
377 Print(L"SecureBoot: %s\n", yes_no(*b > 0));
378 FreePool(b);
379 }
380
381 if (efivar_get_raw(&global_guid, L"SetupMode", &b, &size) == EFI_SUCCESS) {
382 Print(L"SetupMode: %s\n", *b > 0 ? L"setup" : L"user");
383 FreePool(b);
384 }
385
386 if (efivar_get_raw(&global_guid, L"OsIndicationsSupported", &b, &size) == EFI_SUCCESS) {
387 Print(L"OsIndicationsSupported: %d\n", (UINT64)*b);
388 FreePool(b);
389 }
390 Print(L"\n");
391
392 Print(L"timeout: %d\n", config->timeout_sec);
393 if (config->timeout_sec_efivar >= 0)
394 Print(L"timeout (EFI var): %d\n", config->timeout_sec_efivar);
395 Print(L"timeout (config): %d\n", config->timeout_sec_config);
396 if (config->entry_default_pattern)
397 Print(L"default pattern: '%s'\n", config->entry_default_pattern);
398 Print(L"editor: %s\n", yes_no(!config->no_editor));
399 Print(L"\n");
400
401 Print(L"config entry count: %d\n", config->entry_count);
402 Print(L"entry selected idx: %d\n", config->idx_default);
403 if (config->idx_default_efivar >= 0)
404 Print(L"entry EFI var idx: %d\n", config->idx_default_efivar);
405 Print(L"\n");
406
407 if (efivar_get_int(L"LoaderConfigTimeout", &i) == EFI_SUCCESS)
408 Print(L"LoaderConfigTimeout: %d\n", i);
409 if (config->entry_oneshot)
410 Print(L"LoaderEntryOneShot: %s\n", config->entry_oneshot);
411 if (efivar_get(L"LoaderDevicePartUUID", &s) == EFI_SUCCESS) {
412 Print(L"LoaderDevicePartUUID: %s\n", s);
413 FreePool(s);
414 }
415 if (efivar_get(L"LoaderEntryDefault", &s) == EFI_SUCCESS) {
416 Print(L"LoaderEntryDefault: %s\n", s);
417 FreePool(s);
418 }
419
420 Print(L"\n--- press key ---\n\n");
421 console_key_read(&key, TRUE);
422
423 for (i = 0; i < config->entry_count; i++) {
424 ConfigEntry *entry;
425
426 if (key == KEYPRESS(0, SCAN_ESC, 0) || key == KEYPRESS(0, 0, 'q'))
427 break;
428
429 entry = config->entries[i];
430 Print(L"config entry: %d/%d\n", i+1, config->entry_count);
431 if (entry->file)
432 Print(L"file '%s'\n", entry->file);
433 Print(L"title show '%s'\n", entry->title_show);
434 if (entry->title)
435 Print(L"title '%s'\n", entry->title);
436 if (entry->version)
437 Print(L"version '%s'\n", entry->version);
438 if (entry->machine_id)
439 Print(L"machine-id '%s'\n", entry->machine_id);
440 if (entry->device) {
441 EFI_DEVICE_PATH *device_path;
442 CHAR16 *str;
443
444 device_path = DevicePathFromHandle(entry->device);
445 if (device_path) {
446 str = DevicePathToStr(device_path);
447 Print(L"device handle '%s'\n", str);
448 FreePool(str);
449 }
450 }
451 if (entry->loader)
452 Print(L"loader '%s'\n", entry->loader);
453 if (entry->options)
454 Print(L"options '%s'\n", entry->options);
455 Print(L"auto-select %s\n", yes_no(!entry->no_autoselect));
456 if (entry->call)
457 Print(L"internal call yes\n");
458
459 Print(L"\n--- press key ---\n\n");
460 console_key_read(&key, TRUE);
461 }
462
463 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
464 }
465
466 static BOOLEAN menu_run(Config *config, ConfigEntry **chosen_entry, CHAR16 *loaded_image_path) {
467 EFI_STATUS err;
468 UINTN visible_max;
469 UINTN idx_highlight;
470 UINTN idx_highlight_prev;
471 UINTN idx_first;
472 UINTN idx_last;
473 BOOLEAN refresh;
474 BOOLEAN highlight;
475 UINTN i;
476 UINTN line_width;
477 CHAR16 **lines;
478 UINTN x_start;
479 UINTN y_start;
480 UINTN x_max;
481 UINTN y_max;
482 CHAR16 *status;
483 CHAR16 *clearline;
484 INTN timeout_remain;
485 INT16 idx;
486 BOOLEAN exit = FALSE;
487 BOOLEAN run = TRUE;
488 BOOLEAN wait = FALSE;
489
490 graphics_mode(FALSE);
491 uefi_call_wrapper(ST->ConIn->Reset, 2, ST->ConIn, FALSE);
492 uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, FALSE);
493 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
494
495 /* draw a single character to make ClearScreen work on some firmware */
496 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L" ");
497 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
498
499 err = uefi_call_wrapper(ST->ConOut->QueryMode, 4, ST->ConOut, ST->ConOut->Mode->Mode, &x_max, &y_max);
500 if (EFI_ERROR(err)) {
501 x_max = 80;
502 y_max = 25;
503 }
504
505 /* we check 10 times per second for a keystroke */
506 if (config->timeout_sec > 0)
507 timeout_remain = config->timeout_sec * 10;
508 else
509 timeout_remain = -1;
510
511 idx_highlight = config->idx_default;
512 idx_highlight_prev = 0;
513
514 visible_max = y_max - 2;
515
516 if ((UINTN)config->idx_default >= visible_max)
517 idx_first = config->idx_default-1;
518 else
519 idx_first = 0;
520
521 idx_last = idx_first + visible_max-1;
522
523 refresh = TRUE;
524 highlight = FALSE;
525
526 /* length of the longest entry */
527 line_width = 5;
528 for (i = 0; i < config->entry_count; i++) {
529 UINTN entry_len;
530
531 entry_len = StrLen(config->entries[i]->title_show);
532 if (line_width < entry_len)
533 line_width = entry_len;
534 }
535 if (line_width > x_max-6)
536 line_width = x_max-6;
537
538 /* offsets to center the entries on the screen */
539 x_start = (x_max - (line_width)) / 2;
540 if (config->entry_count < visible_max)
541 y_start = ((visible_max - config->entry_count) / 2) + 1;
542 else
543 y_start = 0;
544
545 /* menu entries title lines */
546 lines = AllocatePool(sizeof(CHAR16 *) * config->entry_count);
547 for (i = 0; i < config->entry_count; i++) {
548 UINTN j, k;
549
550 lines[i] = AllocatePool(((x_max+1) * sizeof(CHAR16)));
551 for (j = 0; j < x_start; j++)
552 lines[i][j] = ' ';
553
554 for (k = 0; config->entries[i]->title_show[k] != '\0' && j < x_max; j++, k++)
555 lines[i][j] = config->entries[i]->title_show[k];
556
557 for (; j < x_max; j++)
558 lines[i][j] = ' ';
559 lines[i][x_max] = '\0';
560 }
561
562 status = NULL;
563 clearline = AllocatePool((x_max+1) * sizeof(CHAR16));
564 for (i = 0; i < x_max; i++)
565 clearline[i] = ' ';
566 clearline[i] = 0;
567
568 while (!exit) {
569 UINT64 key;
570
571 if (refresh) {
572 for (i = 0; i < config->entry_count; i++) {
573 if (i < idx_first || i > idx_last)
574 continue;
575 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + i - idx_first);
576 if (i == idx_highlight)
577 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut,
578 EFI_BLACK|EFI_BACKGROUND_LIGHTGRAY);
579 else
580 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut,
581 EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
582 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[i]);
583 if ((INTN)i == config->idx_default_efivar) {
584 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + i - idx_first);
585 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
586 }
587 }
588 refresh = FALSE;
589 } else if (highlight) {
590 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + idx_highlight_prev - idx_first);
591 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
592 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[idx_highlight_prev]);
593 if ((INTN)idx_highlight_prev == config->idx_default_efivar) {
594 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + idx_highlight_prev - idx_first);
595 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
596 }
597
598 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + idx_highlight - idx_first);
599 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_BLACK|EFI_BACKGROUND_LIGHTGRAY);
600 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[idx_highlight]);
601 if ((INTN)idx_highlight == config->idx_default_efivar) {
602 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + idx_highlight - idx_first);
603 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
604 }
605 highlight = FALSE;
606 }
607
608 if (timeout_remain > 0) {
609 FreePool(status);
610 status = PoolPrint(L"Boot in %d sec.", (timeout_remain + 5) / 10);
611 }
612
613 /* print status at last line of screen */
614 if (status) {
615 UINTN len;
616 UINTN x;
617
618 /* center line */
619 len = StrLen(status);
620 if (len < x_max)
621 x = (x_max - len) / 2;
622 else
623 x = 0;
624 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
625 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
626 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline + (x_max - x));
627 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, status);
628 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1 + x + len);
629 }
630
631 err = console_key_read(&key, wait);
632 if (EFI_ERROR(err)) {
633 /* timeout reached */
634 if (timeout_remain == 0) {
635 exit = TRUE;
636 break;
637 }
638
639 /* sleep and update status */
640 if (timeout_remain > 0) {
641 uefi_call_wrapper(BS->Stall, 1, 100 * 1000);
642 timeout_remain--;
643 continue;
644 }
645
646 /* timeout disabled, wait for next key */
647 wait = TRUE;
648 continue;
649 }
650
651 timeout_remain = -1;
652
653 /* clear status after keystroke */
654 if (status) {
655 FreePool(status);
656 status = NULL;
657 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
658 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
659 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
660 }
661
662 idx_highlight_prev = idx_highlight;
663
664 switch (key) {
665 case KEYPRESS(0, SCAN_UP, 0):
666 case KEYPRESS(0, 0, 'k'):
667 if (idx_highlight > 0)
668 idx_highlight--;
669 break;
670
671 case KEYPRESS(0, SCAN_DOWN, 0):
672 case KEYPRESS(0, 0, 'j'):
673 if (idx_highlight < config->entry_count-1)
674 idx_highlight++;
675 break;
676
677 case KEYPRESS(0, SCAN_HOME, 0):
678 case KEYPRESS(EFI_ALT_PRESSED, 0, '<'):
679 if (idx_highlight > 0) {
680 refresh = TRUE;
681 idx_highlight = 0;
682 }
683 break;
684
685 case KEYPRESS(0, SCAN_END, 0):
686 case KEYPRESS(EFI_ALT_PRESSED, 0, '>'):
687 if (idx_highlight < config->entry_count-1) {
688 refresh = TRUE;
689 idx_highlight = config->entry_count-1;
690 }
691 break;
692
693 case KEYPRESS(0, SCAN_PAGE_UP, 0):
694 if (idx_highlight > visible_max)
695 idx_highlight -= visible_max;
696 else
697 idx_highlight = 0;
698 break;
699
700 case KEYPRESS(0, SCAN_PAGE_DOWN, 0):
701 idx_highlight += visible_max;
702 if (idx_highlight > config->entry_count-1)
703 idx_highlight = config->entry_count-1;
704 break;
705
706 case KEYPRESS(0, 0, CHAR_LINEFEED):
707 case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
708 exit = TRUE;
709 break;
710
711 case KEYPRESS(0, SCAN_F1, 0):
712 case KEYPRESS(0, 0, 'h'):
713 case KEYPRESS(0, 0, '?'):
714 status = StrDuplicate(L"(d)efault, (t/T)timeout, (e)dit, (v)ersion (Q)uit (P)rint (h)elp");
715 break;
716
717 case KEYPRESS(0, 0, 'Q'):
718 exit = TRUE;
719 run = FALSE;
720 break;
721
722 case KEYPRESS(0, 0, 'd'):
723 if (config->idx_default_efivar != (INTN)idx_highlight) {
724 /* store the selected entry in a persistent EFI variable */
725 efivar_set(L"LoaderEntryDefault", config->entries[idx_highlight]->file, TRUE);
726 config->idx_default_efivar = idx_highlight;
727 status = StrDuplicate(L"Default boot entry selected.");
728 } else {
729 /* clear the default entry EFI variable */
730 efivar_set(L"LoaderEntryDefault", NULL, TRUE);
731 config->idx_default_efivar = -1;
732 status = StrDuplicate(L"Default boot entry cleared.");
733 }
734 refresh = TRUE;
735 break;
736
737 case KEYPRESS(0, 0, '-'):
738 case KEYPRESS(0, 0, 'T'):
739 if (config->timeout_sec_efivar > 0) {
740 config->timeout_sec_efivar--;
741 efivar_set_int(L"LoaderConfigTimeout", config->timeout_sec_efivar, TRUE);
742 if (config->timeout_sec_efivar > 0)
743 status = PoolPrint(L"Menu timeout set to %d sec.", config->timeout_sec_efivar);
744 else
745 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
746 } else if (config->timeout_sec_efivar <= 0){
747 config->timeout_sec_efivar = -1;
748 efivar_set(L"LoaderConfigTimeout", NULL, TRUE);
749 if (config->timeout_sec_config > 0)
750 status = PoolPrint(L"Menu timeout of %d sec is defined by configuration file.",
751 config->timeout_sec_config);
752 else
753 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
754 }
755 break;
756
757 case KEYPRESS(0, 0, '+'):
758 case KEYPRESS(0, 0, 't'):
759 if (config->timeout_sec_efivar == -1 && config->timeout_sec_config == 0)
760 config->timeout_sec_efivar++;
761 config->timeout_sec_efivar++;
762 efivar_set_int(L"LoaderConfigTimeout", config->timeout_sec_efivar, TRUE);
763 if (config->timeout_sec_efivar > 0)
764 status = PoolPrint(L"Menu timeout set to %d sec.",
765 config->timeout_sec_efivar);
766 else
767 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
768 break;
769
770 case KEYPRESS(0, 0, 'e'):
771 /* only the options of configured entries can be edited */
772 if (config->no_editor || config->entries[idx_highlight]->type == LOADER_UNDEFINED)
773 break;
774 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
775 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
776 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
777 if (line_edit(config->entries[idx_highlight]->options, &config->options_edit, x_max-1, y_max-1))
778 exit = TRUE;
779 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
780 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
781 break;
782
783 case KEYPRESS(0, 0, 'v'):
784 status = PoolPrint(L"systemd-boot " PACKAGE_VERSION " (" EFI_MACHINE_TYPE_NAME "), UEFI Specification %d.%02d, Vendor %s %d.%02d",
785 ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff,
786 ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
787 break;
788
789 case KEYPRESS(0, 0, 'P'):
790 print_status(config, loaded_image_path);
791 refresh = TRUE;
792 break;
793
794 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'l'):
795 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('l')):
796 refresh = TRUE;
797 break;
798
799 default:
800 /* jump with a hotkey directly to a matching entry */
801 idx = entry_lookup_key(config, idx_highlight+1, KEYCHAR(key));
802 if (idx < 0)
803 break;
804 idx_highlight = idx;
805 refresh = TRUE;
806 }
807
808 if (idx_highlight > idx_last) {
809 idx_last = idx_highlight;
810 idx_first = 1 + idx_highlight - visible_max;
811 refresh = TRUE;
812 } else if (idx_highlight < idx_first) {
813 idx_first = idx_highlight;
814 idx_last = idx_highlight + visible_max-1;
815 refresh = TRUE;
816 }
817
818 if (!refresh && idx_highlight != idx_highlight_prev)
819 highlight = TRUE;
820 }
821
822 *chosen_entry = config->entries[idx_highlight];
823
824 for (i = 0; i < config->entry_count; i++)
825 FreePool(lines[i]);
826 FreePool(lines);
827 FreePool(clearline);
828
829 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_WHITE|EFI_BACKGROUND_BLACK);
830 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
831 return run;
832 }
833
834 static VOID config_add_entry(Config *config, ConfigEntry *entry) {
835 if ((config->entry_count & 15) == 0) {
836 UINTN i;
837
838 i = config->entry_count + 16;
839 if (config->entry_count == 0)
840 config->entries = AllocatePool(sizeof(VOID *) * i);
841 else
842 config->entries = ReallocatePool(config->entries,
843 sizeof(VOID *) * config->entry_count, sizeof(VOID *) * i);
844 }
845 config->entries[config->entry_count++] = entry;
846 }
847
848 static VOID config_entry_free(ConfigEntry *entry) {
849 FreePool(entry->title_show);
850 FreePool(entry->title);
851 FreePool(entry->machine_id);
852 FreePool(entry->loader);
853 FreePool(entry->options);
854 }
855
856 static BOOLEAN is_digit(CHAR16 c) {
857 return (c >= '0') && (c <= '9');
858 }
859
860 static UINTN c_order(CHAR16 c) {
861 if (c == '\0')
862 return 0;
863 if (is_digit(c))
864 return 0;
865 else if ((c >= 'a') && (c <= 'z'))
866 return c;
867 else
868 return c + 0x10000;
869 }
870
871 static INTN str_verscmp(CHAR16 *s1, CHAR16 *s2) {
872 CHAR16 *os1 = s1;
873 CHAR16 *os2 = s2;
874
875 while (*s1 || *s2) {
876 INTN first;
877
878 while ((*s1 && !is_digit(*s1)) || (*s2 && !is_digit(*s2))) {
879 INTN order;
880
881 order = c_order(*s1) - c_order(*s2);
882 if (order)
883 return order;
884 s1++;
885 s2++;
886 }
887
888 while (*s1 == '0')
889 s1++;
890 while (*s2 == '0')
891 s2++;
892
893 first = 0;
894 while (is_digit(*s1) && is_digit(*s2)) {
895 if (first == 0)
896 first = *s1 - *s2;
897 s1++;
898 s2++;
899 }
900
901 if (is_digit(*s1))
902 return 1;
903 if (is_digit(*s2))
904 return -1;
905
906 if (first)
907 return first;
908 }
909
910 return StrCmp(os1, os2);
911 }
912
913 static CHAR8 *line_get_key_value(CHAR8 *content, CHAR8 *sep, UINTN *pos, CHAR8 **key_ret, CHAR8 **value_ret) {
914 CHAR8 *line;
915 UINTN linelen;
916 CHAR8 *value;
917
918 skip:
919 line = content + *pos;
920 if (*line == '\0')
921 return NULL;
922
923 linelen = 0;
924 while (line[linelen] && !strchra((CHAR8 *)"\n\r", line[linelen]))
925 linelen++;
926
927 /* move pos to next line */
928 *pos += linelen;
929 if (content[*pos])
930 (*pos)++;
931
932 /* empty line */
933 if (linelen == 0)
934 goto skip;
935
936 /* terminate line */
937 line[linelen] = '\0';
938
939 /* remove leading whitespace */
940 while (strchra((CHAR8 *)" \t", *line)) {
941 line++;
942 linelen--;
943 }
944
945 /* remove trailing whitespace */
946 while (linelen > 0 && strchra(sep, line[linelen-1]))
947 linelen--;
948 line[linelen] = '\0';
949
950 if (*line == '#')
951 goto skip;
952
953 /* split key/value */
954 value = line;
955 while (*value && !strchra(sep, *value))
956 value++;
957 if (*value == '\0')
958 goto skip;
959 *value = '\0';
960 value++;
961 while (*value && strchra(sep, *value))
962 value++;
963
964 /* unquote */
965 if (value[0] == '\"' && line[linelen-1] == '\"') {
966 value++;
967 line[linelen-1] = '\0';
968 }
969
970 *key_ret = line;
971 *value_ret = value;
972 return line;
973 }
974
975 static VOID config_defaults_load_from_file(Config *config, CHAR8 *content) {
976 CHAR8 *line;
977 UINTN pos = 0;
978 CHAR8 *key, *value;
979
980 line = content;
981 while ((line = line_get_key_value(content, (CHAR8 *)" \t", &pos, &key, &value))) {
982 if (strcmpa((CHAR8 *)"timeout", key) == 0) {
983 CHAR16 *s;
984
985 s = stra_to_str(value);
986 config->timeout_sec_config = Atoi(s);
987 config->timeout_sec = config->timeout_sec_config;
988 FreePool(s);
989 continue;
990 }
991
992 if (strcmpa((CHAR8 *)"default", key) == 0) {
993 FreePool(config->entry_default_pattern);
994 config->entry_default_pattern = stra_to_str(value);
995 StrLwr(config->entry_default_pattern);
996 continue;
997 }
998
999 if (strcmpa((CHAR8 *)"editor", key) == 0) {
1000 BOOLEAN on;
1001
1002 if (EFI_ERROR(parse_boolean(value, &on)))
1003 continue;
1004 config->no_editor = !on;
1005 }
1006 }
1007 }
1008
1009 static VOID config_entry_add_from_file(Config *config, EFI_HANDLE *device, CHAR16 *file, CHAR8 *content, CHAR16 *loaded_image_path) {
1010 ConfigEntry *entry;
1011 CHAR8 *line;
1012 UINTN pos = 0;
1013 CHAR8 *key, *value;
1014 UINTN len;
1015 CHAR16 *initrd = NULL;
1016
1017 entry = AllocateZeroPool(sizeof(ConfigEntry));
1018
1019 line = content;
1020 while ((line = line_get_key_value(content, (CHAR8 *)" \t", &pos, &key, &value))) {
1021 if (strcmpa((CHAR8 *)"title", key) == 0) {
1022 FreePool(entry->title);
1023 entry->title = stra_to_str(value);
1024 continue;
1025 }
1026
1027 if (strcmpa((CHAR8 *)"version", key) == 0) {
1028 FreePool(entry->version);
1029 entry->version = stra_to_str(value);
1030 continue;
1031 }
1032
1033 if (strcmpa((CHAR8 *)"machine-id", key) == 0) {
1034 FreePool(entry->machine_id);
1035 entry->machine_id = stra_to_str(value);
1036 continue;
1037 }
1038
1039 if (strcmpa((CHAR8 *)"linux", key) == 0) {
1040 FreePool(entry->loader);
1041 entry->type = LOADER_LINUX;
1042 entry->loader = stra_to_path(value);
1043 entry->key = 'l';
1044 continue;
1045 }
1046
1047 if (strcmpa((CHAR8 *)"efi", key) == 0) {
1048 entry->type = LOADER_EFI;
1049 FreePool(entry->loader);
1050 entry->loader = stra_to_path(value);
1051
1052 /* do not add an entry for ourselves */
1053 if (StriCmp(entry->loader, loaded_image_path) == 0) {
1054 entry->type = LOADER_UNDEFINED;
1055 break;
1056 }
1057 continue;
1058 }
1059
1060 if (strcmpa((CHAR8 *)"architecture", key) == 0) {
1061 /* do not add an entry for an EFI image of architecture not matching with that of the image */
1062 if (strcmpa((CHAR8 *)EFI_MACHINE_TYPE_NAME, value) != 0) {
1063 entry->type = LOADER_UNDEFINED;
1064 break;
1065 }
1066 continue;
1067 }
1068
1069 if (strcmpa((CHAR8 *)"initrd", key) == 0) {
1070 CHAR16 *new;
1071
1072 new = stra_to_path(value);
1073 if (initrd) {
1074 CHAR16 *s;
1075
1076 s = PoolPrint(L"%s initrd=%s", initrd, new);
1077 FreePool(initrd);
1078 initrd = s;
1079 } else
1080 initrd = PoolPrint(L"initrd=%s", new);
1081 FreePool(new);
1082 continue;
1083 }
1084
1085 if (strcmpa((CHAR8 *)"options", key) == 0) {
1086 CHAR16 *new;
1087
1088 new = stra_to_str(value);
1089 if (entry->options) {
1090 CHAR16 *s;
1091
1092 s = PoolPrint(L"%s %s", entry->options, new);
1093 FreePool(entry->options);
1094 entry->options = s;
1095 } else {
1096 entry->options = new;
1097 new = NULL;
1098 }
1099 FreePool(new);
1100 continue;
1101 }
1102 }
1103
1104 if (entry->type == LOADER_UNDEFINED) {
1105 config_entry_free(entry);
1106 FreePool(initrd);
1107 FreePool(entry);
1108 return;
1109 }
1110
1111 /* add initrd= to options */
1112 if (entry->type == LOADER_LINUX && initrd) {
1113 if (entry->options) {
1114 CHAR16 *s;
1115
1116 s = PoolPrint(L"%s %s", initrd, entry->options);
1117 FreePool(entry->options);
1118 entry->options = s;
1119 } else {
1120 entry->options = initrd;
1121 initrd = NULL;
1122 }
1123 }
1124 FreePool(initrd);
1125
1126 entry->device = device;
1127 entry->file = StrDuplicate(file);
1128 len = StrLen(entry->file);
1129 /* remove ".conf" */
1130 if (len > 5)
1131 entry->file[len - 5] = '\0';
1132 StrLwr(entry->file);
1133
1134 config_add_entry(config, entry);
1135 }
1136
1137 static VOID config_load_defaults(Config *config, EFI_FILE *root_dir) {
1138 CHAR8 *content = NULL;
1139 UINTN sec;
1140 UINTN len;
1141 EFI_STATUS err;
1142
1143 len = file_read(root_dir, L"\\loader\\loader.conf", 0, 0, &content);
1144 if (len > 0)
1145 config_defaults_load_from_file(config, content);
1146 FreePool(content);
1147
1148 err = efivar_get_int(L"LoaderConfigTimeout", &sec);
1149 if (!EFI_ERROR(err)) {
1150 config->timeout_sec_efivar = sec;
1151 config->timeout_sec = sec;
1152 } else
1153 config->timeout_sec_efivar = -1;
1154 }
1155
1156 static VOID config_load_entries(Config *config, EFI_HANDLE *device, EFI_FILE *root_dir, CHAR16 *loaded_image_path) {
1157 EFI_FILE_HANDLE entries_dir;
1158 EFI_STATUS err;
1159
1160 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &entries_dir, L"\\loader\\entries", EFI_FILE_MODE_READ, 0ULL);
1161 if (!EFI_ERROR(err)) {
1162 for (;;) {
1163 CHAR16 buf[256];
1164 UINTN bufsize;
1165 EFI_FILE_INFO *f;
1166 CHAR8 *content = NULL;
1167 UINTN len;
1168
1169 bufsize = sizeof(buf);
1170 err = uefi_call_wrapper(entries_dir->Read, 3, entries_dir, &bufsize, buf);
1171 if (bufsize == 0 || EFI_ERROR(err))
1172 break;
1173
1174 f = (EFI_FILE_INFO *) buf;
1175 if (f->FileName[0] == '.')
1176 continue;
1177 if (f->Attribute & EFI_FILE_DIRECTORY)
1178 continue;
1179
1180 len = StrLen(f->FileName);
1181 if (len < 6)
1182 continue;
1183 if (StriCmp(f->FileName + len - 5, L".conf") != 0)
1184 continue;
1185 if (StrnCmp(f->FileName, L"auto-", 5) == 0)
1186 continue;
1187
1188 len = file_read(entries_dir, f->FileName, 0, 0, &content);
1189 if (len > 0)
1190 config_entry_add_from_file(config, device, f->FileName, content, loaded_image_path);
1191 FreePool(content);
1192 }
1193 uefi_call_wrapper(entries_dir->Close, 1, entries_dir);
1194 }
1195 }
1196
1197 static VOID config_sort_entries(Config *config) {
1198 UINTN i;
1199
1200 for (i = 1; i < config->entry_count; i++) {
1201 BOOLEAN more;
1202 UINTN k;
1203
1204 more = FALSE;
1205 for (k = 0; k < config->entry_count - i; k++) {
1206 ConfigEntry *entry;
1207
1208 if (str_verscmp(config->entries[k]->file, config->entries[k+1]->file) <= 0)
1209 continue;
1210 entry = config->entries[k];
1211 config->entries[k] = config->entries[k+1];
1212 config->entries[k+1] = entry;
1213 more = TRUE;
1214 }
1215 if (!more)
1216 break;
1217 }
1218 }
1219
1220 static VOID config_default_entry_select(Config *config) {
1221 CHAR16 *var;
1222 EFI_STATUS err;
1223 UINTN i;
1224
1225 /*
1226 * The EFI variable to specify a boot entry for the next, and only the
1227 * next reboot. The variable is always cleared directly after it is read.
1228 */
1229 err = efivar_get(L"LoaderEntryOneShot", &var);
1230 if (!EFI_ERROR(err)) {
1231 BOOLEAN found = FALSE;
1232
1233 for (i = 0; i < config->entry_count; i++) {
1234 if (StrCmp(config->entries[i]->file, var) == 0) {
1235 config->idx_default = i;
1236 found = TRUE;
1237 break;
1238 }
1239 }
1240
1241 config->entry_oneshot = StrDuplicate(var);
1242 efivar_set(L"LoaderEntryOneShot", NULL, TRUE);
1243 FreePool(var);
1244 if (found)
1245 return;
1246 }
1247
1248 /*
1249 * The EFI variable to select the default boot entry overrides the
1250 * configured pattern. The variable can be set and cleared by pressing
1251 * the 'd' key in the loader selection menu, the entry is marked with
1252 * an '*'.
1253 */
1254 err = efivar_get(L"LoaderEntryDefault", &var);
1255 if (!EFI_ERROR(err)) {
1256 BOOLEAN found = FALSE;
1257
1258 for (i = 0; i < config->entry_count; i++) {
1259 if (StrCmp(config->entries[i]->file, var) == 0) {
1260 config->idx_default = i;
1261 config->idx_default_efivar = i;
1262 found = TRUE;
1263 break;
1264 }
1265 }
1266 FreePool(var);
1267 if (found)
1268 return;
1269 }
1270 config->idx_default_efivar = -1;
1271
1272 if (config->entry_count == 0)
1273 return;
1274
1275 /*
1276 * Match the pattern from the end of the list to the start, find last
1277 * entry (largest number) matching the given pattern.
1278 */
1279 if (config->entry_default_pattern) {
1280 i = config->entry_count;
1281 while (i--) {
1282 if (config->entries[i]->no_autoselect)
1283 continue;
1284 if (MetaiMatch(config->entries[i]->file, config->entry_default_pattern)) {
1285 config->idx_default = i;
1286 return;
1287 }
1288 }
1289 }
1290
1291 /* select the last suitable entry */
1292 i = config->entry_count;
1293 while (i--) {
1294 if (config->entries[i]->no_autoselect)
1295 continue;
1296 config->idx_default = i;
1297 return;
1298 }
1299
1300 /* no entry found */
1301 config->idx_default = -1;
1302 }
1303
1304 /* generate a unique title, avoiding non-distinguishable menu entries */
1305 static VOID config_title_generate(Config *config) {
1306 UINTN i, k;
1307 BOOLEAN unique;
1308
1309 /* set title */
1310 for (i = 0; i < config->entry_count; i++) {
1311 CHAR16 *title;
1312
1313 FreePool(config->entries[i]->title_show);
1314 title = config->entries[i]->title;
1315 if (!title)
1316 title = config->entries[i]->file;
1317 config->entries[i]->title_show = StrDuplicate(title);
1318 }
1319
1320 unique = TRUE;
1321 for (i = 0; i < config->entry_count; i++) {
1322 for (k = 0; k < config->entry_count; k++) {
1323 if (i == k)
1324 continue;
1325 if (StrCmp(config->entries[i]->title_show, config->entries[k]->title_show) != 0)
1326 continue;
1327
1328 unique = FALSE;
1329 config->entries[i]->non_unique = TRUE;
1330 config->entries[k]->non_unique = TRUE;
1331 }
1332 }
1333 if (unique)
1334 return;
1335
1336 /* add version to non-unique titles */
1337 for (i = 0; i < config->entry_count; i++) {
1338 CHAR16 *s;
1339
1340 if (!config->entries[i]->non_unique)
1341 continue;
1342 if (!config->entries[i]->version)
1343 continue;
1344
1345 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, config->entries[i]->version);
1346 FreePool(config->entries[i]->title_show);
1347 config->entries[i]->title_show = s;
1348 config->entries[i]->non_unique = FALSE;
1349 }
1350
1351 unique = TRUE;
1352 for (i = 0; i < config->entry_count; i++) {
1353 for (k = 0; k < config->entry_count; k++) {
1354 if (i == k)
1355 continue;
1356 if (StrCmp(config->entries[i]->title_show, config->entries[k]->title_show) != 0)
1357 continue;
1358
1359 unique = FALSE;
1360 config->entries[i]->non_unique = TRUE;
1361 config->entries[k]->non_unique = TRUE;
1362 }
1363 }
1364 if (unique)
1365 return;
1366
1367 /* add machine-id to non-unique titles */
1368 for (i = 0; i < config->entry_count; i++) {
1369 CHAR16 *s;
1370 CHAR16 *m;
1371
1372 if (!config->entries[i]->non_unique)
1373 continue;
1374 if (!config->entries[i]->machine_id)
1375 continue;
1376
1377 m = StrDuplicate(config->entries[i]->machine_id);
1378 m[8] = '\0';
1379 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, m);
1380 FreePool(config->entries[i]->title_show);
1381 config->entries[i]->title_show = s;
1382 config->entries[i]->non_unique = FALSE;
1383 FreePool(m);
1384 }
1385
1386 unique = TRUE;
1387 for (i = 0; i < config->entry_count; i++) {
1388 for (k = 0; k < config->entry_count; k++) {
1389 if (i == k)
1390 continue;
1391 if (StrCmp(config->entries[i]->title_show, config->entries[k]->title_show) != 0)
1392 continue;
1393
1394 unique = FALSE;
1395 config->entries[i]->non_unique = TRUE;
1396 config->entries[k]->non_unique = TRUE;
1397 }
1398 }
1399 if (unique)
1400 return;
1401
1402 /* add file name to non-unique titles */
1403 for (i = 0; i < config->entry_count; i++) {
1404 CHAR16 *s;
1405
1406 if (!config->entries[i]->non_unique)
1407 continue;
1408 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, config->entries[i]->file);
1409 FreePool(config->entries[i]->title_show);
1410 config->entries[i]->title_show = s;
1411 config->entries[i]->non_unique = FALSE;
1412 }
1413 }
1414
1415 static BOOLEAN config_entry_add_call(Config *config, CHAR16 *title, EFI_STATUS (*call)(VOID)) {
1416 ConfigEntry *entry;
1417
1418 entry = AllocateZeroPool(sizeof(ConfigEntry));
1419 entry->title = StrDuplicate(title);
1420 entry->call = call;
1421 entry->no_autoselect = TRUE;
1422 config_add_entry(config, entry);
1423 return TRUE;
1424 }
1425
1426 static ConfigEntry *config_entry_add_loader(Config *config, EFI_HANDLE *device,
1427 enum loader_type type,CHAR16 *file, CHAR16 key, CHAR16 *title, CHAR16 *loader) {
1428 ConfigEntry *entry;
1429
1430 entry = AllocateZeroPool(sizeof(ConfigEntry));
1431 entry->type = type;
1432 entry->title = StrDuplicate(title);
1433 entry->device = device;
1434 entry->loader = StrDuplicate(loader);
1435 entry->file = StrDuplicate(file);
1436 StrLwr(entry->file);
1437 entry->key = key;
1438 config_add_entry(config, entry);
1439
1440 return entry;
1441 }
1442
1443 static BOOLEAN config_entry_add_loader_auto(Config *config, EFI_HANDLE *device, EFI_FILE *root_dir, CHAR16 *loaded_image_path,
1444 CHAR16 *file, CHAR16 key, CHAR16 *title, CHAR16 *loader) {
1445 EFI_FILE_HANDLE handle;
1446 ConfigEntry *entry;
1447 EFI_STATUS err;
1448
1449 /* do not add an entry for ourselves */
1450 if (loaded_image_path && StriCmp(loader, loaded_image_path) == 0)
1451 return FALSE;
1452
1453 /* check existence */
1454 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &handle, loader, EFI_FILE_MODE_READ, 0ULL);
1455 if (EFI_ERROR(err))
1456 return FALSE;
1457 uefi_call_wrapper(handle->Close, 1, handle);
1458
1459 entry = config_entry_add_loader(config, device, LOADER_UNDEFINED, file, key, title, loader);
1460 if (!entry)
1461 return FALSE;
1462
1463 /* do not boot right away into auto-detected entries */
1464 entry->no_autoselect = TRUE;
1465
1466 return TRUE;
1467 }
1468
1469 static VOID config_entry_add_osx(Config *config) {
1470 EFI_STATUS err;
1471 UINTN handle_count = 0;
1472 EFI_HANDLE *handles = NULL;
1473
1474 err = LibLocateHandle(ByProtocol, &FileSystemProtocol, NULL, &handle_count, &handles);
1475 if (!EFI_ERROR(err)) {
1476 UINTN i;
1477
1478 for (i = 0; i < handle_count; i++) {
1479 EFI_FILE *root;
1480 BOOLEAN found;
1481
1482 root = LibOpenRoot(handles[i]);
1483 if (!root)
1484 continue;
1485 found = config_entry_add_loader_auto(config, handles[i], root, NULL, L"auto-osx", 'a', L"macOS",
1486 L"\\System\\Library\\CoreServices\\boot.efi");
1487 uefi_call_wrapper(root->Close, 1, root);
1488 if (found)
1489 break;
1490 }
1491
1492 FreePool(handles);
1493 }
1494 }
1495
1496 static VOID config_entry_add_linux( Config *config, EFI_LOADED_IMAGE *loaded_image, EFI_FILE *root_dir) {
1497 EFI_FILE_HANDLE linux_dir;
1498 EFI_STATUS err;
1499 ConfigEntry *entry;
1500
1501 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &linux_dir, L"\\EFI\\Linux", EFI_FILE_MODE_READ, 0ULL);
1502 if (!EFI_ERROR(err)) {
1503 for (;;) {
1504 CHAR16 buf[256];
1505 UINTN bufsize;
1506 EFI_FILE_INFO *f;
1507 CHAR8 *sections[] = {
1508 (UINT8 *)".osrel",
1509 (UINT8 *)".cmdline",
1510 NULL
1511 };
1512 UINTN offs[ELEMENTSOF(sections)-1] = {};
1513 UINTN szs[ELEMENTSOF(sections)-1] = {};
1514 UINTN addrs[ELEMENTSOF(sections)-1] = {};
1515 CHAR8 *content = NULL;
1516 UINTN len;
1517 CHAR8 *line;
1518 UINTN pos = 0;
1519 CHAR8 *key, *value;
1520 CHAR16 *os_name = NULL;
1521 CHAR16 *os_id = NULL;
1522 CHAR16 *os_version = NULL;
1523 CHAR16 *os_build = NULL;
1524
1525 bufsize = sizeof(buf);
1526 err = uefi_call_wrapper(linux_dir->Read, 3, linux_dir, &bufsize, buf);
1527 if (bufsize == 0 || EFI_ERROR(err))
1528 break;
1529
1530 f = (EFI_FILE_INFO *) buf;
1531 if (f->FileName[0] == '.')
1532 continue;
1533 if (f->Attribute & EFI_FILE_DIRECTORY)
1534 continue;
1535 len = StrLen(f->FileName);
1536 if (len < 5)
1537 continue;
1538 if (StriCmp(f->FileName + len - 4, L".efi") != 0)
1539 continue;
1540
1541 /* look for .osrel and .cmdline sections in the .efi binary */
1542 err = pefile_locate_sections(linux_dir, f->FileName, sections, addrs, offs, szs);
1543 if (EFI_ERROR(err))
1544 continue;
1545
1546 len = file_read(linux_dir, f->FileName, offs[0], szs[0], &content);
1547 if (len <= 0)
1548 continue;
1549
1550 /* read properties from the embedded os-release file */
1551 line = content;
1552 while ((line = line_get_key_value(content, (CHAR8 *)"=", &pos, &key, &value))) {
1553 if (strcmpa((CHAR8 *)"PRETTY_NAME", key) == 0) {
1554 FreePool(os_name);
1555 os_name = stra_to_str(value);
1556 continue;
1557 }
1558
1559 if (strcmpa((CHAR8 *)"ID", key) == 0) {
1560 FreePool(os_id);
1561 os_id = stra_to_str(value);
1562 continue;
1563 }
1564
1565 if (strcmpa((CHAR8 *)"VERSION_ID", key) == 0) {
1566 FreePool(os_version);
1567 os_version = stra_to_str(value);
1568 continue;
1569 }
1570
1571 if (strcmpa((CHAR8 *)"BUILD_ID", key) == 0) {
1572 FreePool(os_build);
1573 os_build = stra_to_str(value);
1574 continue;
1575 }
1576 }
1577
1578 if (os_name && os_id && (os_version || os_build)) {
1579 CHAR16 *conf;
1580 CHAR16 *path;
1581 CHAR16 *cmdline;
1582
1583 conf = PoolPrint(L"%s-%s", os_id, os_version ? : os_build);
1584 path = PoolPrint(L"\\EFI\\Linux\\%s", f->FileName);
1585 entry = config_entry_add_loader(config, loaded_image->DeviceHandle, LOADER_LINUX, conf, 'l', os_name, path);
1586
1587 FreePool(content);
1588 /* read the embedded cmdline file */
1589 len = file_read(linux_dir, f->FileName, offs[1], szs[1] - 1 , &content);
1590 if (len > 0) {
1591 cmdline = stra_to_str(content);
1592 entry->options = cmdline;
1593 cmdline = NULL;
1594 }
1595 FreePool(cmdline);
1596 FreePool(conf);
1597 FreePool(path);
1598 }
1599
1600 FreePool(os_name);
1601 FreePool(os_id);
1602 FreePool(os_version);
1603 FreePool(os_build);
1604 FreePool(content);
1605 }
1606 uefi_call_wrapper(linux_dir->Close, 1, linux_dir);
1607 }
1608 }
1609
1610 static EFI_STATUS image_start(EFI_HANDLE parent_image, const Config *config, const ConfigEntry *entry) {
1611 EFI_HANDLE image;
1612 EFI_DEVICE_PATH *path;
1613 CHAR16 *options;
1614 EFI_STATUS err;
1615
1616 path = FileDevicePath(entry->device, entry->loader);
1617 if (!path) {
1618 Print(L"Error getting device path.");
1619 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1620 return EFI_INVALID_PARAMETER;
1621 }
1622
1623 err = uefi_call_wrapper(BS->LoadImage, 6, FALSE, parent_image, path, NULL, 0, &image);
1624 if (EFI_ERROR(err)) {
1625 Print(L"Error loading %s: %r", entry->loader, err);
1626 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1627 goto out;
1628 }
1629
1630 if (config->options_edit)
1631 options = config->options_edit;
1632 else if (entry->options)
1633 options = entry->options;
1634 else
1635 options = NULL;
1636 if (options) {
1637 EFI_LOADED_IMAGE *loaded_image;
1638
1639 err = uefi_call_wrapper(BS->OpenProtocol, 6, image, &LoadedImageProtocol, (VOID **)&loaded_image,
1640 parent_image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
1641 if (EFI_ERROR(err)) {
1642 Print(L"Error getting LoadedImageProtocol handle: %r", err);
1643 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1644 goto out_unload;
1645 }
1646 loaded_image->LoadOptions = options;
1647 loaded_image->LoadOptionsSize = (StrLen(loaded_image->LoadOptions)+1) * sizeof(CHAR16);
1648
1649 #ifdef SD_BOOT_LOG_TPM
1650 /* Try to log any options to the TPM, especially to catch manually edited options */
1651 err = tpm_log_event(SD_TPM_PCR,
1652 (EFI_PHYSICAL_ADDRESS) loaded_image->LoadOptions,
1653 loaded_image->LoadOptionsSize, loaded_image->LoadOptions);
1654 if (EFI_ERROR(err)) {
1655 Print(L"Unable to add image options measurement: %r", err);
1656 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1657 return err;
1658 }
1659 #endif
1660 }
1661
1662 efivar_set_time_usec(L"LoaderTimeExecUSec", 0);
1663 err = uefi_call_wrapper(BS->StartImage, 3, image, NULL, NULL);
1664 out_unload:
1665 uefi_call_wrapper(BS->UnloadImage, 1, image);
1666 out:
1667 FreePool(path);
1668 return err;
1669 }
1670
1671 static EFI_STATUS reboot_into_firmware(VOID) {
1672 CHAR8 *b;
1673 UINTN size;
1674 UINT64 osind;
1675 EFI_STATUS err;
1676
1677 osind = EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
1678
1679 err = efivar_get_raw(&global_guid, L"OsIndications", &b, &size);
1680 if (!EFI_ERROR(err))
1681 osind |= (UINT64)*b;
1682 FreePool(b);
1683
1684 err = efivar_set_raw(&global_guid, L"OsIndications", (CHAR8 *)&osind, sizeof(UINT64), TRUE);
1685 if (EFI_ERROR(err))
1686 return err;
1687
1688 err = uefi_call_wrapper(RT->ResetSystem, 4, EfiResetCold, EFI_SUCCESS, 0, NULL);
1689 Print(L"Error calling ResetSystem: %r", err);
1690 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1691 return err;
1692 }
1693
1694 static VOID config_free(Config *config) {
1695 UINTN i;
1696
1697 for (i = 0; i < config->entry_count; i++)
1698 config_entry_free(config->entries[i]);
1699 FreePool(config->entries);
1700 FreePool(config->entry_default_pattern);
1701 FreePool(config->options_edit);
1702 FreePool(config->entry_oneshot);
1703 }
1704
1705 EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *sys_table) {
1706 CHAR16 *s;
1707 CHAR8 *b;
1708 UINTN size;
1709 EFI_LOADED_IMAGE *loaded_image;
1710 EFI_FILE *root_dir;
1711 CHAR16 *loaded_image_path;
1712 EFI_STATUS err;
1713 Config config;
1714 UINT64 init_usec;
1715 BOOLEAN menu = FALSE;
1716 CHAR16 uuid[37];
1717
1718 InitializeLib(image, sys_table);
1719 init_usec = time_usec();
1720 efivar_set_time_usec(L"LoaderTimeInitUSec", init_usec);
1721 efivar_set(L"LoaderInfo", L"systemd-boot " PACKAGE_VERSION, FALSE);
1722 s = PoolPrint(L"%s %d.%02d", ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1723 efivar_set(L"LoaderFirmwareInfo", s, FALSE);
1724 FreePool(s);
1725 s = PoolPrint(L"UEFI %d.%02d", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
1726 efivar_set(L"LoaderFirmwareType", s, FALSE);
1727 FreePool(s);
1728
1729 err = uefi_call_wrapper(BS->OpenProtocol, 6, image, &LoadedImageProtocol, (VOID **)&loaded_image,
1730 image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
1731 if (EFI_ERROR(err)) {
1732 Print(L"Error getting a LoadedImageProtocol handle: %r ", err);
1733 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1734 return err;
1735 }
1736
1737 /* export the device path this image is started from */
1738 if (disk_get_part_uuid(loaded_image->DeviceHandle, uuid) == EFI_SUCCESS)
1739 efivar_set(L"LoaderDevicePartUUID", uuid, FALSE);
1740
1741 root_dir = LibOpenRoot(loaded_image->DeviceHandle);
1742 if (!root_dir) {
1743 Print(L"Unable to open root directory: %r ", err);
1744 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1745 return EFI_LOAD_ERROR;
1746 }
1747
1748
1749 /* the filesystem path to this image, to prevent adding ourselves to the menu */
1750 loaded_image_path = DevicePathToStr(loaded_image->FilePath);
1751 efivar_set(L"LoaderImageIdentifier", loaded_image_path, FALSE);
1752
1753 ZeroMem(&config, sizeof(Config));
1754 config_load_defaults(&config, root_dir);
1755
1756 /* scan /EFI/Linux/ directory */
1757 config_entry_add_linux(&config, loaded_image, root_dir);
1758
1759 /* scan /loader/entries/\*.conf files */
1760 config_load_entries(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
1761
1762 /* sort entries after version number */
1763 config_sort_entries(&config);
1764
1765 /* if we find some well-known loaders, add them to the end of the list */
1766 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
1767 L"auto-windows", 'w', L"Windows Boot Manager", L"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
1768 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
1769 L"auto-efi-shell", 's', L"EFI Shell", L"\\shell" EFI_MACHINE_TYPE_NAME ".efi");
1770 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
1771 L"auto-efi-default", '\0', L"EFI Default Loader", L"\\EFI\\Boot\\boot" EFI_MACHINE_TYPE_NAME ".efi");
1772 config_entry_add_osx(&config);
1773
1774 if (efivar_get_raw(&global_guid, L"OsIndicationsSupported", &b, &size) == EFI_SUCCESS) {
1775 UINT64 osind = (UINT64)*b;
1776
1777 if (osind & EFI_OS_INDICATIONS_BOOT_TO_FW_UI)
1778 config_entry_add_call(&config, L"Reboot Into Firmware Interface", reboot_into_firmware);
1779 FreePool(b);
1780 }
1781
1782 if (config.entry_count == 0) {
1783 Print(L"No loader found. Configuration files in \\loader\\entries\\*.conf are needed.");
1784 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1785 goto out;
1786 }
1787
1788 config_title_generate(&config);
1789
1790 /* select entry by configured pattern or EFI LoaderDefaultEntry= variable */
1791 config_default_entry_select(&config);
1792
1793 /* if no configured entry to select from was found, enable the menu */
1794 if (config.idx_default == -1) {
1795 config.idx_default = 0;
1796 if (config.timeout_sec == 0)
1797 config.timeout_sec = 10;
1798 }
1799
1800 /* select entry or show menu when key is pressed or timeout is set */
1801 if (config.timeout_sec == 0) {
1802 UINT64 key;
1803
1804 err = console_key_read(&key, FALSE);
1805 if (!EFI_ERROR(err)) {
1806 INT16 idx;
1807
1808 /* find matching key in config entries */
1809 idx = entry_lookup_key(&config, config.idx_default, KEYCHAR(key));
1810 if (idx >= 0)
1811 config.idx_default = idx;
1812 else
1813 menu = TRUE;
1814 }
1815 } else
1816 menu = TRUE;
1817
1818 for (;;) {
1819 ConfigEntry *entry;
1820
1821 entry = config.entries[config.idx_default];
1822 if (menu) {
1823 efivar_set_time_usec(L"LoaderTimeMenuUSec", 0);
1824 uefi_call_wrapper(BS->SetWatchdogTimer, 4, 0, 0x10000, 0, NULL);
1825 if (!menu_run(&config, &entry, loaded_image_path))
1826 break;
1827
1828 /* run special entry like "reboot" */
1829 if (entry->call) {
1830 entry->call();
1831 continue;
1832 }
1833 }
1834
1835 /* export the selected boot entry to the system */
1836 efivar_set(L"LoaderEntrySelected", entry->file, FALSE);
1837
1838 uefi_call_wrapper(BS->SetWatchdogTimer, 4, 5 * 60, 0x10000, 0, NULL);
1839 err = image_start(image, &config, entry);
1840 if (EFI_ERROR(err)) {
1841 graphics_mode(FALSE);
1842 Print(L"\nFailed to execute %s (%s): %r\n", entry->title, entry->loader, err);
1843 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1844 goto out;
1845 }
1846
1847 menu = TRUE;
1848 config.timeout_sec = 0;
1849 }
1850 err = EFI_SUCCESS;
1851 out:
1852 FreePool(loaded_image_path);
1853 config_free(&config);
1854 uefi_call_wrapper(root_dir->Close, 1, root_dir);
1855 uefi_call_wrapper(BS->CloseProtocol, 4, image, &LoadedImageProtocol, image, NULL);
1856 return err;
1857 }