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