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