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