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