]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/boot/efi/boot.c
Merge branch 'master' of github.com:systemd/systemd
[thirdparty/systemd.git] / src / boot / efi / boot.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /*
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU Lesser General Public License as published by
6 * the Free Software Foundation; either version 2.1 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * Copyright (C) 2012-2015 Kay Sievers <kay@vrfy.org>
15 * Copyright (C) 2012-2015 Harald Hoyer <harald@redhat.com>
16 */
17
18 #include <efi.h>
19 #include <efilib.h>
20
21 #include "util.h"
22 #include "console.h"
23 #include "graphics.h"
24 #include "pefile.h"
25 #include "disk.h"
26 #include "linux.h"
27
28 #ifndef EFI_OS_INDICATIONS_BOOT_TO_FW_UI
29 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001ULL
30 #endif
31
32 /* magic string to find in the binary image */
33 static const char __attribute__((used)) magic[] = "#### LoaderInfo: systemd-boot " VERSION " ####";
34
35 static const EFI_GUID global_guid = EFI_GLOBAL_VARIABLE;
36
37 enum loader_type {
38 LOADER_UNDEFINED,
39 LOADER_EFI,
40 LOADER_LINUX
41 };
42
43 typedef struct {
44 CHAR16 *file;
45 CHAR16 *title_show;
46 CHAR16 *title;
47 CHAR16 *version;
48 CHAR16 *machine_id;
49 EFI_HANDLE *device;
50 enum loader_type type;
51 CHAR16 *loader;
52 CHAR16 *options;
53 CHAR16 key;
54 EFI_STATUS (*call)(VOID);
55 BOOLEAN no_autoselect;
56 BOOLEAN non_unique;
57 } ConfigEntry;
58
59 typedef struct {
60 ConfigEntry **entries;
61 UINTN entry_count;
62 INTN idx_default;
63 INTN idx_default_efivar;
64 UINTN timeout_sec;
65 UINTN timeout_sec_config;
66 INTN timeout_sec_efivar;
67 CHAR16 *entry_default_pattern;
68 CHAR16 *entry_oneshot;
69 CHAR16 *options_edit;
70 BOOLEAN no_editor;
71 } Config;
72
73 static VOID cursor_left(UINTN *cursor, UINTN *first)
74 {
75 if ((*cursor) > 0)
76 (*cursor)--;
77 else if ((*first) > 0)
78 (*first)--;
79 }
80
81 static VOID cursor_right(UINTN *cursor, UINTN *first, UINTN x_max, UINTN len)
82 {
83 if ((*cursor)+1 < x_max)
84 (*cursor)++;
85 else if ((*first) + (*cursor) < len)
86 (*first)++;
87 }
88
89 static BOOLEAN line_edit(CHAR16 *line_in, CHAR16 **line_out, UINTN x_max, UINTN y_pos) {
90 CHAR16 *line;
91 UINTN size;
92 UINTN len;
93 UINTN first;
94 CHAR16 *print;
95 UINTN cursor;
96 UINTN clear;
97 BOOLEAN exit;
98 BOOLEAN enter;
99
100 if (!line_in)
101 line_in = L"";
102 size = StrLen(line_in) + 1024;
103 line = AllocatePool(size * sizeof(CHAR16));
104 StrCpy(line, line_in);
105 len = StrLen(line);
106 print = AllocatePool((x_max+1) * sizeof(CHAR16));
107
108 uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, TRUE);
109
110 first = 0;
111 cursor = 0;
112 clear = 0;
113 enter = FALSE;
114 exit = FALSE;
115 while (!exit) {
116 EFI_STATUS err;
117 UINT64 key;
118 UINTN i;
119
120 i = len - first;
121 if (i >= x_max-1)
122 i = x_max-1;
123 CopyMem(print, line + first, i * sizeof(CHAR16));
124 while (clear > 0 && i < x_max-1) {
125 clear--;
126 print[i++] = ' ';
127 }
128 print[i] = '\0';
129
130 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_pos);
131 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, print);
132 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
133
134 err = console_key_read(&key, TRUE);
135 if (EFI_ERROR(err))
136 continue;
137
138 switch (key) {
139 case KEYPRESS(0, SCAN_ESC, 0):
140 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'c'):
141 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'g'):
142 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('c')):
143 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('g')):
144 exit = TRUE;
145 break;
146
147 case KEYPRESS(0, SCAN_HOME, 0):
148 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'a'):
149 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('a')):
150 /* beginning-of-line */
151 cursor = 0;
152 first = 0;
153 continue;
154
155 case KEYPRESS(0, SCAN_END, 0):
156 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'e'):
157 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('e')):
158 /* end-of-line */
159 cursor = len - first;
160 if (cursor+1 >= x_max) {
161 cursor = x_max-1;
162 first = len - (x_max-1);
163 }
164 continue;
165
166 case KEYPRESS(0, SCAN_DOWN, 0):
167 case KEYPRESS(EFI_ALT_PRESSED, 0, 'f'):
168 case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_RIGHT, 0):
169 /* forward-word */
170 while (line[first + cursor] && line[first + cursor] == ' ')
171 cursor_right(&cursor, &first, x_max, len);
172 while (line[first + cursor] && line[first + cursor] != ' ')
173 cursor_right(&cursor, &first, x_max, len);
174 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
175 continue;
176
177 case KEYPRESS(0, SCAN_UP, 0):
178 case KEYPRESS(EFI_ALT_PRESSED, 0, 'b'):
179 case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_LEFT, 0):
180 /* backward-word */
181 if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
182 cursor_left(&cursor, &first);
183 while ((first + cursor) > 0 && line[first + cursor] == ' ')
184 cursor_left(&cursor, &first);
185 }
186 while ((first + cursor) > 0 && line[first + cursor-1] != ' ')
187 cursor_left(&cursor, &first);
188 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
189 continue;
190
191 case KEYPRESS(0, SCAN_RIGHT, 0):
192 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'f'):
193 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('f')):
194 /* forward-char */
195 if (first + cursor == len)
196 continue;
197 cursor_right(&cursor, &first, x_max, len);
198 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
199 continue;
200
201 case KEYPRESS(0, SCAN_LEFT, 0):
202 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'b'):
203 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('b')):
204 /* backward-char */
205 cursor_left(&cursor, &first);
206 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
207 continue;
208
209 case KEYPRESS(EFI_ALT_PRESSED, 0, 'd'):
210 /* kill-word */
211 clear = 0;
212 for (i = first + cursor; i < len && line[i] == ' '; i++)
213 clear++;
214 for (; i < len && line[i] != ' '; i++)
215 clear++;
216
217 for (i = first + cursor; i + clear < len; i++)
218 line[i] = line[i + clear];
219 len -= clear;
220 line[len] = '\0';
221 continue;
222
223 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'w'):
224 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('w')):
225 case KEYPRESS(EFI_ALT_PRESSED, 0, CHAR_BACKSPACE):
226 /* backward-kill-word */
227 clear = 0;
228 if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
229 cursor_left(&cursor, &first);
230 clear++;
231 while ((first + cursor) > 0 && line[first + cursor] == ' ') {
232 cursor_left(&cursor, &first);
233 clear++;
234 }
235 }
236 while ((first + cursor) > 0 && line[first + cursor-1] != ' ') {
237 cursor_left(&cursor, &first);
238 clear++;
239 }
240 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
241
242 for (i = first + cursor; i + clear < len; i++)
243 line[i] = line[i + clear];
244 len -= clear;
245 line[len] = '\0';
246 continue;
247
248 case KEYPRESS(0, SCAN_DELETE, 0):
249 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'd'):
250 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('d')):
251 if (len == 0)
252 continue;
253 if (first + cursor == len)
254 continue;
255 for (i = first + cursor; i < len; i++)
256 line[i] = line[i+1];
257 clear = 1;
258 len--;
259 continue;
260
261 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'k'):
262 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('k')):
263 /* kill-line */
264 line[first + cursor] = '\0';
265 clear = len - (first + cursor);
266 len = first + cursor;
267 continue;
268
269 case KEYPRESS(0, 0, CHAR_LINEFEED):
270 case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
271 if (StrCmp(line, line_in) != 0) {
272 *line_out = line;
273 line = NULL;
274 }
275 enter = TRUE;
276 exit = TRUE;
277 break;
278
279 case KEYPRESS(0, 0, CHAR_BACKSPACE):
280 if (len == 0)
281 continue;
282 if (first == 0 && cursor == 0)
283 continue;
284 for (i = first + cursor-1; i < len; i++)
285 line[i] = line[i+1];
286 clear = 1;
287 len--;
288 if (cursor > 0)
289 cursor--;
290 if (cursor > 0 || first == 0)
291 continue;
292 /* show full line if it fits */
293 if (len < x_max) {
294 cursor = first;
295 first = 0;
296 continue;
297 }
298 /* jump left to see what we delete */
299 if (first > 10) {
300 first -= 10;
301 cursor = 10;
302 } else {
303 cursor = first;
304 first = 0;
305 }
306 continue;
307
308 case KEYPRESS(0, 0, ' ') ... KEYPRESS(0, 0, '~'):
309 case KEYPRESS(0, 0, 0x80) ... KEYPRESS(0, 0, 0xffff):
310 if (len+1 == size)
311 continue;
312 for (i = len; i > first + cursor; i--)
313 line[i] = line[i-1];
314 line[first + cursor] = KEYCHAR(key);
315 len++;
316 line[len] = '\0';
317 if (cursor+1 < x_max)
318 cursor++;
319 else if (first + cursor < len)
320 first++;
321 continue;
322 }
323 }
324
325 uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, FALSE);
326 FreePool(print);
327 FreePool(line);
328 return enter;
329 }
330
331 static UINTN entry_lookup_key(Config *config, UINTN start, CHAR16 key) {
332 UINTN i;
333
334 if (key == 0)
335 return -1;
336
337 /* select entry by number key */
338 if (key >= '1' && key <= '9') {
339 i = key - '0';
340 if (i > config->entry_count)
341 i = config->entry_count;
342 return i-1;
343 }
344
345 /* find matching key in config entries */
346 for (i = start; i < config->entry_count; i++)
347 if (config->entries[i]->key == key)
348 return i;
349
350 for (i = 0; i < start; i++)
351 if (config->entries[i]->key == key)
352 return i;
353
354 return -1;
355 }
356
357 static VOID print_status(Config *config, CHAR16 *loaded_image_path) {
358 UINT64 key;
359 UINTN i;
360 CHAR16 *s;
361 CHAR8 *b;
362 UINTN x;
363 UINTN y;
364 UINTN size;
365
366 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
367 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
368
369 Print(L"systemd-boot version: " VERSION "\n");
370 Print(L"architecture: " EFI_MACHINE_TYPE_NAME "\n");
371 Print(L"loaded image: %s\n", loaded_image_path);
372 Print(L"UEFI specification: %d.%02d\n", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
373 Print(L"firmware vendor: %s\n", ST->FirmwareVendor);
374 Print(L"firmware version: %d.%02d\n", ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
375
376 if (uefi_call_wrapper(ST->ConOut->QueryMode, 4, ST->ConOut, ST->ConOut->Mode->Mode, &x, &y) == EFI_SUCCESS)
377 Print(L"console size: %d x %d\n", x, y);
378
379 if (efivar_get_raw(&global_guid, L"SecureBoot", &b, &size) == EFI_SUCCESS) {
380 Print(L"SecureBoot: %s\n", yes_no(*b > 0));
381 FreePool(b);
382 }
383
384 if (efivar_get_raw(&global_guid, L"SetupMode", &b, &size) == EFI_SUCCESS) {
385 Print(L"SetupMode: %s\n", *b > 0 ? L"setup" : L"user");
386 FreePool(b);
387 }
388
389 if (efivar_get_raw(&global_guid, L"OsIndicationsSupported", &b, &size) == EFI_SUCCESS) {
390 Print(L"OsIndicationsSupported: %d\n", (UINT64)*b);
391 FreePool(b);
392 }
393 Print(L"\n");
394
395 Print(L"timeout: %d\n", config->timeout_sec);
396 if (config->timeout_sec_efivar >= 0)
397 Print(L"timeout (EFI var): %d\n", config->timeout_sec_efivar);
398 Print(L"timeout (config): %d\n", config->timeout_sec_config);
399 if (config->entry_default_pattern)
400 Print(L"default pattern: '%s'\n", config->entry_default_pattern);
401 Print(L"editor: %s\n", yes_no(!config->no_editor));
402 Print(L"\n");
403
404 Print(L"config entry count: %d\n", config->entry_count);
405 Print(L"entry selected idx: %d\n", config->idx_default);
406 if (config->idx_default_efivar >= 0)
407 Print(L"entry EFI var idx: %d\n", config->idx_default_efivar);
408 Print(L"\n");
409
410 if (efivar_get_int(L"LoaderConfigTimeout", &i) == EFI_SUCCESS)
411 Print(L"LoaderConfigTimeout: %d\n", i);
412 if (config->entry_oneshot)
413 Print(L"LoaderEntryOneShot: %s\n", config->entry_oneshot);
414 if (efivar_get(L"LoaderDevicePartUUID", &s) == EFI_SUCCESS) {
415 Print(L"LoaderDevicePartUUID: %s\n", s);
416 FreePool(s);
417 }
418 if (efivar_get(L"LoaderEntryDefault", &s) == EFI_SUCCESS) {
419 Print(L"LoaderEntryDefault: %s\n", s);
420 FreePool(s);
421 }
422
423 Print(L"\n--- press key ---\n\n");
424 console_key_read(&key, TRUE);
425
426 for (i = 0; i < config->entry_count; i++) {
427 ConfigEntry *entry;
428
429 if (key == KEYPRESS(0, SCAN_ESC, 0) || key == KEYPRESS(0, 0, 'q'))
430 break;
431
432 entry = config->entries[i];
433 Print(L"config entry: %d/%d\n", i+1, config->entry_count);
434 if (entry->file)
435 Print(L"file '%s'\n", entry->file);
436 Print(L"title show '%s'\n", entry->title_show);
437 if (entry->title)
438 Print(L"title '%s'\n", entry->title);
439 if (entry->version)
440 Print(L"version '%s'\n", entry->version);
441 if (entry->machine_id)
442 Print(L"machine-id '%s'\n", entry->machine_id);
443 if (entry->device) {
444 EFI_DEVICE_PATH *device_path;
445 CHAR16 *str;
446
447 device_path = DevicePathFromHandle(entry->device);
448 if (device_path) {
449 str = DevicePathToStr(device_path);
450 Print(L"device handle '%s'\n", str);
451 FreePool(str);
452 }
453 }
454 if (entry->loader)
455 Print(L"loader '%s'\n", entry->loader);
456 if (entry->options)
457 Print(L"options '%s'\n", entry->options);
458 Print(L"auto-select %s\n", yes_no(!entry->no_autoselect));
459 if (entry->call)
460 Print(L"internal call yes\n");
461
462 Print(L"\n--- press key ---\n\n");
463 console_key_read(&key, TRUE);
464 }
465
466 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
467 }
468
469 static BOOLEAN menu_run(Config *config, ConfigEntry **chosen_entry, CHAR16 *loaded_image_path) {
470 EFI_STATUS err;
471 UINTN visible_max;
472 UINTN idx_highlight;
473 UINTN idx_highlight_prev;
474 UINTN idx_first;
475 UINTN idx_last;
476 BOOLEAN refresh;
477 BOOLEAN highlight;
478 UINTN i;
479 UINTN line_width;
480 CHAR16 **lines;
481 UINTN x_start;
482 UINTN y_start;
483 UINTN x_max;
484 UINTN y_max;
485 CHAR16 *status;
486 CHAR16 *clearline;
487 INTN timeout_remain;
488 INT16 idx;
489 BOOLEAN exit = FALSE;
490 BOOLEAN run = TRUE;
491 BOOLEAN wait = FALSE;
492
493 graphics_mode(FALSE);
494 uefi_call_wrapper(ST->ConIn->Reset, 2, ST->ConIn, FALSE);
495 uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, FALSE);
496 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
497
498 /* draw a single character to make ClearScreen work on some firmware */
499 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L" ");
500 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
501
502 err = uefi_call_wrapper(ST->ConOut->QueryMode, 4, ST->ConOut, ST->ConOut->Mode->Mode, &x_max, &y_max);
503 if (EFI_ERROR(err)) {
504 x_max = 80;
505 y_max = 25;
506 }
507
508 /* we check 10 times per second for a keystroke */
509 if (config->timeout_sec > 0)
510 timeout_remain = config->timeout_sec * 10;
511 else
512 timeout_remain = -1;
513
514 idx_highlight = config->idx_default;
515 idx_highlight_prev = 0;
516
517 visible_max = y_max - 2;
518
519 if ((UINTN)config->idx_default >= visible_max)
520 idx_first = config->idx_default-1;
521 else
522 idx_first = 0;
523
524 idx_last = idx_first + visible_max-1;
525
526 refresh = TRUE;
527 highlight = FALSE;
528
529 /* length of the longest entry */
530 line_width = 5;
531 for (i = 0; i < config->entry_count; i++) {
532 UINTN entry_len;
533
534 entry_len = StrLen(config->entries[i]->title_show);
535 if (line_width < entry_len)
536 line_width = entry_len;
537 }
538 if (line_width > x_max-6)
539 line_width = x_max-6;
540
541 /* offsets to center the entries on the screen */
542 x_start = (x_max - (line_width)) / 2;
543 if (config->entry_count < visible_max)
544 y_start = ((visible_max - config->entry_count) / 2) + 1;
545 else
546 y_start = 0;
547
548 /* menu entries title lines */
549 lines = AllocatePool(sizeof(CHAR16 *) * config->entry_count);
550 for (i = 0; i < config->entry_count; i++) {
551 UINTN j, k;
552
553 lines[i] = AllocatePool(((x_max+1) * sizeof(CHAR16)));
554 for (j = 0; j < x_start; j++)
555 lines[i][j] = ' ';
556
557 for (k = 0; config->entries[i]->title_show[k] != '\0' && j < x_max; j++, k++)
558 lines[i][j] = config->entries[i]->title_show[k];
559
560 for (; j < x_max; j++)
561 lines[i][j] = ' ';
562 lines[i][x_max] = '\0';
563 }
564
565 status = NULL;
566 clearline = AllocatePool((x_max+1) * sizeof(CHAR16));
567 for (i = 0; i < x_max; i++)
568 clearline[i] = ' ';
569 clearline[i] = 0;
570
571 while (!exit) {
572 UINT64 key;
573
574 if (refresh) {
575 for (i = 0; i < config->entry_count; i++) {
576 if (i < idx_first || i > idx_last)
577 continue;
578 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + i - idx_first);
579 if (i == idx_highlight)
580 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut,
581 EFI_BLACK|EFI_BACKGROUND_LIGHTGRAY);
582 else
583 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut,
584 EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
585 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[i]);
586 if ((INTN)i == config->idx_default_efivar) {
587 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + i - idx_first);
588 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
589 }
590 }
591 refresh = FALSE;
592 } else if (highlight) {
593 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + idx_highlight_prev - idx_first);
594 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
595 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[idx_highlight_prev]);
596 if ((INTN)idx_highlight_prev == config->idx_default_efivar) {
597 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + idx_highlight_prev - idx_first);
598 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
599 }
600
601 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + idx_highlight - idx_first);
602 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_BLACK|EFI_BACKGROUND_LIGHTGRAY);
603 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[idx_highlight]);
604 if ((INTN)idx_highlight == config->idx_default_efivar) {
605 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + idx_highlight - idx_first);
606 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
607 }
608 highlight = FALSE;
609 }
610
611 if (timeout_remain > 0) {
612 FreePool(status);
613 status = PoolPrint(L"Boot in %d sec.", (timeout_remain + 5) / 10);
614 }
615
616 /* print status at last line of screen */
617 if (status) {
618 UINTN len;
619 UINTN x;
620
621 /* center line */
622 len = StrLen(status);
623 if (len < x_max)
624 x = (x_max - len) / 2;
625 else
626 x = 0;
627 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
628 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
629 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline + (x_max - x));
630 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, status);
631 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1 + x + len);
632 }
633
634 err = console_key_read(&key, wait);
635 if (EFI_ERROR(err)) {
636 /* timeout reached */
637 if (timeout_remain == 0) {
638 exit = TRUE;
639 break;
640 }
641
642 /* sleep and update status */
643 if (timeout_remain > 0) {
644 uefi_call_wrapper(BS->Stall, 1, 100 * 1000);
645 timeout_remain--;
646 continue;
647 }
648
649 /* timeout disabled, wait for next key */
650 wait = TRUE;
651 continue;
652 }
653
654 timeout_remain = -1;
655
656 /* clear status after keystroke */
657 if (status) {
658 FreePool(status);
659 status = NULL;
660 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
661 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
662 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
663 }
664
665 idx_highlight_prev = idx_highlight;
666
667 switch (key) {
668 case KEYPRESS(0, SCAN_UP, 0):
669 case KEYPRESS(0, 0, 'k'):
670 if (idx_highlight > 0)
671 idx_highlight--;
672 break;
673
674 case KEYPRESS(0, SCAN_DOWN, 0):
675 case KEYPRESS(0, 0, 'j'):
676 if (idx_highlight < config->entry_count-1)
677 idx_highlight++;
678 break;
679
680 case KEYPRESS(0, SCAN_HOME, 0):
681 case KEYPRESS(EFI_ALT_PRESSED, 0, '<'):
682 if (idx_highlight > 0) {
683 refresh = TRUE;
684 idx_highlight = 0;
685 }
686 break;
687
688 case KEYPRESS(0, SCAN_END, 0):
689 case KEYPRESS(EFI_ALT_PRESSED, 0, '>'):
690 if (idx_highlight < config->entry_count-1) {
691 refresh = TRUE;
692 idx_highlight = config->entry_count-1;
693 }
694 break;
695
696 case KEYPRESS(0, SCAN_PAGE_UP, 0):
697 if (idx_highlight > visible_max)
698 idx_highlight -= visible_max;
699 else
700 idx_highlight = 0;
701 break;
702
703 case KEYPRESS(0, SCAN_PAGE_DOWN, 0):
704 idx_highlight += visible_max;
705 if (idx_highlight > config->entry_count-1)
706 idx_highlight = config->entry_count-1;
707 break;
708
709 case KEYPRESS(0, 0, CHAR_LINEFEED):
710 case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
711 exit = TRUE;
712 break;
713
714 case KEYPRESS(0, SCAN_F1, 0):
715 case KEYPRESS(0, 0, 'h'):
716 case KEYPRESS(0, 0, '?'):
717 status = StrDuplicate(L"(d)efault, (t/T)timeout, (e)dit, (v)ersion (Q)uit (P)rint (h)elp");
718 break;
719
720 case KEYPRESS(0, 0, 'Q'):
721 exit = TRUE;
722 run = FALSE;
723 break;
724
725 case KEYPRESS(0, 0, 'd'):
726 if (config->idx_default_efivar != (INTN)idx_highlight) {
727 /* store the selected entry in a persistent EFI variable */
728 efivar_set(L"LoaderEntryDefault", config->entries[idx_highlight]->file, TRUE);
729 config->idx_default_efivar = idx_highlight;
730 status = StrDuplicate(L"Default boot entry selected.");
731 } else {
732 /* clear the default entry EFI variable */
733 efivar_set(L"LoaderEntryDefault", NULL, TRUE);
734 config->idx_default_efivar = -1;
735 status = StrDuplicate(L"Default boot entry cleared.");
736 }
737 refresh = TRUE;
738 break;
739
740 case KEYPRESS(0, 0, '-'):
741 case KEYPRESS(0, 0, 'T'):
742 if (config->timeout_sec_efivar > 0) {
743 config->timeout_sec_efivar--;
744 efivar_set_int(L"LoaderConfigTimeout", config->timeout_sec_efivar, TRUE);
745 if (config->timeout_sec_efivar > 0)
746 status = PoolPrint(L"Menu timeout set to %d sec.", config->timeout_sec_efivar);
747 else
748 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
749 } else if (config->timeout_sec_efivar <= 0){
750 config->timeout_sec_efivar = -1;
751 efivar_set(L"LoaderConfigTimeout", NULL, TRUE);
752 if (config->timeout_sec_config > 0)
753 status = PoolPrint(L"Menu timeout of %d sec is defined by configuration file.",
754 config->timeout_sec_config);
755 else
756 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
757 }
758 break;
759
760 case KEYPRESS(0, 0, '+'):
761 case KEYPRESS(0, 0, 't'):
762 if (config->timeout_sec_efivar == -1 && config->timeout_sec_config == 0)
763 config->timeout_sec_efivar++;
764 config->timeout_sec_efivar++;
765 efivar_set_int(L"LoaderConfigTimeout", config->timeout_sec_efivar, TRUE);
766 if (config->timeout_sec_efivar > 0)
767 status = PoolPrint(L"Menu timeout set to %d sec.",
768 config->timeout_sec_efivar);
769 else
770 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
771 break;
772
773 case KEYPRESS(0, 0, 'e'):
774 /* only the options of configured entries can be edited */
775 if (config->no_editor || config->entries[idx_highlight]->type == LOADER_UNDEFINED)
776 break;
777 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
778 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
779 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
780 if (line_edit(config->entries[idx_highlight]->options, &config->options_edit, x_max-1, y_max-1))
781 exit = TRUE;
782 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
783 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
784 break;
785
786 case KEYPRESS(0, 0, 'v'):
787 status = PoolPrint(L"systemd-boot " VERSION " (" EFI_MACHINE_TYPE_NAME "), UEFI Specification %d.%02d, Vendor %s %d.%02d",
788 ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff,
789 ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
790 break;
791
792 case KEYPRESS(0, 0, 'P'):
793 print_status(config, loaded_image_path);
794 refresh = TRUE;
795 break;
796
797 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'l'):
798 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('l')):
799 refresh = TRUE;
800 break;
801
802 default:
803 /* jump with a hotkey directly to a matching entry */
804 idx = entry_lookup_key(config, idx_highlight+1, KEYCHAR(key));
805 if (idx < 0)
806 break;
807 idx_highlight = idx;
808 refresh = TRUE;
809 }
810
811 if (idx_highlight > idx_last) {
812 idx_last = idx_highlight;
813 idx_first = 1 + idx_highlight - visible_max;
814 refresh = TRUE;
815 } else if (idx_highlight < idx_first) {
816 idx_first = idx_highlight;
817 idx_last = idx_highlight + visible_max-1;
818 refresh = TRUE;
819 }
820
821 if (!refresh && idx_highlight != idx_highlight_prev)
822 highlight = TRUE;
823 }
824
825 *chosen_entry = config->entries[idx_highlight];
826
827 for (i = 0; i < config->entry_count; i++)
828 FreePool(lines[i]);
829 FreePool(lines);
830 FreePool(clearline);
831
832 uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_WHITE|EFI_BACKGROUND_BLACK);
833 uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
834 return run;
835 }
836
837 static VOID config_add_entry(Config *config, ConfigEntry *entry) {
838 if ((config->entry_count & 15) == 0) {
839 UINTN i;
840
841 i = config->entry_count + 16;
842 if (config->entry_count == 0)
843 config->entries = AllocatePool(sizeof(VOID *) * i);
844 else
845 config->entries = ReallocatePool(config->entries,
846 sizeof(VOID *) * config->entry_count, sizeof(VOID *) * i);
847 }
848 config->entries[config->entry_count++] = entry;
849 }
850
851 static VOID config_entry_free(ConfigEntry *entry) {
852 FreePool(entry->title_show);
853 FreePool(entry->title);
854 FreePool(entry->machine_id);
855 FreePool(entry->loader);
856 FreePool(entry->options);
857 }
858
859 static BOOLEAN is_digit(CHAR16 c)
860 {
861 return (c >= '0') && (c <= '9');
862 }
863
864 static UINTN c_order(CHAR16 c)
865 {
866 if (c == '\0')
867 return 0;
868 if (is_digit(c))
869 return 0;
870 else if ((c >= 'a') && (c <= 'z'))
871 return c;
872 else
873 return c + 0x10000;
874 }
875
876 static INTN str_verscmp(CHAR16 *s1, CHAR16 *s2)
877 {
878 CHAR16 *os1 = s1;
879 CHAR16 *os2 = s2;
880
881 while (*s1 || *s2) {
882 INTN first;
883
884 while ((*s1 && !is_digit(*s1)) || (*s2 && !is_digit(*s2))) {
885 INTN order;
886
887 order = c_order(*s1) - c_order(*s2);
888 if (order)
889 return order;
890 s1++;
891 s2++;
892 }
893
894 while (*s1 == '0')
895 s1++;
896 while (*s2 == '0')
897 s2++;
898
899 first = 0;
900 while (is_digit(*s1) && is_digit(*s2)) {
901 if (first == 0)
902 first = *s1 - *s2;
903 s1++;
904 s2++;
905 }
906
907 if (is_digit(*s1))
908 return 1;
909 if (is_digit(*s2))
910 return -1;
911
912 if (first)
913 return first;
914 }
915
916 return StrCmp(os1, os2);
917 }
918
919 static CHAR8 *line_get_key_value(CHAR8 *content, CHAR8 *sep, UINTN *pos, CHAR8 **key_ret, CHAR8 **value_ret) {
920 CHAR8 *line;
921 UINTN linelen;
922 CHAR8 *value;
923
924 skip:
925 line = content + *pos;
926 if (*line == '\0')
927 return NULL;
928
929 linelen = 0;
930 while (line[linelen] && !strchra((CHAR8 *)"\n\r", line[linelen]))
931 linelen++;
932
933 /* move pos to next line */
934 *pos += linelen;
935 if (content[*pos])
936 (*pos)++;
937
938 /* empty line */
939 if (linelen == 0)
940 goto skip;
941
942 /* terminate line */
943 line[linelen] = '\0';
944
945 /* remove leading whitespace */
946 while (strchra((CHAR8 *)" \t", *line)) {
947 line++;
948 linelen--;
949 }
950
951 /* remove trailing whitespace */
952 while (linelen > 0 && strchra(sep, line[linelen-1]))
953 linelen--;
954 line[linelen] = '\0';
955
956 if (*line == '#')
957 goto skip;
958
959 /* split key/value */
960 value = line;
961 while (*value && !strchra(sep, *value))
962 value++;
963 if (*value == '\0')
964 goto skip;
965 *value = '\0';
966 value++;
967 while (*value && strchra(sep, *value))
968 value++;
969
970 /* unquote */
971 if (value[0] == '\"' && line[linelen-1] == '\"') {
972 value++;
973 line[linelen-1] = '\0';
974 }
975
976 *key_ret = line;
977 *value_ret = value;
978 return line;
979 }
980
981 static VOID config_defaults_load_from_file(Config *config, CHAR8 *content) {
982 CHAR8 *line;
983 UINTN pos = 0;
984 CHAR8 *key, *value;
985
986 line = content;
987 while ((line = line_get_key_value(content, (CHAR8 *)" \t", &pos, &key, &value))) {
988 if (strcmpa((CHAR8 *)"timeout", key) == 0) {
989 CHAR16 *s;
990
991 s = stra_to_str(value);
992 config->timeout_sec_config = Atoi(s);
993 config->timeout_sec = config->timeout_sec_config;
994 FreePool(s);
995 continue;
996 }
997
998 if (strcmpa((CHAR8 *)"default", key) == 0) {
999 FreePool(config->entry_default_pattern);
1000 config->entry_default_pattern = stra_to_str(value);
1001 StrLwr(config->entry_default_pattern);
1002 continue;
1003 }
1004
1005 if (strcmpa((CHAR8 *)"editor", key) == 0) {
1006 BOOLEAN on;
1007
1008 if (EFI_ERROR(parse_boolean(value, &on)))
1009 continue;
1010 config->no_editor = !on;
1011 }
1012 }
1013 }
1014
1015 static VOID config_entry_add_from_file(Config *config, EFI_HANDLE *device, CHAR16 *file, CHAR8 *content, CHAR16 *loaded_image_path) {
1016 ConfigEntry *entry;
1017 CHAR8 *line;
1018 UINTN pos = 0;
1019 CHAR8 *key, *value;
1020 UINTN len;
1021 CHAR16 *initrd = NULL;
1022
1023 entry = AllocateZeroPool(sizeof(ConfigEntry));
1024
1025 line = content;
1026 while ((line = line_get_key_value(content, (CHAR8 *)" \t", &pos, &key, &value))) {
1027 if (strcmpa((CHAR8 *)"title", key) == 0) {
1028 FreePool(entry->title);
1029 entry->title = stra_to_str(value);
1030 continue;
1031 }
1032
1033 if (strcmpa((CHAR8 *)"version", key) == 0) {
1034 FreePool(entry->version);
1035 entry->version = stra_to_str(value);
1036 continue;
1037 }
1038
1039 if (strcmpa((CHAR8 *)"machine-id", key) == 0) {
1040 FreePool(entry->machine_id);
1041 entry->machine_id = stra_to_str(value);
1042 continue;
1043 }
1044
1045 if (strcmpa((CHAR8 *)"linux", key) == 0) {
1046 FreePool(entry->loader);
1047 entry->type = LOADER_LINUX;
1048 entry->loader = stra_to_path(value);
1049 entry->key = 'l';
1050 continue;
1051 }
1052
1053 if (strcmpa((CHAR8 *)"efi", key) == 0) {
1054 entry->type = LOADER_EFI;
1055 FreePool(entry->loader);
1056 entry->loader = stra_to_path(value);
1057
1058 /* do not add an entry for ourselves */
1059 if (StriCmp(entry->loader, loaded_image_path) == 0) {
1060 entry->type = LOADER_UNDEFINED;
1061 break;
1062 }
1063 continue;
1064 }
1065
1066 if (strcmpa((CHAR8 *)"architecture", key) == 0) {
1067 /* do not add an entry for an EFI image of architecture not matching with that of the image */
1068 if (strcmpa((CHAR8 *)EFI_MACHINE_TYPE_NAME, value) != 0) {
1069 entry->type = LOADER_UNDEFINED;
1070 break;
1071 }
1072 continue;
1073 }
1074
1075 if (strcmpa((CHAR8 *)"initrd", key) == 0) {
1076 CHAR16 *new;
1077
1078 new = stra_to_path(value);
1079 if (initrd) {
1080 CHAR16 *s;
1081
1082 s = PoolPrint(L"%s initrd=%s", initrd, new);
1083 FreePool(initrd);
1084 initrd = s;
1085 } else
1086 initrd = PoolPrint(L"initrd=%s", new);
1087 FreePool(new);
1088 continue;
1089 }
1090
1091 if (strcmpa((CHAR8 *)"options", key) == 0) {
1092 CHAR16 *new;
1093
1094 new = stra_to_str(value);
1095 if (entry->options) {
1096 CHAR16 *s;
1097
1098 s = PoolPrint(L"%s %s", entry->options, new);
1099 FreePool(entry->options);
1100 entry->options = s;
1101 } else {
1102 entry->options = new;
1103 new = NULL;
1104 }
1105 FreePool(new);
1106 continue;
1107 }
1108 }
1109
1110 if (entry->type == LOADER_UNDEFINED) {
1111 config_entry_free(entry);
1112 FreePool(initrd);
1113 FreePool(entry);
1114 return;
1115 }
1116
1117 /* add initrd= to options */
1118 if (entry->type == LOADER_LINUX && initrd) {
1119 if (entry->options) {
1120 CHAR16 *s;
1121
1122 s = PoolPrint(L"%s %s", initrd, entry->options);
1123 FreePool(entry->options);
1124 entry->options = s;
1125 } else {
1126 entry->options = initrd;
1127 initrd = NULL;
1128 }
1129 }
1130 FreePool(initrd);
1131
1132 entry->device = device;
1133 entry->file = StrDuplicate(file);
1134 len = StrLen(entry->file);
1135 /* remove ".conf" */
1136 if (len > 5)
1137 entry->file[len - 5] = '\0';
1138 StrLwr(entry->file);
1139
1140 config_add_entry(config, entry);
1141 }
1142
1143 static VOID config_load(Config *config, EFI_HANDLE *device, EFI_FILE *root_dir, CHAR16 *loaded_image_path) {
1144 EFI_FILE_HANDLE entries_dir;
1145 EFI_STATUS err;
1146 CHAR8 *content = NULL;
1147 UINTN sec;
1148 UINTN len;
1149 UINTN i;
1150
1151 len = file_read(root_dir, L"\\loader\\loader.conf", 0, 0, &content);
1152 if (len > 0)
1153 config_defaults_load_from_file(config, content);
1154 FreePool(content);
1155
1156 err = efivar_get_int(L"LoaderConfigTimeout", &sec);
1157 if (!EFI_ERROR(err)) {
1158 config->timeout_sec_efivar = sec;
1159 config->timeout_sec = sec;
1160 } else
1161 config->timeout_sec_efivar = -1;
1162
1163 err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &entries_dir, L"\\loader\\entries", EFI_FILE_MODE_READ, 0ULL);
1164 if (!EFI_ERROR(err)) {
1165 for (;;) {
1166 CHAR16 buf[256];
1167 UINTN bufsize;
1168 EFI_FILE_INFO *f;
1169 CHAR8 *content = NULL;
1170 UINTN len;
1171
1172 bufsize = sizeof(buf);
1173 err = uefi_call_wrapper(entries_dir->Read, 3, entries_dir, &bufsize, buf);
1174 if (bufsize == 0 || EFI_ERROR(err))
1175 break;
1176
1177 f = (EFI_FILE_INFO *) buf;
1178 if (f->FileName[0] == '.')
1179 continue;
1180 if (f->Attribute & EFI_FILE_DIRECTORY)
1181 continue;
1182
1183 len = StrLen(f->FileName);
1184 if (len < 6)
1185 continue;
1186 if (StriCmp(f->FileName + len - 5, L".conf") != 0)
1187 continue;
1188 if (StrnCmp(f->FileName, L"auto-", 5) == 0)
1189 continue;
1190
1191 len = file_read(entries_dir, f->FileName, 0, 0, &content);
1192 if (len > 0)
1193 config_entry_add_from_file(config, device, f->FileName, content, loaded_image_path);
1194 FreePool(content);
1195 }
1196 uefi_call_wrapper(entries_dir->Close, 1, entries_dir);
1197 }
1198
1199 /* sort entries after version number */
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"OS X",
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
1650 efivar_set_time_usec(L"LoaderTimeExecUSec", 0);
1651 err = uefi_call_wrapper(BS->StartImage, 3, image, NULL, NULL);
1652 out_unload:
1653 uefi_call_wrapper(BS->UnloadImage, 1, image);
1654 out:
1655 FreePool(path);
1656 return err;
1657 }
1658
1659 static EFI_STATUS reboot_into_firmware(VOID) {
1660 CHAR8 *b;
1661 UINTN size;
1662 UINT64 osind;
1663 EFI_STATUS err;
1664
1665 osind = EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
1666
1667 err = efivar_get_raw(&global_guid, L"OsIndications", &b, &size);
1668 if (!EFI_ERROR(err))
1669 osind |= (UINT64)*b;
1670 FreePool(b);
1671
1672 err = efivar_set_raw(&global_guid, L"OsIndications", (CHAR8 *)&osind, sizeof(UINT64), TRUE);
1673 if (EFI_ERROR(err))
1674 return err;
1675
1676 err = uefi_call_wrapper(RT->ResetSystem, 4, EfiResetCold, EFI_SUCCESS, 0, NULL);
1677 Print(L"Error calling ResetSystem: %r", err);
1678 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1679 return err;
1680 }
1681
1682 static VOID config_free(Config *config) {
1683 UINTN i;
1684
1685 for (i = 0; i < config->entry_count; i++)
1686 config_entry_free(config->entries[i]);
1687 FreePool(config->entries);
1688 FreePool(config->entry_default_pattern);
1689 FreePool(config->options_edit);
1690 FreePool(config->entry_oneshot);
1691 }
1692
1693 EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *sys_table) {
1694 CHAR16 *s;
1695 CHAR8 *b;
1696 UINTN size;
1697 EFI_LOADED_IMAGE *loaded_image;
1698 EFI_FILE *root_dir;
1699 CHAR16 *loaded_image_path;
1700 EFI_STATUS err;
1701 Config config;
1702 UINT64 init_usec;
1703 BOOLEAN menu = FALSE;
1704 CHAR16 uuid[37];
1705
1706 InitializeLib(image, sys_table);
1707 init_usec = time_usec();
1708 efivar_set_time_usec(L"LoaderTimeInitUSec", init_usec);
1709 efivar_set(L"LoaderInfo", L"systemd-boot " VERSION, FALSE);
1710 s = PoolPrint(L"%s %d.%02d", ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1711 efivar_set(L"LoaderFirmwareInfo", s, FALSE);
1712 FreePool(s);
1713 s = PoolPrint(L"UEFI %d.%02d", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
1714 efivar_set(L"LoaderFirmwareType", s, FALSE);
1715 FreePool(s);
1716
1717 err = uefi_call_wrapper(BS->OpenProtocol, 6, image, &LoadedImageProtocol, (VOID **)&loaded_image,
1718 image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
1719 if (EFI_ERROR(err)) {
1720 Print(L"Error getting a LoadedImageProtocol handle: %r ", err);
1721 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1722 return err;
1723 }
1724
1725 /* export the device path this image is started from */
1726 if (disk_get_part_uuid(loaded_image->DeviceHandle, uuid) == EFI_SUCCESS)
1727 efivar_set(L"LoaderDevicePartUUID", uuid, FALSE);
1728
1729 root_dir = LibOpenRoot(loaded_image->DeviceHandle);
1730 if (!root_dir) {
1731 Print(L"Unable to open root directory: %r ", err);
1732 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1733 return EFI_LOAD_ERROR;
1734 }
1735
1736
1737 /* the filesystem path to this image, to prevent adding ourselves to the menu */
1738 loaded_image_path = DevicePathToStr(loaded_image->FilePath);
1739 efivar_set(L"LoaderImageIdentifier", loaded_image_path, FALSE);
1740
1741 /* scan "\loader\entries\*.conf" files */
1742 ZeroMem(&config, sizeof(Config));
1743 config_load(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
1744
1745 /* if we find some well-known loaders, add them to the end of the list */
1746 config_entry_add_linux(&config, loaded_image, root_dir);
1747 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
1748 L"auto-windows", 'w', L"Windows Boot Manager", L"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
1749 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
1750 L"auto-efi-shell", 's', L"EFI Shell", L"\\shell" EFI_MACHINE_TYPE_NAME ".efi");
1751 config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
1752 L"auto-efi-default", '\0', L"EFI Default Loader", L"\\EFI\\Boot\\boot" EFI_MACHINE_TYPE_NAME ".efi");
1753 config_entry_add_osx(&config);
1754
1755 if (efivar_get_raw(&global_guid, L"OsIndicationsSupported", &b, &size) == EFI_SUCCESS) {
1756 UINT64 osind = (UINT64)*b;
1757
1758 if (osind & EFI_OS_INDICATIONS_BOOT_TO_FW_UI)
1759 config_entry_add_call(&config, L"Reboot Into Firmware Interface", reboot_into_firmware);
1760 FreePool(b);
1761 }
1762
1763 if (config.entry_count == 0) {
1764 Print(L"No loader found. Configuration files in \\loader\\entries\\*.conf are needed.");
1765 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1766 goto out;
1767 }
1768
1769 config_title_generate(&config);
1770
1771 /* select entry by configured pattern or EFI LoaderDefaultEntry= variable*/
1772 config_default_entry_select(&config);
1773
1774 /* if no configured entry to select from was found, enable the menu */
1775 if (config.idx_default == -1) {
1776 config.idx_default = 0;
1777 if (config.timeout_sec == 0)
1778 config.timeout_sec = 10;
1779 }
1780
1781 /* select entry or show menu when key is pressed or timeout is set */
1782 if (config.timeout_sec == 0) {
1783 UINT64 key;
1784
1785 err = console_key_read(&key, FALSE);
1786 if (!EFI_ERROR(err)) {
1787 INT16 idx;
1788
1789 /* find matching key in config entries */
1790 idx = entry_lookup_key(&config, config.idx_default, KEYCHAR(key));
1791 if (idx >= 0)
1792 config.idx_default = idx;
1793 else
1794 menu = TRUE;
1795 }
1796 } else
1797 menu = TRUE;
1798
1799 for (;;) {
1800 ConfigEntry *entry;
1801
1802 entry = config.entries[config.idx_default];
1803 if (menu) {
1804 efivar_set_time_usec(L"LoaderTimeMenuUSec", 0);
1805 uefi_call_wrapper(BS->SetWatchdogTimer, 4, 0, 0x10000, 0, NULL);
1806 if (!menu_run(&config, &entry, loaded_image_path))
1807 break;
1808
1809 /* run special entry like "reboot" */
1810 if (entry->call) {
1811 entry->call();
1812 continue;
1813 }
1814 }
1815
1816 /* export the selected boot entry to the system */
1817 efivar_set(L"LoaderEntrySelected", entry->file, FALSE);
1818
1819 uefi_call_wrapper(BS->SetWatchdogTimer, 4, 5 * 60, 0x10000, 0, NULL);
1820 err = image_start(image, &config, entry);
1821 if (EFI_ERROR(err)) {
1822 graphics_mode(FALSE);
1823 Print(L"\nFailed to execute %s (%s): %r\n", entry->title, entry->loader, err);
1824 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1825 goto out;
1826 }
1827
1828 menu = TRUE;
1829 config.timeout_sec = 0;
1830 }
1831 err = EFI_SUCCESS;
1832 out:
1833 FreePool(loaded_image_path);
1834 config_free(&config);
1835 uefi_call_wrapper(root_dir->Close, 1, root_dir);
1836 uefi_call_wrapper(BS->CloseProtocol, 4, image, &LoadedImageProtocol, image, NULL);
1837 return err;
1838 }