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