1e16ef07b01f90cc72b99c955309394ace860eec
[platform/upstream/gummiboot.git] / src / efi / gummiboot.c
1 /*
2  * Simple UEFI boot loader which executes configured EFI images, where the
3  * default entry is selected by a configured pattern (glob) or an on-screen
4  * menu.
5  *
6  * All gummiboot code is LGPL not GPL, to stay out of politics and to give
7  * the freedom of copying code from programs to possible future libraries.
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * Copyright (C) 2012-2013 Kay Sievers <kay@vrfy.org>
20  * Copyright (C) 2012 Harald Hoyer <harald@redhat.com>
21  *
22  * "Any intelligent fool can make things bigger, more complex, and more violent."
23  *   -- Albert Einstein
24  */
25
26 #include <efi.h>
27 #include <efilib.h>
28
29 #ifndef EFI_OS_INDICATIONS_BOOT_TO_FW_UI
30 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001ULL
31 #endif
32
33 #ifndef EFI_SECURITY_VIOLATION
34 #define EFI_SECURITY_VIOLATION      EFIERR(26)
35 #endif
36
37 /* magic string to find in the binary image */
38 static const char __attribute__((used)) magic[] = "#### LoaderInfo: gummiboot " VERSION " ####";
39
40 /*
41  * Allocated random UUID, intended to be shared across tools that implement
42  * the (ESP)\loader\entries\<vendor>-<revision>.conf convention and the
43  * associated EFI variables.
44  */
45 static const EFI_GUID loader_guid = { 0x4a67b082, 0x0a4c, 0x41cf, {0xb6, 0xc7, 0x44, 0x0b, 0x29, 0xbb, 0x8c, 0x4f} };
46
47 static const EFI_GUID global_guid = EFI_GLOBAL_VARIABLE;
48
49 enum loader_type {
50         LOADER_UNDEFINED,
51         LOADER_EFI,
52         LOADER_LINUX
53 };
54
55 typedef struct {
56         CHAR16 *file;
57         CHAR16 *title_show;
58         CHAR16 *title;
59         CHAR16 *version;
60         CHAR16 *machine_id;
61         EFI_HANDLE *device;
62         enum loader_type type;
63         CHAR16 *loader;
64         CHAR16 *options;
65         CHAR16 key;
66         EFI_STATUS (*call)(void);
67         BOOLEAN no_autoselect;
68         BOOLEAN non_unique;
69 } ConfigEntry;
70
71 typedef struct {
72         ConfigEntry **entries;
73         UINTN entry_count;
74         INTN idx_default;
75         INTN idx_default_efivar;
76         UINTN timeout_sec;
77         UINTN timeout_sec_config;
78         INTN timeout_sec_efivar;
79         CHAR16 *entry_default_pattern;
80         CHAR16 *entry_oneshot;
81         CHAR16 *options_edit;
82         CHAR16 *entries_auto;
83 } Config;
84
85 static CHAR16 *stra_to_str(CHAR8 *stra);
86
87 #ifdef __x86_64__
88 static UINT64 ticks_read(void) {
89         UINT64 a, d;
90         __asm__ volatile ("rdtsc" : "=a" (a), "=d" (d));
91         return (d << 32) | a;
92 }
93 #else
94 static UINT64 ticks_read(void) {
95         UINT64 val;
96         __asm__ volatile ("rdtsc" : "=A" (val));
97         return val;
98 }
99 #endif
100
101 /* count TSC ticks during a millisecond delay */
102 static UINT64 ticks_freq(void) {
103         UINT64 ticks_start, ticks_end;
104
105         ticks_start = ticks_read();
106         uefi_call_wrapper(BS->Stall, 1, 1000);
107         ticks_end = ticks_read();
108
109         return (ticks_end - ticks_start) * 1000;
110 }
111
112 static UINT64 time_usec(void) {
113         UINT64 ticks;
114         static UINT64 freq;
115
116         ticks = ticks_read();
117         if (ticks == 0)
118                 return 0;
119
120         if (freq == 0) {
121                 freq = ticks_freq();
122                 if (freq == 0)
123                         return 0;
124         }
125
126         return 1000 * 1000 * ticks / freq;
127 }
128
129 static EFI_STATUS efivar_set_raw(const EFI_GUID *vendor, CHAR16 *name, CHAR8 *buf, UINTN size, BOOLEAN persistent) {
130         UINT32 flags;
131
132         flags = EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS;
133         if (persistent)
134                 flags |= EFI_VARIABLE_NON_VOLATILE;
135
136         return uefi_call_wrapper(RT->SetVariable, 5, name, (EFI_GUID *)vendor, flags, size, buf);
137 }
138
139 static EFI_STATUS efivar_set(CHAR16 *name, CHAR16 *value, BOOLEAN persistent) {
140         return efivar_set_raw(&loader_guid, name, (CHAR8 *)value, value ? (StrLen(value)+1) * sizeof(CHAR16) : 0, persistent);
141 }
142
143 static EFI_STATUS efivar_get_raw(const EFI_GUID *vendor, CHAR16 *name, CHAR8 **buffer, UINTN *size) {
144         CHAR8 *buf;
145         UINTN l;
146         EFI_STATUS err;
147
148         l = sizeof(CHAR16 *) * EFI_MAXIMUM_VARIABLE_SIZE;
149         buf = AllocatePool(l);
150         if (!buf)
151                 return EFI_OUT_OF_RESOURCES;
152
153         err = uefi_call_wrapper(RT->GetVariable, 5, name, (EFI_GUID *)vendor, NULL, &l, buf);
154         if (!EFI_ERROR(err)) {
155                 *buffer = buf;
156                 if (size)
157                         *size = l;
158         } else
159                 FreePool(buf);
160         return err;
161
162 }
163
164 static EFI_STATUS efivar_get(CHAR16 *name, CHAR16 **value) {
165         CHAR8 *buf;
166         CHAR16 *val;
167         UINTN size;
168         EFI_STATUS err;
169
170         err = efivar_get_raw(&loader_guid, name, &buf, &size);
171         if (EFI_ERROR(err))
172                 return err;
173
174         val = StrDuplicate((CHAR16 *)buf);
175         if (!val) {
176                 FreePool(val);
177                 return EFI_OUT_OF_RESOURCES;
178         }
179
180         *value = val;
181         return EFI_SUCCESS;
182 }
183
184 static EFI_STATUS efivar_set_int(CHAR16 *name, UINTN i, BOOLEAN persistent) {
185         CHAR16 str[32];
186
187         SPrint(str, 32, L"%d", i);
188         return efivar_set(name, str, persistent);
189 }
190
191 static EFI_STATUS efivar_get_int(CHAR16 *name, UINTN *i) {
192         CHAR16 *val;
193         EFI_STATUS err;
194
195         err = efivar_get(name, &val);
196         if (!EFI_ERROR(err)) {
197                 *i = Atoi(val);
198                 FreePool(val);
199         }
200         return err;
201 }
202
203 static VOID efivar_set_time_usec(CHAR16 *name, UINT64 usec) {
204         CHAR16 str[32];
205
206         if (usec == 0)
207                 usec = time_usec();
208         if (usec == 0)
209                 return;
210
211         SPrint(str, 32, L"%ld", usec);
212         efivar_set(name, str, FALSE);
213 }
214
215 #define EFI_SHIFT_STATE_VALID           0x80000000
216 #define EFI_RIGHT_CONTROL_PRESSED       0x00000004
217 #define EFI_LEFT_CONTROL_PRESSED        0x00000008
218 #define EFI_RIGHT_ALT_PRESSED           0x00000010
219 #define EFI_LEFT_ALT_PRESSED            0x00000020
220 #define EFI_CONTROL_PRESSED             (EFI_RIGHT_CONTROL_PRESSED|EFI_LEFT_CONTROL_PRESSED)
221 #define EFI_ALT_PRESSED                 (EFI_RIGHT_ALT_PRESSED|EFI_LEFT_ALT_PRESSED)
222 #define KEYPRESS(keys, scan, uni) ((((UINT64)keys) << 32) | ((scan) << 16) | (uni))
223 #define KEYCHAR(k) ((k) & 0xffff)
224 #define CHAR_CTRL(c) ((c) - 'a' + 1)
225
226 static EFI_STATUS key_read(UINT64 *key, BOOLEAN wait) {
227         #define EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL_GUID \
228                 { 0xdd9e7534, 0x7762, 0x4698, { 0x8c, 0x14, 0xf5, 0x85, 0x17, 0xa6, 0x25, 0xaa } }
229
230         struct _EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL;
231
232         typedef EFI_STATUS (EFIAPI *EFI_INPUT_RESET_EX)(
233                 struct _EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This;
234                 BOOLEAN ExtendedVerification;
235         );
236
237         typedef UINT8 EFI_KEY_TOGGLE_STATE;
238
239         typedef struct {
240                 UINT32 KeyShiftState;
241                 EFI_KEY_TOGGLE_STATE KeyToggleState;
242         } EFI_KEY_STATE;
243
244         typedef struct {
245                 EFI_INPUT_KEY Key;
246                 EFI_KEY_STATE KeyState;
247         } EFI_KEY_DATA;
248
249         typedef EFI_STATUS (EFIAPI *EFI_INPUT_READ_KEY_EX)(
250                 struct _EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This;
251                 EFI_KEY_DATA *KeyData;
252         );
253
254         typedef EFI_STATUS (EFIAPI *EFI_SET_STATE)(
255                 struct _EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This;
256                 EFI_KEY_TOGGLE_STATE *KeyToggleState;
257         );
258
259         typedef EFI_STATUS (EFIAPI *EFI_KEY_NOTIFY_FUNCTION)(
260                 EFI_KEY_DATA *KeyData;
261         );
262
263         typedef EFI_STATUS (EFIAPI *EFI_REGISTER_KEYSTROKE_NOTIFY)(
264                 struct _EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This;
265                 EFI_KEY_DATA KeyData;
266                 EFI_KEY_NOTIFY_FUNCTION KeyNotificationFunction;
267                 VOID **NotifyHandle;
268         );
269
270         typedef EFI_STATUS (EFIAPI *EFI_UNREGISTER_KEYSTROKE_NOTIFY)(
271                 struct _EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This;
272                 VOID *NotificationHandle;
273         );
274
275         typedef struct _EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL {
276                 EFI_INPUT_RESET_EX Reset;
277                 EFI_INPUT_READ_KEY_EX ReadKeyStrokeEx;
278                 EFI_EVENT WaitForKeyEx;
279                 EFI_SET_STATE SetState;
280                 EFI_REGISTER_KEYSTROKE_NOTIFY RegisterKeyNotify;
281                 EFI_UNREGISTER_KEYSTROKE_NOTIFY UnregisterKeyNotify;
282         } EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL;
283
284         EFI_GUID EfiSimpleTextInputExProtocolGuid = EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL_GUID;
285         static EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *TextInputEx;
286         static BOOLEAN checked;
287         EFI_KEY_DATA keydata;
288         UINT32 shift = 0;
289         UINT64 keypress;
290         UINTN index;
291         EFI_STATUS err;
292
293         if (!checked) {
294                 err = LibLocateProtocol(&EfiSimpleTextInputExProtocolGuid, (VOID **)&TextInputEx);
295                 if (EFI_ERROR(err))
296                         TextInputEx = NULL;
297
298                 checked = TRUE;
299         }
300
301 fallback:
302         if (!TextInputEx) {
303                 EFI_INPUT_KEY k;
304
305                 /* fallback for firmware which does not support SimpleTextInputExProtocol */
306                 if (wait)
307                         uefi_call_wrapper(BS->WaitForEvent, 3, 1, &ST->ConIn->WaitForKey, &index);
308                 err  = uefi_call_wrapper(ST->ConIn->ReadKeyStroke, 2, ST->ConIn, &k);
309                 if (EFI_ERROR(err))
310                         return err;
311
312                 *key = KEYPRESS(0, k.ScanCode, k.UnicodeChar);
313                 return 0;
314         }
315
316         if (wait) {
317                 /* wait for key press */
318                 err = uefi_call_wrapper(BS->WaitForEvent, 3, 1, &TextInputEx->WaitForKeyEx, &index);
319                 if (EFI_ERROR(err)) {
320                         /* some firmware exposes SimpleTextInputExProtocol, but it doesn't work */
321                         TextInputEx = NULL;
322                         goto fallback;
323                 }
324         }
325
326         err = uefi_call_wrapper(TextInputEx->ReadKeyStrokeEx, 2, TextInputEx, &keydata);
327         if (EFI_ERROR(err)) {
328                 if (err != EFI_NOT_READY) {
329                         /* some firmware exposes SimpleTextInputExProtocol, but it doesn't work */
330                         TextInputEx = NULL;
331                         goto fallback;
332                 }
333
334                 return err;
335         }
336
337         /* do not distinguish between left and right keys */
338         if (keydata.KeyState.KeyShiftState & EFI_SHIFT_STATE_VALID) {
339                 if (keydata.KeyState.KeyShiftState & (EFI_RIGHT_CONTROL_PRESSED|EFI_LEFT_CONTROL_PRESSED))
340                         shift |= EFI_CONTROL_PRESSED;
341                 if (keydata.KeyState.KeyShiftState & (EFI_RIGHT_ALT_PRESSED|EFI_LEFT_ALT_PRESSED))
342                         shift |= EFI_ALT_PRESSED;
343         };
344
345         /* 32 bit modifier keys + 16 bit scan code + 16 bit unicode */
346         keypress = KEYPRESS(shift, keydata.Key.ScanCode, keydata.Key.UnicodeChar);
347         if (keypress == 0) {
348                 /* some firmware exposes SimpleTextInputExProtocol, but it doesn't work */
349                 TextInputEx = NULL;
350                 goto fallback;
351         }
352
353         *key = keypress;
354         return 0;
355 }
356
357 static void cursor_left(UINTN *cursor, UINTN *first)
358 {
359         if ((*cursor) > 0)
360                 (*cursor)--;
361         else if ((*first) > 0)
362                 (*first)--;
363 }
364
365 static void cursor_right(UINTN *cursor, UINTN *first, UINTN x_max, UINTN len)
366 {
367         if ((*cursor)+1 < x_max)
368                 (*cursor)++;
369         else if ((*first) + (*cursor) < len)
370                 (*first)++;
371 }
372
373 static BOOLEAN line_edit(CHAR16 *line_in, CHAR16 **line_out, UINTN x_max, UINTN y_pos) {
374         CHAR16 *line;
375         UINTN size;
376         UINTN len;
377         UINTN first;
378         CHAR16 *print;
379         UINTN cursor;
380         UINTN clear;
381         BOOLEAN exit;
382         BOOLEAN enter;
383
384         if (!line_in)
385                 line_in = L"";
386         size = StrLen(line_in) + 1024;
387         line = AllocatePool(size * sizeof(CHAR16));
388         StrCpy(line, line_in);
389         len = StrLen(line);
390         print = AllocatePool((x_max+1) * sizeof(CHAR16));
391
392         uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, TRUE);
393
394         first = 0;
395         cursor = 0;
396         clear = 0;
397         enter = FALSE;
398         exit = FALSE;
399         while (!exit) {
400                 EFI_STATUS err;
401                 UINT64 key;
402                 UINTN i;
403
404                 i = len - first;
405                 if (i >= x_max-1)
406                         i = x_max-1;
407                 CopyMem(print, line + first, i * sizeof(CHAR16));
408                 while (clear > 0 && i < x_max-1) {
409                         clear--;
410                         print[i++] = ' ';
411                 }
412                 print[i] = '\0';
413
414                 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_pos);
415                 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, print);
416                 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
417
418                 err = key_read(&key, TRUE);
419                 if (EFI_ERROR(err))
420                         continue;
421
422                 switch (key) {
423                 case KEYPRESS(0, SCAN_ESC, 0):
424                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'c'):
425                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'g'):
426                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('c')):
427                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('g')):
428                         exit = TRUE;
429                         break;
430
431                 case KEYPRESS(0, SCAN_HOME, 0):
432                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'a'):
433                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('a')):
434                         /* beginning-of-line */
435                         cursor = 0;
436                         first = 0;
437                         continue;
438
439                 case KEYPRESS(0, SCAN_END, 0):
440                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'e'):
441                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('e')):
442                         /* end-of-line */
443                         cursor = len - first;
444                         if (cursor+1 >= x_max) {
445                                 cursor = x_max-1;
446                                 first = len - (x_max-1);
447                         }
448                         continue;
449
450                 case KEYPRESS(0, SCAN_DOWN, 0):
451                 case KEYPRESS(EFI_ALT_PRESSED, 0, 'f'):
452                 case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_RIGHT, 0):
453                         /* forward-word */
454                         while (line[first + cursor] && line[first + cursor] == ' ')
455                                 cursor_right(&cursor, &first, x_max, len);
456                         while (line[first + cursor] && line[first + cursor] != ' ')
457                                 cursor_right(&cursor, &first, x_max, len);
458                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
459                         continue;
460
461                 case KEYPRESS(0, SCAN_UP, 0):
462                 case KEYPRESS(EFI_ALT_PRESSED, 0, 'b'):
463                 case KEYPRESS(EFI_CONTROL_PRESSED, SCAN_LEFT, 0):
464                         /* backward-word */
465                         if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
466                                 cursor_left(&cursor, &first);
467                                 while ((first + cursor) > 0 && line[first + cursor] == ' ')
468                                         cursor_left(&cursor, &first);
469                         }
470                         while ((first + cursor) > 0 && line[first + cursor-1] != ' ')
471                                 cursor_left(&cursor, &first);
472                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
473                         continue;
474
475                 case KEYPRESS(0, SCAN_RIGHT, 0):
476                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'f'):
477                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('f')):
478                         /* forward-char */
479                         if (first + cursor == len)
480                                 continue;
481                         cursor_right(&cursor, &first, x_max, len);
482                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
483                         continue;
484
485                 case KEYPRESS(0, SCAN_LEFT, 0):
486                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'b'):
487                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('b')):
488                         /* backward-char */
489                         cursor_left(&cursor, &first);
490                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
491                         continue;
492
493                 case KEYPRESS(EFI_ALT_PRESSED, 0, 'd'):
494                         /* kill-word */
495                         clear = 0;
496                         for (i = first + cursor; i < len && line[i] == ' '; i++)
497                                 clear++;
498                         for (; i < len && line[i] != ' '; i++)
499                                 clear++;
500
501                         for (i = first + cursor; i + clear < len; i++)
502                                 line[i] = line[i + clear];
503                         len -= clear;
504                         line[len] = '\0';
505                         continue;
506
507                 case KEYPRESS(EFI_ALT_PRESSED, 0, CHAR_BACKSPACE):
508                         /* backward-kill-word */
509                         clear = 0;
510                         if ((first + cursor) > 0 && line[first + cursor-1] == ' ') {
511                                 cursor_left(&cursor, &first);
512                                 clear++;
513                                 while ((first + cursor) > 0 && line[first + cursor] == ' ') {
514                                         cursor_left(&cursor, &first);
515                                         clear++;
516                                 }
517                         }
518                         while ((first + cursor) > 0 && line[first + cursor-1] != ' ') {
519                                 cursor_left(&cursor, &first);
520                                 clear++;
521                         }
522                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, cursor, y_pos);
523
524                         for (i = first + cursor; i + clear < len; i++)
525                                 line[i] = line[i + clear];
526                         len -= clear;
527                         line[len] = '\0';
528                         continue;
529
530                 case KEYPRESS(0, SCAN_DELETE, 0):
531                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'd'):
532                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('d')):
533                         if (len == 0)
534                                 continue;
535                         if (first + cursor == len)
536                                 continue;
537                         for (i = first + cursor; i < len; i++)
538                                 line[i] = line[i+1];
539                         clear = 1;
540                         len--;
541                         continue;
542
543                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'k'):
544                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('k')):
545                         /* kill-line */
546                         line[first + cursor] = '\0';
547                         clear = len - (first + cursor);
548                         len = first + cursor;
549                         continue;
550
551                 case KEYPRESS(0, 0, CHAR_LINEFEED):
552                 case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
553                         if (StrCmp(line, line_in) != 0) {
554                                 *line_out = line;
555                                 line = NULL;
556                         }
557                         enter = TRUE;
558                         exit = TRUE;
559                         break;
560
561                 case KEYPRESS(0, 0, CHAR_BACKSPACE):
562                         if (len == 0)
563                                 continue;
564                         if (first == 0 && cursor == 0)
565                                 continue;
566                         for (i = first + cursor-1; i < len; i++)
567                                 line[i] = line[i+1];
568                         clear = 1;
569                         len--;
570                         if (cursor > 0)
571                                 cursor--;
572                         if (cursor > 0 || first == 0)
573                                 continue;
574                         /* show full line if it fits */
575                         if (len < x_max) {
576                                 cursor = first;
577                                 first = 0;
578                                 continue;
579                         }
580                         /* jump left to see what we delete */
581                         if (first > 10) {
582                                 first -= 10;
583                                 cursor = 10;
584                         } else {
585                                 cursor = first;
586                                 first = 0;
587                         }
588                         continue;
589
590                 case KEYPRESS(0, 0, ' ') ... KEYPRESS(0, 0, '~'):
591                 case KEYPRESS(0, 0, 0x80) ... KEYPRESS(0, 0, 0xffff):
592                         if (len+1 == size)
593                                 continue;
594                         for (i = len; i > first + cursor; i--)
595                                 line[i] = line[i-1];
596                         line[first + cursor] = KEYCHAR(key);
597                         len++;
598                         line[len] = '\0';
599                         if (cursor+1 < x_max)
600                                 cursor++;
601                         else if (first + cursor < len)
602                                 first++;
603                         continue;
604                 }
605         }
606
607         uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, FALSE);
608         FreePool(print);
609         FreePool(line);
610         return enter;
611 }
612
613 static UINTN entry_lookup_key(Config *config, UINTN start, CHAR16 key) {
614         UINTN i;
615
616         if (key == 0)
617                 return -1;
618
619         /* select entry by number key */
620         if (key >= '1' && key <= '9') {
621                 i = key - '0';
622                 if (i > config->entry_count)
623                         i = config->entry_count;
624                 return i-1;
625         }
626
627         /* find matching key in config entries */
628         for (i = start; i < config->entry_count; i++)
629                 if (config->entries[i]->key == key)
630                         return i;
631
632         for (i = 0; i < start; i++)
633                 if (config->entries[i]->key == key)
634                         return i;
635
636         return -1;
637 }
638
639 static VOID print_status(Config *config, CHAR16 *loaded_image_path) {
640         UINT64 key;
641         UINTN i;
642         CHAR16 *s;
643         CHAR8 *b;
644         UINTN size;
645
646         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
647         uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
648
649         Print(L"gummiboot version:      " VERSION "\n");
650         Print(L"loaded image:           %s\n", loaded_image_path);
651         Print(L"UEFI version:           %d.%02d\n", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
652         Print(L"firmware vendor:        %s\n", ST->FirmwareVendor);
653         Print(L"firmware version:       %d.%02d\n", ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
654         if (efivar_get_raw(&global_guid, L"SecureBoot", &b, &size) == EFI_SUCCESS) {
655                 Print(L"SecureBoot:             %s\n", *b > 0 ? L"enabled" : L"disabled");
656                 FreePool(b);
657         }
658
659         if (efivar_get_raw(&global_guid, L"SetupMode", &b, &size) == EFI_SUCCESS) {
660                 Print(L"SetupMode:              %s\n", *b > 0 ? L"setup" : L"user");
661                 FreePool(b);
662         }
663
664         if (efivar_get_raw(&global_guid, L"OsIndicationsSupported", &b, &size) == EFI_SUCCESS) {
665                 Print(L"OsIndicationsSupported: %d\n", (UINT64)*b);
666                 FreePool(b);
667         }
668         Print(L"\n");
669
670         Print(L"timeout:                %d\n", config->timeout_sec);
671         if (config->timeout_sec_efivar >= 0)
672                 Print(L"timeout (EFI var):      %d\n", config->timeout_sec_efivar);
673         Print(L"timeout (config):       %d\n", config->timeout_sec_config);
674         if (config->entry_default_pattern)
675                 Print(L"default pattern:        '%s'\n", config->entry_default_pattern);
676         Print(L"\n");
677
678         Print(L"config entry count:     %d\n", config->entry_count);
679         Print(L"entry selected idx:     %d\n", config->idx_default);
680         if (config->idx_default_efivar >= 0)
681                 Print(L"entry EFI var idx:      %d\n", config->idx_default_efivar);
682         Print(L"\n");
683
684         if (efivar_get_int(L"LoaderConfigTimeout", &i) == EFI_SUCCESS)
685                 Print(L"LoaderConfigTimeout:    %d\n", i);
686         if (config->entry_oneshot)
687                 Print(L"LoaderEntryOneShot:     %s\n", config->entry_oneshot);
688         if (efivar_get(L"LoaderDeviceIdentifier", &s) == EFI_SUCCESS) {
689                 Print(L"LoaderDeviceIdentifier: %s\n", s);
690                 FreePool(s);
691         }
692         if (efivar_get(L"LoaderDevicePartUUID", &s) == EFI_SUCCESS) {
693                 Print(L"LoaderDevicePartUUID:   %s\n", s);
694                 FreePool(s);
695         }
696         if (efivar_get(L"LoaderEntryDefault", &s) == EFI_SUCCESS) {
697                 Print(L"LoaderEntryDefault:     %s\n", s);
698                 FreePool(s);
699         }
700
701         Print(L"\n--- press key ---\n\n");
702         key_read(&key, TRUE);
703
704         for (i = 0; i < config->entry_count; i++) {
705                 ConfigEntry *entry;
706
707                 if (key == KEYPRESS(0, SCAN_ESC, 0) || key == KEYPRESS(0, 0, 'q'))
708                         break;
709
710                 entry = config->entries[i];
711                 Print(L"config entry:           %d/%d\n", i+1, config->entry_count);
712                 if (entry->file)
713                         Print(L"file                    '%s'\n", entry->file);
714                 Print(L"title show              '%s'\n", entry->title_show);
715                 if (entry->title)
716                         Print(L"title                   '%s'\n", entry->title);
717                 if (entry->version)
718                         Print(L"version                 '%s'\n", entry->version);
719                 if (entry->machine_id)
720                         Print(L"machine-id              '%s'\n", entry->machine_id);
721                 if (entry->device) {
722                         EFI_DEVICE_PATH *device_path;
723                         CHAR16 *str;
724
725                         device_path = DevicePathFromHandle(entry->device);
726                         if (device_path) {
727                                 str = DevicePathToStr(device_path);
728                                 Print(L"device handle           '%s'\n", str);
729                                 FreePool(str);
730                         }
731                 }
732                 if (entry->loader)
733                         Print(L"loader                  '%s'\n", entry->loader);
734                 if (entry->options)
735                         Print(L"options                 '%s'\n", entry->options);
736                 Print(L"auto-select             %s\n", entry->no_autoselect ? L"no" : L"yes");
737                 if (entry->call)
738                         Print(L"internal call           yes\n");
739
740                 Print(L"\n--- press key ---\n\n");
741                 key_read(&key, TRUE);
742         }
743
744         uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
745 }
746
747 static EFI_STATUS console_text_mode(VOID) {
748         #define EFI_CONSOLE_CONTROL_PROTOCOL_GUID \
749                 { 0xf42f7782, 0x12e, 0x4c12, { 0x99, 0x56, 0x49, 0xf9, 0x43, 0x4, 0xf7, 0x21 } };
750
751         struct _EFI_CONSOLE_CONTROL_PROTOCOL;
752
753         typedef enum {
754                 EfiConsoleControlScreenText,
755                 EfiConsoleControlScreenGraphics,
756                 EfiConsoleControlScreenMaxValue,
757         } EFI_CONSOLE_CONTROL_SCREEN_MODE;
758
759         typedef EFI_STATUS (EFIAPI *EFI_CONSOLE_CONTROL_PROTOCOL_GET_MODE)(
760                 struct _EFI_CONSOLE_CONTROL_PROTOCOL *This,
761                 EFI_CONSOLE_CONTROL_SCREEN_MODE *Mode,
762                 BOOLEAN *UgaExists,
763                 BOOLEAN *StdInLocked
764         );
765
766         typedef EFI_STATUS (EFIAPI *EFI_CONSOLE_CONTROL_PROTOCOL_SET_MODE)(
767                 struct _EFI_CONSOLE_CONTROL_PROTOCOL *This,
768                 EFI_CONSOLE_CONTROL_SCREEN_MODE Mode
769         );
770
771         typedef EFI_STATUS (EFIAPI *EFI_CONSOLE_CONTROL_PROTOCOL_LOCK_STD_IN)(
772                 struct _EFI_CONSOLE_CONTROL_PROTOCOL *This,
773                 CHAR16 *Password
774         );
775
776         typedef struct _EFI_CONSOLE_CONTROL_PROTOCOL {
777                 EFI_CONSOLE_CONTROL_PROTOCOL_GET_MODE GetMode;
778                 EFI_CONSOLE_CONTROL_PROTOCOL_SET_MODE SetMode;
779                 EFI_CONSOLE_CONTROL_PROTOCOL_LOCK_STD_IN LockStdIn;
780         } EFI_CONSOLE_CONTROL_PROTOCOL;
781
782         EFI_GUID ConsoleControlProtocolGuid = EFI_CONSOLE_CONTROL_PROTOCOL_GUID;
783         EFI_CONSOLE_CONTROL_PROTOCOL *ConsoleControl = NULL;
784         EFI_STATUS err;
785
786         err = LibLocateProtocol(&ConsoleControlProtocolGuid, (VOID **)&ConsoleControl);
787         if (EFI_ERROR(err))
788                 return err;
789         return uefi_call_wrapper(ConsoleControl->SetMode, 2, ConsoleControl, EfiConsoleControlScreenText);
790 }
791
792 static BOOLEAN menu_run(Config *config, ConfigEntry **chosen_entry, CHAR16 *loaded_image_path) {
793         EFI_STATUS err;
794         UINTN visible_max;
795         UINTN idx_highlight;
796         UINTN idx_highlight_prev;
797         UINTN idx_first;
798         UINTN idx_last;
799         BOOLEAN refresh;
800         BOOLEAN highlight;
801         UINTN i;
802         UINTN line_width;
803         CHAR16 **lines;
804         UINTN x_start;
805         UINTN y_start;
806         UINTN x_max;
807         UINTN y_max;
808         CHAR16 *status;
809         CHAR16 *clearline;
810         INTN timeout_remain;
811         INT16 idx;
812         BOOLEAN exit = FALSE;
813         BOOLEAN run = TRUE;
814         BOOLEAN wait = FALSE;
815
816         console_text_mode();
817         uefi_call_wrapper(ST->ConIn->Reset, 2, ST->ConIn, FALSE);
818         uefi_call_wrapper(ST->ConOut->EnableCursor, 2, ST->ConOut, FALSE);
819         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
820         uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
821
822         err = uefi_call_wrapper(ST->ConOut->QueryMode, 4, ST->ConOut, ST->ConOut->Mode->Mode, &x_max, &y_max);
823         if (EFI_ERROR(err)) {
824                 x_max = 80;
825                 y_max = 25;
826         }
827
828         /* we check 10 times per second for a keystroke */
829         if (config->timeout_sec > 0)
830                 timeout_remain = config->timeout_sec * 10;
831         else
832                 timeout_remain = -1;
833
834         idx_highlight = config->idx_default;
835         idx_highlight_prev = 0;
836
837         visible_max = y_max - 2;
838
839         if ((UINTN)config->idx_default >= visible_max)
840                 idx_first = config->idx_default-1;
841         else
842                 idx_first = 0;
843
844         idx_last = idx_first + visible_max-1;
845
846         refresh = TRUE;
847         highlight = FALSE;
848
849         /* length of the longest entry */
850         line_width = 5;
851         for (i = 0; i < config->entry_count; i++) {
852                 UINTN entry_len;
853
854                 entry_len = StrLen(config->entries[i]->title_show);
855                 if (line_width < entry_len)
856                         line_width = entry_len;
857         }
858         if (line_width > x_max-6)
859                 line_width = x_max-6;
860
861         /* offsets to center the entries on the screen */
862         x_start = (x_max - (line_width)) / 2;
863         if (config->entry_count < visible_max)
864                 y_start = ((visible_max - config->entry_count) / 2) + 1;
865         else
866                 y_start = 0;
867
868         /* menu entries title lines */
869         lines = AllocatePool(sizeof(CHAR16 *) * config->entry_count);
870         for (i = 0; i < config->entry_count; i++) {
871                 UINTN j, k;
872
873                 lines[i] = AllocatePool(((x_max+1) * sizeof(CHAR16)));
874                 for (j = 0; j < x_start; j++)
875                         lines[i][j] = ' ';
876
877                 for (k = 0; config->entries[i]->title_show[k] != '\0' && j < x_max; j++, k++)
878                         lines[i][j] = config->entries[i]->title_show[k];
879
880                 for (; j < x_max; j++)
881                         lines[i][j] = ' ';
882                 lines[i][x_max] = '\0';
883         }
884
885         status = NULL;
886         clearline = AllocatePool((x_max+1) * sizeof(CHAR16));
887         for (i = 0; i < x_max; i++)
888                 clearline[i] = ' ';
889         clearline[i] = 0;
890
891         while (!exit) {
892                 UINT64 key;
893
894                 if (refresh) {
895                         for (i = 0; i < config->entry_count; i++) {
896                                 if (i < idx_first || i > idx_last)
897                                         continue;
898                                 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + i - idx_first);
899                                 if (i == idx_highlight)
900                                         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut,
901                                                           EFI_BLACK|EFI_BACKGROUND_LIGHTGRAY);
902                                 else
903                                         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut,
904                                                           EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
905                                 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[i]);
906                                 if ((INTN)i == config->idx_default_efivar) {
907                                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + i - idx_first);
908                                         uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
909                                 }
910                         }
911                         refresh = FALSE;
912                 } else if (highlight) {
913                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + idx_highlight_prev - idx_first);
914                         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
915                         uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[idx_highlight_prev]);
916                         if ((INTN)idx_highlight_prev == config->idx_default_efivar) {
917                                 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + idx_highlight_prev - idx_first);
918                                 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
919                         }
920
921                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_start + idx_highlight - idx_first);
922                         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_BLACK|EFI_BACKGROUND_LIGHTGRAY);
923                         uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, lines[idx_highlight]);
924                         if ((INTN)idx_highlight == config->idx_default_efivar) {
925                                 uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, x_start-3, y_start + idx_highlight - idx_first);
926                                 uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, L"=>");
927                         }
928                         highlight = FALSE;
929                 }
930
931                 if (timeout_remain > 0) {
932                         FreePool(status);
933                         status = PoolPrint(L"Boot in %d sec.", (timeout_remain + 5) / 10);
934                 }
935
936                 /* print status at last line of screen */
937                 if (status) {
938                         UINTN len;
939                         UINTN x;
940
941                         /* center line */
942                         len = StrLen(status);
943                         if (len < x_max)
944                                 x = (x_max - len) / 2;
945                         else
946                                 x = 0;
947                         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
948                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
949                         uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline + (x_max - x));
950                         uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, status);
951                         uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1 + x + len);
952                 }
953
954                 err = key_read(&key, wait);
955                 if (EFI_ERROR(err)) {
956                         /* timeout reached */
957                         if (timeout_remain == 0) {
958                                 exit = TRUE;
959                                 break;
960                         }
961
962                         /* sleep and update status */
963                         if (timeout_remain > 0) {
964                                 uefi_call_wrapper(BS->Stall, 1, 100 * 1000);
965                                 timeout_remain--;
966                                 continue;
967                         }
968
969                         /* timeout disabled, wait for next key */
970                         wait = TRUE;
971                         continue;
972                 }
973
974                 timeout_remain = -1;
975
976                 /* clear status after keystroke */
977                 if (status) {
978                         FreePool(status);
979                         status = NULL;
980                         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
981                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
982                         uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
983                 }
984
985                 idx_highlight_prev = idx_highlight;
986
987                 switch (key) {
988                 case KEYPRESS(0, SCAN_UP, 0):
989                 case KEYPRESS(0, 0, 'k'):
990                         if (idx_highlight > 0)
991                                 idx_highlight--;
992                         break;
993
994                 case KEYPRESS(0, SCAN_DOWN, 0):
995                 case KEYPRESS(0, 0, 'j'):
996                         if (idx_highlight < config->entry_count-1)
997                                 idx_highlight++;
998                         break;
999
1000                 case KEYPRESS(0, SCAN_HOME, 0):
1001                 case KEYPRESS(EFI_ALT_PRESSED, 0, '<'):
1002                         if (idx_highlight > 0) {
1003                                 refresh = TRUE;
1004                                 idx_highlight = 0;
1005                         }
1006                         break;
1007
1008                 case KEYPRESS(0, SCAN_END, 0):
1009                 case KEYPRESS(EFI_ALT_PRESSED, 0, '>'):
1010                         if (idx_highlight < config->entry_count-1) {
1011                                 refresh = TRUE;
1012                                 idx_highlight = config->entry_count-1;
1013                         }
1014                         break;
1015
1016                 case KEYPRESS(0, SCAN_PAGE_UP, 0):
1017                         if (idx_highlight > visible_max)
1018                                 idx_highlight -= visible_max;
1019                         else
1020                                 idx_highlight = 0;
1021                         break;
1022
1023                 case KEYPRESS(0, SCAN_PAGE_DOWN, 0):
1024                         idx_highlight += visible_max;
1025                         if (idx_highlight > config->entry_count-1)
1026                                 idx_highlight = config->entry_count-1;
1027                         break;
1028
1029                 case KEYPRESS(0, 0, CHAR_LINEFEED):
1030                 case KEYPRESS(0, 0, CHAR_CARRIAGE_RETURN):
1031                         exit = TRUE;
1032                         break;
1033
1034                 case KEYPRESS(0, SCAN_F1, 0):
1035                 case KEYPRESS(0, 0, 'h'):
1036                 case KEYPRESS(0, 0, '?'):
1037                         status = StrDuplicate(L"(d)efault, (t/T)timeout, (e)dit, (v)ersion (Q)uit (P)rint (h)elp");
1038                         break;
1039
1040                 case KEYPRESS(0, 0, 'Q'):
1041                         exit = TRUE;
1042                         run = FALSE;
1043                         break;
1044
1045                 case KEYPRESS(0, 0, 'd'):
1046                         if (config->idx_default_efivar != (INTN)idx_highlight) {
1047                                 /* store the selected entry in a persistent EFI variable */
1048                                 efivar_set(L"LoaderEntryDefault", config->entries[idx_highlight]->file, TRUE);
1049                                 config->idx_default_efivar = idx_highlight;
1050                                 status = StrDuplicate(L"Default boot entry selected.");
1051                         } else {
1052                                 /* clear the default entry EFI variable */
1053                                 efivar_set(L"LoaderEntryDefault", NULL, TRUE);
1054                                 config->idx_default_efivar = -1;
1055                                 status = StrDuplicate(L"Default boot entry cleared.");
1056                         }
1057                         refresh = TRUE;
1058                         break;
1059
1060                 case KEYPRESS(0, 0, '-'):
1061                 case KEYPRESS(0, 0, 'T'):
1062                         if (config->timeout_sec_efivar > 0) {
1063                                 config->timeout_sec_efivar--;
1064                                 efivar_set_int(L"LoaderConfigTimeout", config->timeout_sec_efivar, TRUE);
1065                                 if (config->timeout_sec_efivar > 0)
1066                                         status = PoolPrint(L"Menu timeout set to %d sec.", config->timeout_sec_efivar);
1067                                 else
1068                                         status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
1069                         } else if (config->timeout_sec_efivar <= 0){
1070                                 config->timeout_sec_efivar = -1;
1071                                 efivar_set(L"LoaderConfigTimeout", NULL, TRUE);
1072                                 if (config->timeout_sec_config > 0)
1073                                         status = PoolPrint(L"Menu timeout of %d sec is defined by configuration file.",
1074                                                            config->timeout_sec_config);
1075                                 else
1076                                         status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
1077                         }
1078                         break;
1079
1080                 case KEYPRESS(0, 0, '+'):
1081                 case KEYPRESS(0, 0, 't'):
1082                         if (config->timeout_sec_efivar == -1 && config->timeout_sec_config == 0)
1083                                 config->timeout_sec_efivar++;
1084                         config->timeout_sec_efivar++;
1085                         efivar_set_int(L"LoaderConfigTimeout", config->timeout_sec_efivar, TRUE);
1086                         if (config->timeout_sec_efivar > 0)
1087                                 status = PoolPrint(L"Menu timeout set to %d sec.",
1088                                                    config->timeout_sec_efivar);
1089                         else
1090                                 status = StrDuplicate(L"Menu disabled. Hold down key at bootup to show menu.");
1091                         break;
1092
1093                 case KEYPRESS(0, 0, 'e'):
1094                         /* only the options of configured entries can be edited */
1095                         if (config->entries[idx_highlight]->type == LOADER_UNDEFINED)
1096                                 break;
1097                         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_LIGHTGRAY|EFI_BACKGROUND_BLACK);
1098                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
1099                         uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
1100                         if (line_edit(config->entries[idx_highlight]->options, &config->options_edit, x_max-1, y_max-1))
1101                                 exit = TRUE;
1102                         uefi_call_wrapper(ST->ConOut->SetCursorPosition, 3, ST->ConOut, 0, y_max-1);
1103                         uefi_call_wrapper(ST->ConOut->OutputString, 2, ST->ConOut, clearline+1);
1104                         break;
1105
1106                 case KEYPRESS(0, 0, 'v'):
1107                         status = PoolPrint(L"gummiboot " VERSION ", UEFI %d.%02d, %s %d.%02d",
1108                                            ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff,
1109                                            ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1110                         break;
1111
1112                 case KEYPRESS(0, 0, 'P'):
1113                         print_status(config, loaded_image_path);
1114                         refresh = TRUE;
1115                         break;
1116
1117                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, 'l'):
1118                 case KEYPRESS(EFI_CONTROL_PRESSED, 0, CHAR_CTRL('l')):
1119                         refresh = TRUE;
1120                         break;
1121
1122                 default:
1123                         /* jump with a hotkey directly to a matching entry */
1124                         idx = entry_lookup_key(config, idx_highlight+1, KEYCHAR(key));
1125                         if (idx < 0)
1126                                 break;
1127                         idx_highlight = idx;
1128                         refresh = TRUE;
1129                 }
1130
1131                 if (idx_highlight > idx_last) {
1132                         idx_last = idx_highlight;
1133                         idx_first = 1 + idx_highlight - visible_max;
1134                         refresh = TRUE;
1135                 }
1136                 if (idx_highlight < idx_first) {
1137                         idx_first = idx_highlight;
1138                         idx_last = idx_highlight + visible_max-1;
1139                         refresh = TRUE;
1140                 }
1141
1142                 idx_last = idx_first + visible_max-1;
1143
1144                 if (!refresh && idx_highlight != idx_highlight_prev)
1145                         highlight = TRUE;
1146         }
1147
1148         *chosen_entry = config->entries[idx_highlight];
1149
1150         for (i = 0; i < config->entry_count; i++)
1151                 FreePool(lines[i]);
1152         FreePool(lines);
1153         FreePool(clearline);
1154
1155         uefi_call_wrapper(ST->ConOut->SetAttribute, 2, ST->ConOut, EFI_WHITE|EFI_BACKGROUND_BLACK);
1156         uefi_call_wrapper(ST->ConOut->ClearScreen, 1, ST->ConOut);
1157         return run;
1158 }
1159
1160 static VOID config_add_entry(Config *config, ConfigEntry *entry) {
1161         if ((config->entry_count & 15) == 0) {
1162                 UINTN i;
1163
1164                 i = config->entry_count + 16;
1165                 if (config->entry_count == 0)
1166                         config->entries = AllocatePool(sizeof(VOID *) * i);
1167                 else
1168                         config->entries = ReallocatePool(config->entries,
1169                                                          sizeof(VOID *) * config->entry_count, sizeof(VOID *) * i);
1170         }
1171         config->entries[config->entry_count++] = entry;
1172 }
1173
1174 static VOID config_entry_free(ConfigEntry *entry) {
1175         FreePool(entry->title_show);
1176         FreePool(entry->title);
1177         FreePool(entry->machine_id);
1178         FreePool(entry->loader);
1179         FreePool(entry->options);
1180 }
1181
1182 static BOOLEAN is_digit(CHAR16 c)
1183 {
1184         return (c >= '0') && (c <= '9');
1185 }
1186
1187 static UINTN c_order(CHAR16 c)
1188 {
1189         if (c == '\0')
1190                 return 0;
1191         if (is_digit(c))
1192                 return 0;
1193         else if ((c >= 'a') && (c <= 'z'))
1194                 return c;
1195         else
1196                 return c + 0x10000;
1197 }
1198
1199 static INTN str_verscmp(CHAR16 *s1, CHAR16 *s2)
1200 {
1201         CHAR16 *os1 = s1;
1202         CHAR16 *os2 = s2;
1203
1204         while (*s1 || *s2) {
1205                 INTN first;
1206
1207                 while ((*s1 && !is_digit(*s1)) || (*s2 && !is_digit(*s2))) {
1208                         INTN order;
1209
1210                         order = c_order(*s1) - c_order(*s2);
1211                         if (order)
1212                                 return order;
1213                         s1++;
1214                         s2++;
1215                 }
1216
1217                 while (*s1 == '0')
1218                         s1++;
1219                 while (*s2 == '0')
1220                         s2++;
1221
1222                 first = 0;
1223                 while (is_digit(*s1) && is_digit(*s2)) {
1224                         if (first == 0)
1225                                 first = *s1 - *s2;
1226                         s1++;
1227                         s2++;
1228                 }
1229
1230                 if (is_digit(*s1))
1231                         return 1;
1232                 if (is_digit(*s2))
1233                         return -1;
1234
1235                 if (first)
1236                         return first;
1237         }
1238
1239         return StrCmp(os1, os2);
1240 }
1241
1242 static INTN utf8_to_16(CHAR8 *stra, CHAR16 *c) {
1243         CHAR16 unichar;
1244         UINTN len;
1245         UINTN i;
1246
1247         if (stra[0] < 0x80)
1248                 len = 1;
1249         else if ((stra[0] & 0xe0) == 0xc0)
1250                 len = 2;
1251         else if ((stra[0] & 0xf0) == 0xe0)
1252                 len = 3;
1253         else if ((stra[0] & 0xf8) == 0xf0)
1254                 len = 4;
1255         else if ((stra[0] & 0xfc) == 0xf8)
1256                 len = 5;
1257         else if ((stra[0] & 0xfe) == 0xfc)
1258                 len = 6;
1259         else
1260                 return -1;
1261
1262         switch (len) {
1263         case 1:
1264                 unichar = stra[0];
1265                 break;
1266         case 2:
1267                 unichar = stra[0] & 0x1f;
1268                 break;
1269         case 3:
1270                 unichar = stra[0] & 0x0f;
1271                 break;
1272         case 4:
1273                 unichar = stra[0] & 0x07;
1274                 break;
1275         case 5:
1276                 unichar = stra[0] & 0x03;
1277                 break;
1278         case 6:
1279                 unichar = stra[0] & 0x01;
1280                 break;
1281         }
1282
1283         for (i = 1; i < len; i++) {
1284                 if ((stra[i] & 0xc0) != 0x80)
1285                         return -1;
1286                 unichar <<= 6;
1287                 unichar |= stra[i] & 0x3f;
1288         }
1289
1290         *c = unichar;
1291         return len;
1292 }
1293
1294 static CHAR16 *stra_to_str(CHAR8 *stra) {
1295         UINTN strlen;
1296         UINTN len;
1297         UINTN i;
1298         CHAR16 *str;
1299
1300         len = strlena(stra);
1301         str = AllocatePool((len + 1) * sizeof(CHAR16));
1302
1303         strlen = 0;
1304         i = 0;
1305         while (i < len) {
1306                 INTN utf8len;
1307
1308                 utf8len = utf8_to_16(stra + i, str + strlen);
1309                 if (utf8len <= 0) {
1310                         /* invalid utf8 sequence, skip the garbage */
1311                         i++;
1312                         continue;
1313                 }
1314
1315                 strlen++;
1316                 i += utf8len;
1317         }
1318         str[strlen] = '\0';
1319         return str;
1320 }
1321
1322 static CHAR16 *stra_to_path(CHAR8 *stra) {
1323         CHAR16 *str;
1324         UINTN strlen;
1325         UINTN len;
1326         UINTN i;
1327
1328         len = strlena(stra);
1329         str = AllocatePool((len + 2) * sizeof(CHAR16));
1330
1331         str[0] = '\\';
1332         strlen = 1;
1333         i = 0;
1334         while (i < len) {
1335                 INTN utf8len;
1336
1337                 utf8len = utf8_to_16(stra + i, str + strlen);
1338                 if (utf8len <= 0) {
1339                         /* invalid utf8 sequence, skip the garbage */
1340                         i++;
1341                         continue;
1342                 }
1343
1344                 if (str[strlen] == '/')
1345                         str[strlen] = '\\';
1346                 if (str[strlen] == '\\' && str[strlen-1] == '\\') {
1347                         /* skip double slashes */
1348                         i += utf8len;
1349                         continue;
1350                 }
1351
1352                 strlen++;
1353                 i += utf8len;
1354         }
1355         str[strlen] = '\0';
1356         return str;
1357 }
1358
1359 static CHAR8 *strchra(CHAR8 *s, CHAR8 c) {
1360         do {
1361                 if (*s == c)
1362                         return s;
1363         } while (*s++);
1364         return NULL;
1365 }
1366
1367 static CHAR8 *line_get_key_value(CHAR8 *content, UINTN *pos, CHAR8 **key_ret, CHAR8 **value_ret) {
1368         CHAR8 *line;
1369         UINTN linelen;
1370         CHAR8 *value;
1371
1372 skip:
1373         line = content + *pos;
1374         if (*line == '\0')
1375                 return NULL;
1376
1377         linelen = 0;
1378         while (line[linelen] && !strchra((CHAR8 *)"\n\r", line[linelen]))
1379                linelen++;
1380
1381         /* move pos to next line */
1382         *pos += linelen;
1383         if (content[*pos])
1384                 (*pos)++;
1385
1386         /* empty line */
1387         if (linelen == 0)
1388                 goto skip;
1389
1390         /* terminate line */
1391         line[linelen] = '\0';
1392
1393         /* remove leading whitespace */
1394         while (strchra((CHAR8 *)" \t", *line)) {
1395                 line++;
1396                 linelen--;
1397         }
1398
1399         /* remove trailing whitespace */
1400         while (linelen > 0 && strchra((CHAR8 *)" \t", line[linelen-1]))
1401                 linelen--;
1402         line[linelen] = '\0';
1403
1404         if (*line == '#')
1405                 goto skip;
1406
1407         /* split key/value */
1408         value = line;
1409         while (*value && !strchra((CHAR8 *)" \t", *value))
1410                 value++;
1411         if (*value == '\0')
1412                 goto skip;
1413         *value = '\0';
1414         value++;
1415         while (*value && strchra((CHAR8 *)" \t", *value))
1416                 value++;
1417
1418         *key_ret = line;
1419         *value_ret = value;
1420         return line;
1421 }
1422
1423 static VOID config_defaults_load_from_file(Config *config, CHAR8 *content) {
1424         CHAR8 *line;
1425         UINTN pos = 0;
1426         CHAR8 *key, *value;
1427
1428         line = content;
1429         while ((line = line_get_key_value(content, &pos, &key, &value))) {
1430                 if (strcmpa((CHAR8 *)"timeout", key) == 0) {
1431                         CHAR16 *s;
1432
1433                         s = stra_to_str(value);
1434                         config->timeout_sec_config = Atoi(s);
1435                         config->timeout_sec = config->timeout_sec_config;
1436                         FreePool(s);
1437                         continue;
1438                 }
1439                 if (strcmpa((CHAR8 *)"default", key) == 0) {
1440                         config->entry_default_pattern = stra_to_str(value);
1441                         StrLwr(config->entry_default_pattern);
1442                         continue;
1443                 }
1444         }
1445 }
1446
1447 static VOID config_entry_add_from_file(Config *config, EFI_HANDLE *device, CHAR16 *file, CHAR8 *content, CHAR16 *loaded_image_path) {
1448         ConfigEntry *entry;
1449         CHAR8 *line;
1450         UINTN pos = 0;
1451         CHAR8 *key, *value;
1452         UINTN len;
1453         CHAR16 *initrd = NULL;
1454
1455         entry = AllocateZeroPool(sizeof(ConfigEntry));
1456
1457         line = content;
1458         while ((line = line_get_key_value(content, &pos, &key, &value))) {
1459                 if (strcmpa((CHAR8 *)"title", key) == 0) {
1460                         FreePool(entry->title);
1461                         entry->title = stra_to_str(value);
1462                         continue;
1463                 }
1464
1465                 if (strcmpa((CHAR8 *)"version", key) == 0) {
1466                         FreePool(entry->version);
1467                         entry->version = stra_to_str(value);
1468                         continue;
1469                 }
1470
1471                 if (strcmpa((CHAR8 *)"machine-id", key) == 0) {
1472                         FreePool(entry->machine_id);
1473                         entry->machine_id = stra_to_str(value);
1474                         continue;
1475                 }
1476
1477                 if (strcmpa((CHAR8 *)"linux", key) == 0) {
1478                         FreePool(entry->loader);
1479                         entry->type = LOADER_LINUX;
1480                         entry->loader = stra_to_path(value);
1481                         entry->key = 'l';
1482                         continue;
1483                 }
1484
1485                 if (strcmpa((CHAR8 *)"efi", key) == 0) {
1486                         entry->type = LOADER_EFI;
1487                         FreePool(entry->loader);
1488                         entry->loader = stra_to_path(value);
1489
1490                         /* do not add an entry for ourselves */
1491                         if (StriCmp(entry->loader, loaded_image_path) == 0) {
1492                                 entry->type = LOADER_UNDEFINED;
1493                                 break;
1494                         }
1495                         continue;
1496                 }
1497
1498                 if (strcmpa((CHAR8 *)"initrd", key) == 0) {
1499                         CHAR16 *new;
1500
1501                         new = stra_to_path(value);
1502                         if (initrd) {
1503                                 CHAR16 *s;
1504
1505                                 s = PoolPrint(L"%s initrd=%s", initrd, new);
1506                                 FreePool(initrd);
1507                                 initrd = s;
1508                         } else
1509                                 initrd = PoolPrint(L"initrd=%s", new);
1510                         FreePool(new);
1511                         continue;
1512                 }
1513
1514                 if (strcmpa((CHAR8 *)"options", key) == 0) {
1515                         CHAR16 *new;
1516
1517                         new = stra_to_str(value);
1518                         if (entry->options) {
1519                                 CHAR16 *s;
1520
1521                                 s = PoolPrint(L"%s %s", entry->options, new);
1522                                 FreePool(entry->options);
1523                                 entry->options = s;
1524                         } else {
1525                                 entry->options = new;
1526                                 new = NULL;
1527                         }
1528                         FreePool(new);
1529                         continue;
1530                 }
1531         }
1532
1533         if (entry->type == LOADER_UNDEFINED) {
1534                 config_entry_free(entry);
1535                 FreePool(initrd);
1536                 FreePool(entry);
1537                 return;
1538         }
1539
1540         /* add initrd= to options */
1541         if (entry->type == LOADER_LINUX && initrd) {
1542                 if (entry->options) {
1543                         CHAR16 *s;
1544
1545                         s = PoolPrint(L"%s %s", initrd, entry->options);
1546                         FreePool(entry->options);
1547                         entry->options = s;
1548                 } else {
1549                         entry->options = initrd;
1550                         initrd = NULL;
1551                 }
1552         }
1553         FreePool(initrd);
1554
1555         if (entry->machine_id) {
1556                 CHAR16 *var;
1557
1558                 /* append additional options from EFI variables for this machine-id */
1559                 var = PoolPrint(L"LoaderEntryOptions-%s", entry->machine_id);
1560                 if (var) {
1561                         CHAR16 *s;
1562
1563                         if (efivar_get(var, &s) == EFI_SUCCESS) {
1564                                 if (entry->options) {
1565                                         CHAR16 *s2;
1566
1567                                         s2 = PoolPrint(L"%s %s", entry->options, s);
1568                                         FreePool(entry->options);
1569                                         entry->options = s2;
1570                                 } else
1571                                         entry->options = s;
1572                         }
1573                         FreePool(var);
1574                 }
1575
1576                 var = PoolPrint(L"LoaderEntryOptionsOneShot-%s", entry->machine_id);
1577                 if (var) {
1578                         CHAR16 *s;
1579
1580                         if (efivar_get(var, &s) == EFI_SUCCESS) {
1581                                 if (entry->options) {
1582                                         CHAR16 *s2;
1583
1584                                         s2 = PoolPrint(L"%s %s", entry->options, s);
1585                                         FreePool(entry->options);
1586                                         entry->options = s2;
1587                                 } else
1588                                         entry->options = s;
1589                                 efivar_set(var, NULL, TRUE);
1590                         }
1591                         FreePool(var);
1592                 }
1593         }
1594
1595         entry->device = device;
1596         entry->file = StrDuplicate(file);
1597         len = StrLen(entry->file);
1598         /* remove ".conf" */
1599         if (len > 5)
1600                 entry->file[len - 5] = '\0';
1601         StrLwr(entry->file);
1602
1603         config_add_entry(config, entry);
1604 }
1605
1606 static UINTN file_read(EFI_FILE_HANDLE dir, CHAR16 *name, CHAR8 **content) {
1607         EFI_FILE_HANDLE handle;
1608         EFI_FILE_INFO *info;
1609         CHAR8 *buf;
1610         UINTN buflen;
1611         EFI_STATUS err;
1612         UINTN len = 0;
1613
1614         err = uefi_call_wrapper(dir->Open, 5, dir, &handle, name, EFI_FILE_MODE_READ, 0ULL);
1615         if (EFI_ERROR(err))
1616                 goto out;
1617
1618         info = LibFileInfo(handle);
1619         buflen = info->FileSize+1;
1620         buf = AllocatePool(buflen);
1621
1622         err = uefi_call_wrapper(handle->Read, 3, handle, &buflen, buf);
1623         if (!EFI_ERROR(err)) {
1624                 buf[buflen] = '\0';
1625                 *content = buf;
1626                 len = buflen;
1627         } else
1628                 FreePool(buf);
1629
1630         FreePool(info);
1631         uefi_call_wrapper(handle->Close, 1, handle);
1632 out:
1633         return len;
1634 }
1635
1636 static VOID config_load(Config *config, EFI_HANDLE *device, EFI_FILE *root_dir, CHAR16 *loaded_image_path) {
1637         EFI_FILE_HANDLE entries_dir;
1638         EFI_STATUS err;
1639         CHAR8 *content = NULL;
1640         UINTN sec;
1641         UINTN len;
1642         UINTN i;
1643
1644         len = file_read(root_dir, L"\\loader\\loader.conf", &content);
1645         if (len > 0)
1646                 config_defaults_load_from_file(config, content);
1647         FreePool(content);
1648
1649         err = efivar_get_int(L"LoaderConfigTimeout", &sec);
1650         if (!EFI_ERROR(err)) {
1651                 config->timeout_sec_efivar = sec;
1652                 config->timeout_sec = sec;
1653         } else
1654                 config->timeout_sec_efivar = -1;
1655
1656         err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &entries_dir, L"\\loader\\entries", EFI_FILE_MODE_READ, 0ULL);
1657         if (!EFI_ERROR(err)) {
1658                 for (;;) {
1659                         CHAR16 buf[256];
1660                         UINTN bufsize;
1661                         EFI_FILE_INFO *f;
1662                         CHAR8 *content = NULL;
1663                         UINTN len;
1664
1665                         bufsize = sizeof(buf);
1666                         err = uefi_call_wrapper(entries_dir->Read, 3, entries_dir, &bufsize, buf);
1667                         if (bufsize == 0 || EFI_ERROR(err))
1668                                 break;
1669
1670                         f = (EFI_FILE_INFO *) buf;
1671                         if (f->FileName[0] == '.')
1672                                 continue;
1673                         if (f->Attribute & EFI_FILE_DIRECTORY)
1674                                 continue;
1675                         len = StrLen(f->FileName);
1676                         if (len < 6)
1677                                 continue;
1678                         if (StriCmp(f->FileName + len - 5, L".conf") != 0)
1679                                 continue;
1680
1681                         len = file_read(entries_dir, f->FileName, &content);
1682                         if (len > 0)
1683                                 config_entry_add_from_file(config, device, f->FileName, content, loaded_image_path);
1684                         FreePool(content);
1685                 }
1686                 uefi_call_wrapper(entries_dir->Close, 1, entries_dir);
1687         }
1688
1689         /* sort entries after version number */
1690         for (i = 1; i < config->entry_count; i++) {
1691                 BOOLEAN more;
1692                 UINTN k;
1693
1694                 more = FALSE;
1695                 for (k = 0; k < config->entry_count - i; k++) {
1696                         ConfigEntry *entry;
1697
1698                         if (str_verscmp(config->entries[k]->file, config->entries[k+1]->file) <= 0)
1699                                 continue;
1700                         entry = config->entries[k];
1701                         config->entries[k] = config->entries[k+1];
1702                         config->entries[k+1] = entry;
1703                         more = TRUE;
1704                 }
1705                 if (!more)
1706                         break;
1707         }
1708 }
1709
1710 static VOID config_default_entry_select(Config *config) {
1711         CHAR16 *var;
1712         EFI_STATUS err;
1713         UINTN i;
1714
1715         /*
1716          * The EFI variable to specify a boot entry for the next, and only the
1717          * next reboot. The variable is always cleared directly after it is read.
1718          */
1719         err = efivar_get(L"LoaderEntryOneShot", &var);
1720         if (!EFI_ERROR(err)) {
1721                 BOOLEAN found = FALSE;
1722
1723                 for (i = 0; i < config->entry_count; i++) {
1724                         if (StrCmp(config->entries[i]->file, var) == 0) {
1725                                 config->idx_default = i;
1726                                 found = TRUE;
1727                                 break;
1728                         }
1729                 }
1730
1731                 config->entry_oneshot = StrDuplicate(var);
1732                 efivar_set(L"LoaderEntryOneShot", NULL, TRUE);
1733                 FreePool(var);
1734                 if (found)
1735                         return;
1736         }
1737
1738         /*
1739          * The EFI variable to select the default boot entry overrides the
1740          * configured pattern. The variable can be set and cleared by pressing
1741          * the 'd' key in the loader selection menu, the entry is marked with
1742          * an '*'.
1743          */
1744         err = efivar_get(L"LoaderEntryDefault", &var);
1745         if (!EFI_ERROR(err)) {
1746                 BOOLEAN found = FALSE;
1747
1748                 for (i = 0; i < config->entry_count; i++) {
1749                         if (StrCmp(config->entries[i]->file, var) == 0) {
1750                                 config->idx_default = i;
1751                                 config->idx_default_efivar = i;
1752                                 found = TRUE;
1753                                 break;
1754                         }
1755                 }
1756                 FreePool(var);
1757                 if (found)
1758                         return;
1759         }
1760         config->idx_default_efivar = -1;
1761
1762         if (config->entry_count == 0)
1763                 return;
1764
1765         /*
1766          * Match the pattern from the end of the list to the start, find last
1767          * entry (largest number) matching the given pattern.
1768          */
1769         if (config->entry_default_pattern) {
1770                 i = config->entry_count;
1771                 while (i--) {
1772                         if (config->entries[i]->no_autoselect)
1773                                 continue;
1774                         if (MetaiMatch(config->entries[i]->file, config->entry_default_pattern)) {
1775                                 config->idx_default = i;
1776                                 return;
1777                         }
1778                 }
1779         }
1780
1781         /* select the last suitable entry */
1782         i = config->entry_count;
1783         while (i--) {
1784                 if (config->entries[i]->no_autoselect)
1785                         continue;
1786                 config->idx_default = i;
1787                 return;
1788         }
1789
1790         /* no entry found */
1791         config->idx_default = -1;
1792 }
1793
1794 /* generate a unique title, avoiding non-distinguishable menu entries */
1795 static VOID config_title_generate(Config *config) {
1796         UINTN i, k;
1797         BOOLEAN unique;
1798
1799         /* set title */
1800         for (i = 0; i < config->entry_count; i++) {
1801                 CHAR16 *title;
1802
1803                 FreePool(config->entries[i]->title_show);
1804                 title = config->entries[i]->title;
1805                 if (!title)
1806                         title = config->entries[i]->file;
1807                 config->entries[i]->title_show = StrDuplicate(title);
1808         }
1809
1810         unique = TRUE;
1811         for (i = 0; i < config->entry_count; i++) {
1812                 for (k = 0; k < config->entry_count; k++) {
1813                         if (i == k)
1814                                 continue;
1815                         if (StrCmp(config->entries[i]->title_show, config->entries[k]->title_show) != 0)
1816                                 continue;
1817
1818                         unique = FALSE;
1819                         config->entries[i]->non_unique = TRUE;
1820                         config->entries[k]->non_unique = TRUE;
1821                 }
1822         }
1823         if (unique)
1824                 return;
1825
1826         /* add version to non-unique titles */
1827         for (i = 0; i < config->entry_count; i++) {
1828                 CHAR16 *s;
1829
1830                 if (!config->entries[i]->non_unique)
1831                         continue;
1832                 if (!config->entries[i]->version)
1833                         continue;
1834
1835                 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, config->entries[i]->version);
1836                 FreePool(config->entries[i]->title_show);
1837                 config->entries[i]->title_show = s;
1838                 config->entries[i]->non_unique = FALSE;
1839         }
1840
1841         unique = TRUE;
1842         for (i = 0; i < config->entry_count; i++) {
1843                 for (k = 0; k < config->entry_count; k++) {
1844                         if (i == k)
1845                                 continue;
1846                         if (StrCmp(config->entries[i]->title_show, config->entries[k]->title_show) != 0)
1847                                 continue;
1848
1849                         unique = FALSE;
1850                         config->entries[i]->non_unique = TRUE;
1851                         config->entries[k]->non_unique = TRUE;
1852                 }
1853         }
1854         if (unique)
1855                 return;
1856
1857         /* add machine-id to non-unique titles */
1858         for (i = 0; i < config->entry_count; i++) {
1859                 CHAR16 *s;
1860                 CHAR16 *m;
1861
1862                 if (!config->entries[i]->non_unique)
1863                         continue;
1864                 if (!config->entries[i]->machine_id)
1865                         continue;
1866
1867                 m = StrDuplicate(config->entries[i]->machine_id);
1868                 m[8] = '\0';
1869                 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, m);
1870                 FreePool(config->entries[i]->title_show);
1871                 config->entries[i]->title_show = s;
1872                 config->entries[i]->non_unique = FALSE;
1873                 FreePool(m);
1874         }
1875
1876         unique = TRUE;
1877         for (i = 0; i < config->entry_count; i++) {
1878                 for (k = 0; k < config->entry_count; k++) {
1879                         if (i == k)
1880                                 continue;
1881                         if (StrCmp(config->entries[i]->title_show, config->entries[k]->title_show) != 0)
1882                                 continue;
1883
1884                         unique = FALSE;
1885                         config->entries[i]->non_unique = TRUE;
1886                         config->entries[k]->non_unique = TRUE;
1887                 }
1888         }
1889         if (unique)
1890                 return;
1891
1892         /* add file name to non-unique titles */
1893         for (i = 0; i < config->entry_count; i++) {
1894                 CHAR16 *s;
1895
1896                 if (!config->entries[i]->non_unique)
1897                         continue;
1898                 s = PoolPrint(L"%s (%s)", config->entries[i]->title_show, config->entries[i]->file);
1899                 FreePool(config->entries[i]->title_show);
1900                 config->entries[i]->title_show = s;
1901                 config->entries[i]->non_unique = FALSE;
1902         }
1903 }
1904
1905 static BOOLEAN config_entry_add_call(Config *config, CHAR16 *title, EFI_STATUS (*call)(void)) {
1906         ConfigEntry *entry;
1907
1908         entry = AllocateZeroPool(sizeof(ConfigEntry));
1909         entry->title = StrDuplicate(title);
1910         entry->call = call;
1911         entry->no_autoselect = TRUE;
1912         config_add_entry(config, entry);
1913         return TRUE;
1914 }
1915
1916 static BOOLEAN config_entry_add_loader(Config *config, EFI_HANDLE *device, EFI_FILE *root_dir, CHAR16 *loaded_image_path,
1917                                        CHAR16 *file, CHAR16 key, CHAR16 *title, CHAR16 *loader) {
1918         EFI_FILE_HANDLE handle;
1919         EFI_STATUS err;
1920         ConfigEntry *entry;
1921
1922         /* do not add an entry for ourselves */
1923         if (loaded_image_path && StriCmp(loader, loaded_image_path) == 0)
1924                 return FALSE;
1925
1926         /* check existence */
1927         err = uefi_call_wrapper(root_dir->Open, 5, root_dir, &handle, loader, EFI_FILE_MODE_READ, 0ULL);
1928         if (EFI_ERROR(err))
1929                 return FALSE;
1930         uefi_call_wrapper(handle->Close, 1, handle);
1931
1932         entry = AllocateZeroPool(sizeof(ConfigEntry));
1933         entry->title = StrDuplicate(title);
1934         entry->device = device;
1935         entry->loader = StrDuplicate(loader);
1936         entry->file = StrDuplicate(file);
1937         StrLwr(entry->file);
1938         entry->no_autoselect = TRUE;
1939         entry->key = key;
1940         config_add_entry(config, entry);
1941         return TRUE;
1942 }
1943
1944 static VOID config_entry_add_loader_auto(Config *config, EFI_HANDLE *device, EFI_FILE *root_dir, CHAR16 *loaded_image_path,
1945                                          CHAR16 *file, CHAR16 key, CHAR16 *title, CHAR16 *loader) {
1946         if (!config_entry_add_loader(config, device, root_dir, loaded_image_path, file, key, title, loader))
1947                 return;
1948
1949         /* export identifiers of automatically added entries */
1950         if (config->entries_auto) {
1951                 CHAR16 *s;
1952
1953                 s = PoolPrint(L"%s %s", config->entries_auto, file);
1954                 FreePool(config->entries_auto);
1955                 config->entries_auto = s;
1956         } else
1957                 config->entries_auto = StrDuplicate(file);
1958 }
1959
1960 static VOID config_entry_add_osx(Config *config) {
1961         EFI_STATUS err;
1962         UINTN handle_count = 0;
1963         EFI_HANDLE *handles = NULL;
1964
1965         err = LibLocateHandle(ByProtocol, &FileSystemProtocol, NULL, &handle_count, &handles);
1966         if (!EFI_ERROR(err)) {
1967                 UINTN i;
1968
1969                 for (i = 0; i < handle_count; i++) {
1970                         EFI_FILE *root;
1971
1972                         root = LibOpenRoot(handles[i]);
1973                         if (!root)
1974                                 continue;
1975                         config_entry_add_loader_auto(config, handles[i], root, NULL, L"auto-osx", 'a', L"OS X",
1976                                                      L"\\System\\Library\\CoreServices\\boot.efi");
1977                         uefi_call_wrapper(root->Close, 1, root);
1978                 }
1979
1980                 FreePool(handles);
1981         }
1982 }
1983
1984 static EFI_STATUS image_start(EFI_HANDLE parent_image, const Config *config, const ConfigEntry *entry) {
1985         EFI_STATUS err;
1986         EFI_HANDLE image;
1987         EFI_DEVICE_PATH *path;
1988         CHAR16 *options;
1989
1990         path = FileDevicePath(entry->device, entry->loader);
1991         if (!path) {
1992                 Print(L"Error getting device path.");
1993                 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
1994                 return EFI_INVALID_PARAMETER;
1995         }
1996
1997         err = uefi_call_wrapper(BS->LoadImage, 6, FALSE, parent_image, path, NULL, 0, &image);
1998         if (EFI_ERROR(err)) {
1999                 Print(L"Error loading %s: %r", entry->loader, err);
2000                 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2001                 goto out;
2002         }
2003
2004         if (config->options_edit)
2005                 options = config->options_edit;
2006         else if (entry->options)
2007                 options = entry->options;
2008         else
2009                 options = NULL;
2010         if (options) {
2011                 EFI_LOADED_IMAGE *loaded_image;
2012
2013                 err = uefi_call_wrapper(BS->OpenProtocol, 6, image, &LoadedImageProtocol, (void **)&loaded_image,
2014                                         parent_image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
2015                 if (EFI_ERROR(err)) {
2016                         Print(L"Error getting LoadedImageProtocol handle: %r", err);
2017                         uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2018                         goto out_unload;
2019                 }
2020                 loaded_image->LoadOptions = options;
2021                 loaded_image->LoadOptionsSize = (StrLen(loaded_image->LoadOptions)+1) * sizeof(CHAR16);
2022         }
2023
2024         efivar_set_time_usec(L"LoaderTimeExecUSec", 0);
2025         err = uefi_call_wrapper(BS->StartImage, 3, image, NULL, NULL);
2026 out_unload:
2027         uefi_call_wrapper(BS->UnloadImage, 1, image);
2028 out:
2029         FreePool(path);
2030         return err;
2031 }
2032
2033 static EFI_STATUS reboot_into_firmware(VOID) {
2034         CHAR8 *b;
2035         UINTN size;
2036         UINT64 osind;
2037         EFI_STATUS err;
2038
2039         osind = EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
2040
2041         err = efivar_get_raw(&global_guid, L"OsIndications", &b, &size);
2042         if (!EFI_ERROR(err))
2043                 osind |= (UINT64)*b;
2044         FreePool(b);
2045
2046         err = efivar_set_raw(&global_guid, L"OsIndications", (CHAR8 *)&osind, sizeof(UINT64), TRUE);
2047         if (EFI_ERROR(err))
2048                 return err;
2049
2050         err = uefi_call_wrapper(RT->ResetSystem, 4, EfiResetCold, EFI_SUCCESS, 0, NULL);
2051         Print(L"Error calling ResetSystem: %r", err);
2052         uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2053         return err;
2054 }
2055
2056 static VOID config_free(Config *config) {
2057         UINTN i;
2058
2059         for (i = 0; i < config->entry_count; i++)
2060                 config_entry_free(config->entries[i]);
2061         FreePool(config->entries);
2062         FreePool(config->entry_default_pattern);
2063         FreePool(config->options_edit);
2064         FreePool(config->entry_oneshot);
2065         FreePool(config->entries_auto);
2066 }
2067
2068 EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *sys_table) {
2069         CHAR16 *s;
2070         CHAR8 *b;
2071         UINTN size;
2072         EFI_LOADED_IMAGE *loaded_image;
2073         EFI_FILE *root_dir;
2074         CHAR16 *loaded_image_path;
2075         EFI_DEVICE_PATH *device_path;
2076         EFI_STATUS err;
2077         Config config;
2078         UINT64 init_usec;
2079         BOOLEAN menu = FALSE;
2080
2081         InitializeLib(image, sys_table);
2082         init_usec = time_usec();
2083         efivar_set_time_usec(L"LoaderTimeInitUSec", init_usec);
2084         efivar_set(L"LoaderInfo", L"gummiboot " VERSION, FALSE);
2085         s = PoolPrint(L"%s %d.%02d", ST->FirmwareVendor, ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
2086         efivar_set(L"LoaderFirmwareInfo", s, FALSE);
2087         FreePool(s);
2088         s = PoolPrint(L"UEFI %d.%02d", ST->Hdr.Revision >> 16, ST->Hdr.Revision & 0xffff);
2089         efivar_set(L"LoaderFirmwareType", s, FALSE);
2090         FreePool(s);
2091
2092         err = uefi_call_wrapper(BS->OpenProtocol, 6, image, &LoadedImageProtocol, (void **)&loaded_image,
2093                                 image, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
2094         if (EFI_ERROR(err)) {
2095                 Print(L"Error getting a LoadedImageProtocol handle: %r ", err);
2096                 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2097                 return err;
2098         }
2099
2100         /* export the device path this image is started from */
2101         device_path = DevicePathFromHandle(loaded_image->DeviceHandle);
2102         if (device_path) {
2103                 CHAR16 *str;
2104                 EFI_DEVICE_PATH *path, *paths;
2105
2106                 str = DevicePathToStr(device_path);
2107                 efivar_set(L"LoaderDeviceIdentifier", str, FALSE);
2108                 FreePool(str);
2109
2110                 paths = UnpackDevicePath(device_path);
2111                 for (path = paths; !IsDevicePathEnd(path); path = NextDevicePathNode(path)) {
2112                         HARDDRIVE_DEVICE_PATH *drive;
2113                         CHAR16 uuid[37];
2114
2115                         if (DevicePathType(path) != MEDIA_DEVICE_PATH)
2116                                 continue;
2117                         if (DevicePathSubType(path) != MEDIA_HARDDRIVE_DP)
2118                                 continue;
2119                         drive = (HARDDRIVE_DEVICE_PATH *)path;
2120                         if (drive->SignatureType != SIGNATURE_TYPE_GUID)
2121                                 continue;
2122
2123                         GuidToString(uuid, (EFI_GUID *)&drive->Signature);
2124                         efivar_set(L"LoaderDevicePartUUID", uuid, FALSE);
2125                         break;
2126                 }
2127                 FreePool(paths);
2128         }
2129
2130         root_dir = LibOpenRoot(loaded_image->DeviceHandle);
2131         if (!root_dir) {
2132                 Print(L"Unable to open root directory: %r ", err);
2133                 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2134                 return EFI_LOAD_ERROR;
2135         }
2136
2137         /* the filesystem path to this image, to prevent adding ourselves to the menu */
2138         loaded_image_path = DevicePathToStr(loaded_image->FilePath);
2139         efivar_set(L"LoaderImageIdentifier", loaded_image_path, FALSE);
2140
2141         /* scan "\loader\entries\*.conf" files */
2142         ZeroMem(&config, sizeof(Config));
2143         config_load(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
2144
2145         /* if we find some well-known loaders, add them to the end of the list */
2146         config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
2147                                      L"auto-windows", 'w', L"Windows Boot Manager", L"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
2148         config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
2149                                      L"auto-efi-shell", 's', L"EFI Shell", L"\\shell" MACHINE_TYPE_NAME ".efi");
2150         config_entry_add_loader_auto(&config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
2151                                      L"auto-efi-default", '\0', L"EFI Default Loader", L"\\EFI\\Boot\\boot" MACHINE_TYPE_NAME ".efi");
2152         config_entry_add_osx(&config);
2153         efivar_set(L"LoaderEntriesAuto", config.entries_auto, FALSE);
2154
2155         if (efivar_get_raw(&global_guid, L"OsIndicationsSupported", &b, &size) == EFI_SUCCESS) {
2156                 UINT64 osind = (UINT64)*b;
2157
2158                 if (osind & EFI_OS_INDICATIONS_BOOT_TO_FW_UI)
2159                         config_entry_add_call(&config, L"Reboot Into Firmware Interface", reboot_into_firmware);
2160                 FreePool(b);
2161         }
2162
2163         if (config.entry_count == 0) {
2164                 Print(L"No loader found. Configuration files in \\loader\\entries\\*.conf are needed.");
2165                 uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2166                 goto out;
2167         }
2168
2169         config_title_generate(&config);
2170
2171         /* select entry by configured pattern or EFI LoaderDefaultEntry= variable*/
2172         config_default_entry_select(&config);
2173
2174         /* if no configured entry to select from was found, enable the menu */
2175         if (config.idx_default == -1) {
2176                 config.idx_default = 0;
2177                 if (config.timeout_sec == 0)
2178                         config.timeout_sec = 10;
2179         }
2180
2181         /* select entry or show menu when key is pressed or timeout is set */
2182         if (config.timeout_sec == 0) {
2183                 UINT64 key;
2184
2185                 err = key_read(&key, FALSE);
2186                 if (!EFI_ERROR(err)) {
2187                         INT16 idx;
2188
2189                         /* find matching key in config entries */
2190                         idx = entry_lookup_key(&config, config.idx_default, KEYCHAR(key));
2191                         if (idx >= 0)
2192                                 config.idx_default = idx;
2193                         else
2194                                 menu = TRUE;
2195                 }
2196         } else
2197                 menu = TRUE;
2198
2199         for (;;) {
2200                 ConfigEntry *entry;
2201
2202                 entry = config.entries[config.idx_default];
2203                 if (menu) {
2204                         efivar_set_time_usec(L"LoaderTimeMenuUSec", 0);
2205                         uefi_call_wrapper(BS->SetWatchdogTimer, 4, 0, 0x10000, 0, NULL);
2206                         if (!menu_run(&config, &entry, loaded_image_path))
2207                                 break;
2208
2209                         /* run special entry like "reboot" */
2210                         if (entry->call) {
2211                                 entry->call();
2212                                 continue;
2213                         }
2214                 }
2215
2216                 /* export the selected boot entry to the system */
2217                 efivar_set(L"LoaderEntrySelected", entry->file, FALSE);
2218
2219                 uefi_call_wrapper(BS->SetWatchdogTimer, 4, 5 * 60, 0x10000, 0, NULL);
2220                 err = image_start(image, &config, entry);
2221
2222                 if (err == EFI_ACCESS_DENIED || err == EFI_SECURITY_VIOLATION) {
2223                         /* Platform is secure boot and requested image isn't
2224                          * trusted. Need to go back to prior boot system and
2225                          * install more keys or hashes. Signal failure by
2226                          * returning the error */
2227                         Print(L"\nImage %s gives a security error\n", entry->title);
2228                         Print(L"Please enrol the hash or signature of %s\n", entry->loader);
2229                         uefi_call_wrapper(BS->Stall, 1, 3 * 1000 * 1000);
2230                         goto out;
2231                 }
2232
2233                 menu = TRUE;
2234                 config.timeout_sec = 0;
2235         }
2236         err = EFI_SUCCESS;
2237 out:
2238         FreePool(loaded_image_path);
2239         config_free(&config);
2240         uefi_call_wrapper(root_dir->Close, 1, root_dir);
2241         uefi_call_wrapper(BS->CloseProtocol, 4, image, &LoadedImageProtocol, image, NULL);
2242         return err;
2243 }