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