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