]> code.delx.au - refind/blob - refind/main.c
Further refinement to spoof_osx_version feature, including HTML
[refind] / refind / main.c
1 /*
2 * refind/main.c
3 * Main code for the boot menu
4 *
5 * Copyright (c) 2006-2010 Christoph Pfisterer
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * * Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the
18 * distribution.
19 *
20 * * Neither the name of Christoph Pfisterer nor the names of the
21 * contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 */
36 /*
37 * Modifications copyright (c) 2012-2015 Roderick W. Smith
38 *
39 * Modifications distributed under the terms of the GNU General Public
40 * License (GPL) version 3 (GPLv3), or (at your option) any later version.
41 *
42 */
43 /*
44 * This program is free software: you can redistribute it and/or modify
45 * it under the terms of the GNU General Public License as published by
46 * the Free Software Foundation, either version 3 of the License, or
47 * (at your option) any later version.
48 *
49 * This program is distributed in the hope that it will be useful,
50 * but WITHOUT ANY WARRANTY; without even the implied warranty of
51 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
52 * GNU General Public License for more details.
53 *
54 * You should have received a copy of the GNU General Public License
55 * along with this program. If not, see <http://www.gnu.org/licenses/>.
56 */
57
58 #include "global.h"
59 #include "config.h"
60 #include "screen.h"
61 #include "legacy.h"
62 #include "lib.h"
63 #include "icns.h"
64 #include "menu.h"
65 #include "mok.h"
66 #include "gpt.h"
67 #include "security_policy.h"
68 #include "driver_support.h"
69 #include "../include/Handle.h"
70 #include "../include/refit_call_wrapper.h"
71 #include "../EfiLib/BdsHelper.h"
72 #include "../EfiLib/legacy.h"
73
74 #ifdef __MAKEWITH_GNUEFI
75 #ifndef EFI_SECURITY_VIOLATION
76 #define EFI_SECURITY_VIOLATION EFIERR (26)
77 #endif
78 #endif
79
80 #ifndef EFI_OS_INDICATIONS_BOOT_TO_FW_UI
81 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001ULL
82 #endif
83
84 #ifdef __MAKEWITH_TIANO
85 #define LibLocateHandle gBS->LocateHandleBuffer
86 #endif
87
88 //
89 // constants
90
91 #define MACOSX_LOADER_DIR L"System\\Library\\CoreServices"
92 #define MACOSX_LOADER_PATH ( MACOSX_LOADER_DIR L"\\boot.efi" )
93 #if defined (EFIX64)
94 #define SHELL_NAMES L"\\EFI\\tools\\shell.efi,\\EFI\\tools\\shellx64.efi,\\shell.efi,\\shellx64.efi"
95 #define GPTSYNC_NAMES L"\\EFI\\tools\\gptsync.efi,\\EFI\\tools\\gptsync_x64.efi"
96 #define GDISK_NAMES L"\\EFI\\tools\\gdisk.efi,\\EFI\\tools\\gdisk_x64.efi"
97 #define NETBOOT_NAMES L"\\EFI\\tools\\ipxe.efi"
98 #define MEMTEST_NAMES L"memtest86.efi,memtest86_x64.efi,memtest86x64.efi,bootx64.efi"
99 #define DRIVER_DIRS L"drivers,drivers_x64"
100 #define FALLBACK_FULLNAME L"EFI\\BOOT\\bootx64.efi"
101 #define FALLBACK_BASENAME L"bootx64.efi"
102 #define EFI_STUB_ARCH 0x8664
103 EFI_GUID gFreedesktopRootGuid = { 0x4f68bce3, 0xe8cd, 0x4db1, { 0x96, 0xe7, 0xfb, 0xca, 0xf9, 0x84, 0xb7, 0x09 }};
104 #elif defined (EFI32)
105 #define SHELL_NAMES L"\\EFI\\tools\\shell.efi,\\EFI\\tools\\shellia32.efi,\\shell.efi,\\shellia32.efi"
106 #define GPTSYNC_NAMES L"\\EFI\\tools\\gptsync.efi,\\EFI\\tools\\gptsync_ia32.efi"
107 #define GDISK_NAMES L"\\EFI\\tools\\gdisk.efi,\\EFI\\tools\\gdisk_ia32.efi"
108 #define NETBOOT_NAMES L"\\EFI\\tools\\ipxe.efi"
109 #define MEMTEST_NAMES L"memtest86.efi,memtest86_ia32.efi,memtest86ia32.efi,bootia32.efi"
110 #define DRIVER_DIRS L"drivers,drivers_ia32"
111 #define FALLBACK_FULLNAME L"EFI\\BOOT\\bootia32.efi"
112 #define FALLBACK_BASENAME L"bootia32.efi"
113 #define EFI_STUB_ARCH 0x014c
114 EFI_GUID gFreedesktopRootGuid = { 0x44479540, 0xf297, 0x41b2, { 0x9a, 0xf7, 0xd1, 0x31, 0xd5, 0xf0, 0x45, 0x8a }};
115 #else
116 #define SHELL_NAMES L"\\EFI\\tools\\shell.efi,\\shell.efi"
117 #define GPTSYNC_NAMES L"\\EFI\\tools\\gptsync.efi"
118 #define GDISK_NAMES L"\\EFI\\tools\\gdisk.efi"
119 #define NETBOOT_NAMES L"\\EFI\\tools\\ipxe.efi"
120 #define MEMTEST_NAMES L"memtest86.efi"
121 #define DRIVER_DIRS L"drivers"
122 #define FALLBACK_FULLNAME L"EFI\\BOOT\\boot.efi" /* Not really correct */
123 #define FALLBACK_BASENAME L"boot.efi" /* Not really correct */
124 // Below is GUID for ARM64
125 EFI_GUID gFreedesktopRootGuid = { 0xb921b045, 0x1df0, 0x41c3, { 0xaf, 0x44, 0x4c, 0x6f, 0x28, 0x0d, 0x3f, 0xae }};
126 #endif
127 #define FAT_ARCH 0x0ef1fab9 /* ID for Apple "fat" binary */
128
129 #define IPXE_DISCOVER_NAME L"\\efi\\tools\\ipxe_discover.efi"
130 #define IPXE_NAME L"\\efi\\tools\\ipxe.efi"
131
132 // Filename patterns that identify EFI boot loaders. Note that a single case (either L"*.efi" or
133 // L"*.EFI") is fine for most systems; but Gigabyte's buggy Hybrid EFI does a case-sensitive
134 // comparison when it should do a case-insensitive comparison, so I'm doubling this up. It does
135 // no harm on other computers, AFAIK. In theory, every case variation should be done for
136 // completeness, but that's ridiculous....
137 #define LOADER_MATCH_PATTERNS L"*.efi,*.EFI"
138
139 // Patterns that identify Linux kernels. Added to the loader match pattern when the
140 // scan_all_linux_kernels option is set in the configuration file. Causes kernels WITHOUT
141 // a ".efi" extension to be found when scanning for boot loaders.
142 #define LINUX_MATCH_PATTERNS L"vmlinuz*,bzImage*"
143
144 // Maximum length of a text string in certain menus
145 #define MAX_LINE_LENGTH 65
146
147 static REFIT_MENU_ENTRY MenuEntryAbout = { L"About rEFInd", TAG_ABOUT, 1, 0, 'A', NULL, NULL, NULL };
148 static REFIT_MENU_ENTRY MenuEntryReset = { L"Reboot Computer", TAG_REBOOT, 1, 0, 'R', NULL, NULL, NULL };
149 static REFIT_MENU_ENTRY MenuEntryShutdown = { L"Shut Down Computer", TAG_SHUTDOWN, 1, 0, 'U', NULL, NULL, NULL };
150 REFIT_MENU_ENTRY MenuEntryReturn = { L"Return to Main Menu", TAG_RETURN, 1, 0, 0, NULL, NULL, NULL };
151 static REFIT_MENU_ENTRY MenuEntryExit = { L"Exit rEFInd", TAG_EXIT, 1, 0, 0, NULL, NULL, NULL };
152 static REFIT_MENU_ENTRY MenuEntryFirmware = { L"Reboot to Computer Setup Utility", TAG_FIRMWARE, 1, 0, 0, NULL, NULL, NULL };
153
154 REFIT_MENU_SCREEN MainMenu = { L"Main Menu", NULL, 0, NULL, 0, NULL, 0, L"Automatic boot",
155 L"Use arrow keys to move cursor; Enter to boot;",
156 L"Insert or F2 for more options; Esc to refresh" };
157 static REFIT_MENU_SCREEN AboutMenu = { L"About", NULL, 0, NULL, 0, NULL, 0, NULL, L"Press Enter to return to main menu", L"" };
158
159 REFIT_CONFIG GlobalConfig = { FALSE, TRUE, FALSE, FALSE, TRUE, 0, 0, 0, DONT_CHANGE_TEXT_MODE,
160 20, 0, 0, GRAPHICS_FOR_OSX, LEGACY_TYPE_MAC,
161 0, 0, { DEFAULT_BIG_ICON_SIZE / 4, DEFAULT_SMALL_ICON_SIZE, DEFAULT_BIG_ICON_SIZE },
162 BANNER_NOSCALE, NULL, NULL, NULL, NULL, CONFIG_FILE_NAME, NULL, NULL, NULL, NULL,
163 NULL, NULL, NULL, NULL, NULL, NULL, NULL,
164 { TAG_SHELL, TAG_MEMTEST, TAG_GDISK, TAG_APPLE_RECOVERY, TAG_WINDOWS_RECOVERY,
165 TAG_MOK_TOOL, TAG_ABOUT, TAG_SHUTDOWN, TAG_REBOOT, TAG_FIRMWARE,
166 0, 0, 0, 0, 0, 0, 0, 0 }
167 };
168
169 EFI_GUID GlobalGuid = EFI_GLOBAL_VARIABLE;
170 EFI_GUID RefindGuid = REFIND_GUID_VALUE;
171
172 GPT_DATA *gPartitions = NULL;
173
174 // Structure used to hold boot loader filenames and time stamps in
175 // a linked list; used to sort entries within a directory.
176 struct LOADER_LIST {
177 CHAR16 *FileName;
178 EFI_TIME TimeStamp;
179 struct LOADER_LIST *NextEntry;
180 };
181
182 //
183 // misc functions
184 //
185
186 static VOID AboutrEFInd(VOID)
187 {
188 CHAR16 *FirmwareVendor;
189
190 if (AboutMenu.EntryCount == 0) {
191 AboutMenu.TitleImage = BuiltinIcon(BUILTIN_ICON_FUNC_ABOUT);
192 AddMenuInfoLine(&AboutMenu, L"rEFInd Version 0.9.2.3");
193 AddMenuInfoLine(&AboutMenu, L"");
194 AddMenuInfoLine(&AboutMenu, L"Copyright (c) 2006-2010 Christoph Pfisterer");
195 AddMenuInfoLine(&AboutMenu, L"Copyright (c) 2012-2015 Roderick W. Smith");
196 AddMenuInfoLine(&AboutMenu, L"Portions Copyright (c) Intel Corporation and others");
197 AddMenuInfoLine(&AboutMenu, L"Distributed under the terms of the GNU GPLv3 license");
198 AddMenuInfoLine(&AboutMenu, L"");
199 AddMenuInfoLine(&AboutMenu, L"Running on:");
200 AddMenuInfoLine(&AboutMenu, PoolPrint(L" EFI Revision %d.%02d", ST->Hdr.Revision >> 16, ST->Hdr.Revision & ((1 << 16) - 1)));
201 #if defined(EFI32)
202 AddMenuInfoLine(&AboutMenu, PoolPrint(L" Platform: x86 (32 bit); Secure Boot %s",
203 secure_mode() ? L"active" : L"inactive"));
204 #elif defined(EFIX64)
205 AddMenuInfoLine(&AboutMenu, PoolPrint(L" Platform: x86_64 (64 bit); Secure Boot %s",
206 secure_mode() ? L"active" : L"inactive"));
207 #else
208 AddMenuInfoLine(&AboutMenu, L" Platform: unknown");
209 #endif
210 FirmwareVendor = StrDuplicate(ST->FirmwareVendor);
211 LimitStringLength(FirmwareVendor, MAX_LINE_LENGTH); // More than ~65 causes empty info page on 800x600 display
212 AddMenuInfoLine(&AboutMenu, PoolPrint(L" Firmware: %s %d.%02d", FirmwareVendor, ST->FirmwareRevision >> 16,
213 ST->FirmwareRevision & ((1 << 16) - 1)));
214 AddMenuInfoLine(&AboutMenu, PoolPrint(L" Screen Output: %s", egScreenDescription()));
215 AddMenuInfoLine(&AboutMenu, L"");
216 #if defined(__MAKEWITH_GNUEFI)
217 AddMenuInfoLine(&AboutMenu, L"Built with GNU-EFI");
218 #else
219 AddMenuInfoLine(&AboutMenu, L"Built with TianoCore EDK2");
220 #endif
221 AddMenuInfoLine(&AboutMenu, L"");
222 AddMenuInfoLine(&AboutMenu, L"For more information, see the rEFInd Web site:");
223 AddMenuInfoLine(&AboutMenu, L"http://www.rodsbooks.com/refind/");
224 AddMenuEntry(&AboutMenu, &MenuEntryReturn);
225 }
226
227 RunMenu(&AboutMenu, NULL);
228 } /* VOID AboutrEFInd() */
229
230 static VOID WarnSecureBootError(CHAR16 *Name, BOOLEAN Verbose) {
231 if (Name == NULL)
232 Name = L"the loader";
233
234 refit_call2_wrapper(ST->ConOut->SetAttribute, ST->ConOut, ATTR_ERROR);
235 Print(L"Secure Boot validation failure loading %s!\n", Name);
236 refit_call2_wrapper(ST->ConOut->SetAttribute, ST->ConOut, ATTR_BASIC);
237 if (Verbose && secure_mode()) {
238 Print(L"\nThis computer is configured with Secure Boot active, but\n%s has failed validation.\n", Name);
239 Print(L"\nYou can:\n * Launch another boot loader\n");
240 Print(L" * Disable Secure Boot in your firmware\n");
241 Print(L" * Sign %s with a machine owner key (MOK)\n", Name);
242 Print(L" * Use a MOK utility (often present on the second row) to add a MOK with which\n");
243 Print(L" %s has already been signed.\n", Name);
244 Print(L" * Use a MOK utility to register %s (\"enroll its hash\") without\n", Name);
245 Print(L" signing it.\n");
246 Print(L"\nSee http://www.rodsbooks.com/refind/secureboot.html for more information\n");
247 PauseForKey();
248 } // if
249 } // VOID WarnSecureBootError()
250
251 // Returns TRUE if this file is a valid EFI loader file, and is proper ARCH
252 static BOOLEAN IsValidLoader(EFI_FILE *RootDir, CHAR16 *FileName) {
253 BOOLEAN IsValid = TRUE;
254 #if defined (EFIX64) | defined (EFI32)
255 EFI_STATUS Status;
256 EFI_FILE_HANDLE FileHandle;
257 CHAR8 Header[512];
258 UINTN Size = sizeof(Header);
259
260 if ((RootDir == NULL) || (FileName == NULL)) {
261 // Assume valid here, because Macs produce NULL RootDir (& maybe FileName)
262 // when launching from a Firewire drive. This should be handled better, but
263 // fix would have to be in StartEFIImageList() and/or in FindVolumeAndFilename().
264 return TRUE;
265 } // if
266
267 Status = refit_call5_wrapper(RootDir->Open, RootDir, &FileHandle, FileName, EFI_FILE_MODE_READ, 0);
268 if (EFI_ERROR(Status))
269 return FALSE;
270
271 Status = refit_call3_wrapper(FileHandle->Read, FileHandle, &Size, Header);
272 refit_call1_wrapper(FileHandle->Close, FileHandle);
273
274 IsValid = !EFI_ERROR(Status) &&
275 Size == sizeof(Header) &&
276 ((Header[0] == 'M' && Header[1] == 'Z' &&
277 (Size = *(UINT32 *)&Header[0x3c]) < 0x180 &&
278 Header[Size] == 'P' && Header[Size+1] == 'E' &&
279 Header[Size+2] == 0 && Header[Size+3] == 0 &&
280 *(UINT16 *)&Header[Size+4] == EFI_STUB_ARCH) ||
281 (*(UINT32 *)&Header == FAT_ARCH));
282 #endif
283 return IsValid;
284 } // BOOLEAN IsValidLoader()
285
286 // Launch an EFI binary.
287 EFI_STATUS StartEFIImageList(IN EFI_DEVICE_PATH **DevicePaths,
288 IN CHAR16 *LoadOptions, IN UINTN LoaderType,
289 IN CHAR16 *ImageTitle, IN CHAR8 OSType,
290 OUT UINTN *ErrorInStep,
291 IN BOOLEAN Verbose,
292 IN BOOLEAN IsDriver)
293 {
294 EFI_STATUS Status, ReturnStatus;
295 EFI_HANDLE ChildImageHandle, ChildImageHandle2;
296 EFI_LOADED_IMAGE *ChildLoadedImage = NULL;
297 REFIT_VOLUME *Volume = NULL;
298 UINTN DevicePathIndex;
299 CHAR16 ErrorInfo[256];
300 CHAR16 *FullLoadOptions = NULL;
301 CHAR16 *Filename = NULL;
302 CHAR16 *Temp;
303
304 if (ErrorInStep != NULL)
305 *ErrorInStep = 0;
306
307 // set load options
308 if (LoadOptions != NULL) {
309 FullLoadOptions = StrDuplicate(LoadOptions);
310 if ((LoaderType == TYPE_EFI) && (OSType == 'M')) {
311 MergeStrings(&FullLoadOptions, L" ", 0);
312 // NOTE: That last space is also added by the EFI shell and seems to be significant
313 // when passing options to Apple's boot.efi...
314 } // if
315 } // if (LoadOptions != NULL)
316 if (Verbose)
317 Print(L"Starting %s\nUsing load options '%s'\n", ImageTitle, FullLoadOptions ? FullLoadOptions : L"");
318
319 // load the image into memory
320 ReturnStatus = Status = EFI_NOT_FOUND; // in case the list is empty
321 for (DevicePathIndex = 0; DevicePaths[DevicePathIndex] != NULL; DevicePathIndex++) {
322 FindVolumeAndFilename(DevicePaths[DevicePathIndex], &Volume, &Filename);
323 // Some EFIs crash if attempting to load driver for invalid architecture, so
324 // protect for this condition; but sometimes Volume comes back NULL, so provide
325 // an exception. (TODO: Handle this special condition better.)
326 if ((LoaderType == TYPE_LEGACY) || (Volume == NULL) || IsValidLoader(Volume->RootDir, Filename)) {
327 if (Filename && (LoaderType != TYPE_LEGACY)) {
328 Temp = PoolPrint(L"\\%s %s", Filename, FullLoadOptions ? FullLoadOptions : L"");
329 if (Temp != NULL) {
330 MyFreePool(FullLoadOptions);
331 FullLoadOptions = Temp;
332 }
333 } // if (Filename)
334
335 // NOTE: Below commented-out line could be more efficient if file were read ahead of
336 // time and passed as a pre-loaded image to LoadImage(), but it doesn't work on my
337 // 32-bit Mac Mini or my 64-bit Intel box when launching a Linux kernel; the
338 // kernel returns a "Failed to handle fs_proto" error message.
339 // TODO: Track down the cause of this error and fix it, if possible.
340 // ReturnStatus = Status = refit_call6_wrapper(BS->LoadImage, FALSE, SelfImageHandle, DevicePaths[DevicePathIndex],
341 // ImageData, ImageSize, &ChildImageHandle);
342 ReturnStatus = Status = refit_call6_wrapper(BS->LoadImage, FALSE, SelfImageHandle, DevicePaths[DevicePathIndex],
343 NULL, 0, &ChildImageHandle);
344 if (secure_mode() && ShimLoaded()) {
345 // Load ourself into memory. This is a trick to work around a bug in Shim 0.8,
346 // which ties itself into the BS->LoadImage() and BS->StartImage() functions and
347 // then unregisters itself from the EFI system table when its replacement
348 // StartImage() function is called *IF* the previous LoadImage() was for the same
349 // program. The result is that rEFInd can validate only the first program it
350 // launches (often a filesystem driver). Loading a second program (rEFInd itself,
351 // here, to keep it smaller than a kernel) works around this problem. See the
352 // replacements.c file in Shim, and especially its start_image() function, for
353 // the source of the problem.
354 // NOTE: This doesn't check the return status or handle errors. It could
355 // conceivably do weird things if, say, rEFInd were on a USB drive that the
356 // user pulls before launching a program.
357 refit_call6_wrapper(BS->LoadImage, FALSE, SelfImageHandle, GlobalConfig.SelfDevicePath,
358 NULL, 0, &ChildImageHandle2);
359 }
360 } else {
361 Print(L"Invalid loader file!\n");
362 ReturnStatus = EFI_LOAD_ERROR;
363 }
364 if (ReturnStatus != EFI_NOT_FOUND) {
365 break;
366 }
367 } // for
368 if ((Status == EFI_ACCESS_DENIED) || (Status == EFI_SECURITY_VIOLATION)) {
369 WarnSecureBootError(ImageTitle, Verbose);
370 goto bailout;
371 }
372 SPrint(ErrorInfo, 255, L"while loading %s", ImageTitle);
373 if (CheckError(Status, ErrorInfo)) {
374 if (ErrorInStep != NULL)
375 *ErrorInStep = 1;
376 goto bailout;
377 }
378
379 ReturnStatus = Status = refit_call3_wrapper(BS->HandleProtocol, ChildImageHandle, &LoadedImageProtocol,
380 (VOID **) &ChildLoadedImage);
381 if (CheckError(Status, L"while getting a LoadedImageProtocol handle")) {
382 if (ErrorInStep != NULL)
383 *ErrorInStep = 2;
384 goto bailout_unload;
385 }
386 ChildLoadedImage->LoadOptions = (VOID *)FullLoadOptions;
387 ChildLoadedImage->LoadOptionsSize = FullLoadOptions ? ((UINT32)StrLen(FullLoadOptions) + 1) * sizeof(CHAR16) : 0;
388 // turn control over to the image
389 // TODO: (optionally) re-enable the EFI watchdog timer!
390
391 // close open file handles
392 UninitRefitLib();
393 ReturnStatus = Status = refit_call3_wrapper(BS->StartImage, ChildImageHandle, NULL, NULL);
394
395 // control returns here when the child image calls Exit()
396 SPrint(ErrorInfo, 255, L"returned from %s", ImageTitle);
397 if (CheckError(Status, ErrorInfo)) {
398 if (ErrorInStep != NULL)
399 *ErrorInStep = 3;
400 }
401
402 // re-open file handles
403 ReinitRefitLib();
404
405 bailout_unload:
406 // unload the image, we don't care if it works or not...
407 if (!IsDriver)
408 Status = refit_call1_wrapper(BS->UnloadImage, ChildImageHandle);
409
410 bailout:
411 MyFreePool(FullLoadOptions);
412 return ReturnStatus;
413 } /* EFI_STATUS StartEFIImageList() */
414
415 static EFI_STATUS StartEFIImage(IN EFI_DEVICE_PATH *DevicePath,
416 IN CHAR16 *LoadOptions, IN UINTN LoaderType,
417 IN CHAR16 *ImageTitle, IN CHAR8 OSType,
418 OUT UINTN *ErrorInStep,
419 IN BOOLEAN Verbose,
420 IN BOOLEAN IsDriver
421 )
422 {
423 EFI_DEVICE_PATH *DevicePaths[2];
424
425 DevicePaths[0] = DevicePath;
426 DevicePaths[1] = NULL;
427 return StartEFIImageList(DevicePaths, LoadOptions, LoaderType, ImageTitle, OSType, ErrorInStep, Verbose, IsDriver);
428 } /* static EFI_STATUS StartEFIImage() */
429
430 // From gummiboot: Reboot the computer into its built-in user interface
431 static EFI_STATUS RebootIntoFirmware(VOID) {
432 CHAR8 *b;
433 UINTN size;
434 UINT64 osind;
435 EFI_STATUS err;
436
437 osind = EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
438
439 err = EfivarGetRaw(&GlobalGuid, L"OsIndications", &b, &size);
440 if (err == EFI_SUCCESS)
441 osind |= (UINT64)*b;
442 MyFreePool(b);
443
444 err = EfivarSetRaw(&GlobalGuid, L"OsIndications", (CHAR8 *)&osind, sizeof(UINT64), TRUE);
445 if (err != EFI_SUCCESS)
446 return err;
447
448 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
449 Print(L"Error calling ResetSystem: %r", err);
450 PauseForKey();
451 return err;
452 }
453
454 // Record the value of the loader's name/description in rEFInd's "PreviousBoot" EFI variable,
455 // if it's different from what's already stored there.
456 VOID StoreLoaderName(IN CHAR16 *Name) {
457 EFI_STATUS Status;
458 CHAR16 *OldName = NULL;
459 UINTN Length;
460
461 if (Name) {
462 Status = EfivarGetRaw(&RefindGuid, L"PreviousBoot", (CHAR8**) &OldName, &Length);
463 if ((Status != EFI_SUCCESS) || (StrCmp(OldName, Name) != 0)) {
464 EfivarSetRaw(&RefindGuid, L"PreviousBoot", (CHAR8*) Name, StrLen(Name) * 2 + 2, TRUE);
465 } // if
466 MyFreePool(OldName);
467 } // if
468 } // VOID StoreLoaderName()
469
470 //
471 // EFI OS loader functions
472 //
473
474 // See http://www.thomas-krenn.com/en/wiki/Activating_the_Intel_VT_Virtualization_Feature
475 // for information on Intel VMX features
476 static VOID DoEnableAndLockVMX(VOID)
477 {
478 UINT32 msr = 0x3a;
479 UINT32 low_bits = 0, high_bits = 0;
480
481 // is VMX active ?
482 __asm__ volatile ("rdmsr" : "=a" (low_bits), "=d" (high_bits) : "c" (msr));
483
484 // enable and lock vmx if not locked
485 if ((low_bits & 1) == 0) {
486 high_bits = 0;
487 low_bits = 0x05;
488 msr = 0x3a;
489 __asm__ volatile ("wrmsr" : : "c" (msr), "a" (low_bits), "d" (high_bits));
490 }
491 } // VOID DoEnableAndLockVMX()
492
493 static VOID StartLoader(LOADER_ENTRY *Entry, CHAR16 *SelectionName)
494 {
495 UINTN ErrorInStep = 0;
496
497 if (GlobalConfig.EnableAndLockVMX) {
498 DoEnableAndLockVMX();
499 }
500
501 BeginExternalScreen(Entry->UseGraphicsMode, L"Booting OS");
502 StoreLoaderName(SelectionName);
503 StartEFIImage(Entry->DevicePath, Entry->LoadOptions, TYPE_EFI,
504 Basename(Entry->LoaderPath), Entry->OSType, &ErrorInStep, !Entry->UseGraphicsMode, FALSE);
505 FinishExternalScreen();
506 }
507
508 // Locate an initrd or initramfs file that matches the kernel specified by LoaderPath.
509 // The matching file has a name that begins with "init" and includes the same version
510 // number string as is found in LoaderPath -- but not a longer version number string.
511 // For instance, if LoaderPath is \EFI\kernels\bzImage-3.3.0.efi, and if \EFI\kernels
512 // has a file called initramfs-3.3.0.img, this function will return the string
513 // '\EFI\kernels\initramfs-3.3.0.img'. If the directory ALSO contains the file
514 // initramfs-3.3.0-rc7.img or initramfs-13.3.0.img, those files will NOT match;
515 // however, initmine-3.3.0.img might match. (FindInitrd() returns the first match it
516 // finds.) Thus, care should be taken to avoid placing duplicate matching files in
517 // the kernel's directory.
518 // If no matching init file can be found, returns NULL.
519 static CHAR16 * FindInitrd(IN CHAR16 *LoaderPath, IN REFIT_VOLUME *Volume) {
520 CHAR16 *InitrdName = NULL, *FileName, *KernelVersion, *InitrdVersion, *Path;
521 REFIT_DIR_ITER DirIter;
522 EFI_FILE_INFO *DirEntry;
523
524 FileName = Basename(LoaderPath);
525 KernelVersion = FindNumbers(FileName);
526 Path = FindPath(LoaderPath);
527
528 // Add trailing backslash for root directory; necessary on some systems, but must
529 // NOT be added to all directories, since on other systems, a trailing backslash on
530 // anything but the root directory causes them to flake out!
531 if (StrLen(Path) == 0) {
532 MergeStrings(&Path, L"\\", 0);
533 } // if
534 DirIterOpen(Volume->RootDir, Path, &DirIter);
535 // Now add a trailing backslash if it was NOT added earlier, for consistency in
536 // building the InitrdName later....
537 if ((StrLen(Path) > 0) && (Path[StrLen(Path) - 1] != L'\\'))
538 MergeStrings(&Path, L"\\", 0);
539 while ((DirIterNext(&DirIter, 2, L"init*", &DirEntry)) && (InitrdName == NULL)) {
540 InitrdVersion = FindNumbers(DirEntry->FileName);
541 if (KernelVersion != NULL) {
542 if (MyStriCmp(InitrdVersion, KernelVersion)) {
543 InitrdName = PoolPrint(L"%s%s", Path, DirEntry->FileName);
544 } // if
545 } else {
546 if (InitrdVersion == NULL) {
547 InitrdName = PoolPrint(L"%s%s", Path, DirEntry->FileName);
548 } // if
549 } // if/else
550 MyFreePool(InitrdVersion);
551 } // while
552 DirIterClose(&DirIter);
553
554 // Note: Don't FreePool(FileName), since Basename returns a pointer WITHIN the string it's passed.
555 MyFreePool(KernelVersion);
556 MyFreePool(Path);
557 return (InitrdName);
558 } // static CHAR16 * FindInitrd()
559
560 LOADER_ENTRY * AddPreparedLoaderEntry(LOADER_ENTRY *Entry) {
561 AddMenuEntry(&MainMenu, (REFIT_MENU_ENTRY *)Entry);
562
563 return(Entry);
564 } // LOADER_ENTRY * AddPreparedLoaderEntry()
565
566 // Creates a copy of a menu screen.
567 // Returns a pointer to the copy of the menu screen.
568 static REFIT_MENU_SCREEN* CopyMenuScreen(REFIT_MENU_SCREEN *Entry) {
569 REFIT_MENU_SCREEN *NewEntry;
570 UINTN i;
571
572 NewEntry = AllocateZeroPool(sizeof(REFIT_MENU_SCREEN));
573 if ((Entry != NULL) && (NewEntry != NULL)) {
574 CopyMem(NewEntry, Entry, sizeof(REFIT_MENU_SCREEN));
575 NewEntry->Title = (Entry->Title) ? StrDuplicate(Entry->Title) : NULL;
576 NewEntry->TimeoutText = (Entry->TimeoutText) ? StrDuplicate(Entry->TimeoutText) : NULL;
577 if (Entry->TitleImage != NULL) {
578 NewEntry->TitleImage = AllocatePool(sizeof(EG_IMAGE));
579 if (NewEntry->TitleImage != NULL)
580 CopyMem(NewEntry->TitleImage, Entry->TitleImage, sizeof(EG_IMAGE));
581 } // if
582 NewEntry->InfoLines = (CHAR16**) AllocateZeroPool(Entry->InfoLineCount * (sizeof(CHAR16*)));
583 for (i = 0; i < Entry->InfoLineCount && NewEntry->InfoLines; i++) {
584 NewEntry->InfoLines[i] = (Entry->InfoLines[i]) ? StrDuplicate(Entry->InfoLines[i]) : NULL;
585 } // for
586 NewEntry->Entries = (REFIT_MENU_ENTRY**) AllocateZeroPool(Entry->EntryCount * (sizeof (REFIT_MENU_ENTRY*)));
587 for (i = 0; i < Entry->EntryCount && NewEntry->Entries; i++) {
588 AddMenuEntry(NewEntry, Entry->Entries[i]);
589 } // for
590 NewEntry->Hint1 = (Entry->Hint1) ? StrDuplicate(Entry->Hint1) : NULL;
591 NewEntry->Hint2 = (Entry->Hint2) ? StrDuplicate(Entry->Hint2) : NULL;
592 } // if
593 return (NewEntry);
594 } // static REFIT_MENU_SCREEN* CopyMenuScreen()
595
596 // Creates a copy of a menu entry. Intended to enable moving a stack-based
597 // menu entry (such as the ones for the "reboot" and "exit" functions) to
598 // to the heap. This enables easier deletion of the whole set of menu
599 // entries when re-scanning.
600 // Returns a pointer to the copy of the menu entry.
601 static REFIT_MENU_ENTRY* CopyMenuEntry(REFIT_MENU_ENTRY *Entry) {
602 REFIT_MENU_ENTRY *NewEntry;
603
604 NewEntry = AllocateZeroPool(sizeof(REFIT_MENU_ENTRY));
605 if ((Entry != NULL) && (NewEntry != NULL)) {
606 CopyMem(NewEntry, Entry, sizeof(REFIT_MENU_ENTRY));
607 NewEntry->Title = (Entry->Title) ? StrDuplicate(Entry->Title) : NULL;
608 if (Entry->BadgeImage != NULL) {
609 NewEntry->BadgeImage = AllocatePool(sizeof(EG_IMAGE));
610 if (NewEntry->BadgeImage != NULL)
611 CopyMem(NewEntry->BadgeImage, Entry->BadgeImage, sizeof(EG_IMAGE));
612 }
613 if (Entry->Image != NULL) {
614 NewEntry->Image = AllocatePool(sizeof(EG_IMAGE));
615 if (NewEntry->Image != NULL)
616 CopyMem(NewEntry->Image, Entry->Image, sizeof(EG_IMAGE));
617 }
618 if (Entry->SubScreen != NULL) {
619 NewEntry->SubScreen = CopyMenuScreen(Entry->SubScreen);
620 }
621 } // if
622 return (NewEntry);
623 } // REFIT_MENU_ENTRY* CopyMenuEntry()
624
625 // Creates a new LOADER_ENTRY data structure and populates it with
626 // default values from the specified Entry, or NULL values if Entry
627 // is unspecified (NULL).
628 // Returns a pointer to the new data structure, or NULL if it
629 // couldn't be allocated
630 LOADER_ENTRY *InitializeLoaderEntry(IN LOADER_ENTRY *Entry) {
631 LOADER_ENTRY *NewEntry = NULL;
632
633 NewEntry = AllocateZeroPool(sizeof(LOADER_ENTRY));
634 if (NewEntry != NULL) {
635 NewEntry->me.Title = NULL;
636 NewEntry->me.Tag = TAG_LOADER;
637 NewEntry->Enabled = TRUE;
638 NewEntry->UseGraphicsMode = FALSE;
639 NewEntry->OSType = 0;
640 if (Entry != NULL) {
641 NewEntry->LoaderPath = (Entry->LoaderPath) ? StrDuplicate(Entry->LoaderPath) : NULL;
642 NewEntry->VolName = (Entry->VolName) ? StrDuplicate(Entry->VolName) : NULL;
643 NewEntry->DevicePath = Entry->DevicePath;
644 NewEntry->UseGraphicsMode = Entry->UseGraphicsMode;
645 NewEntry->LoadOptions = (Entry->LoadOptions) ? StrDuplicate(Entry->LoadOptions) : NULL;
646 NewEntry->InitrdPath = (Entry->InitrdPath) ? StrDuplicate(Entry->InitrdPath) : NULL;
647 }
648 } // if
649 return (NewEntry);
650 } // LOADER_ENTRY *InitializeLoaderEntry()
651
652 // Adds InitrdPath to Options, but only if Options doesn't already include an
653 // initrd= line. Done to enable overriding the default initrd selection in a
654 // refind_linux.conf file's options list.
655 // Returns a pointer to a new string. The calling function is responsible for
656 // freeing its memory.
657 static CHAR16 *AddInitrdToOptions(CHAR16 *Options, CHAR16 *InitrdPath) {
658 CHAR16 *NewOptions = NULL;
659
660 if (Options != NULL)
661 NewOptions = StrDuplicate(Options);
662 if ((InitrdPath != NULL) && !StriSubCmp(L"initrd=", Options)) {
663 MergeStrings(&NewOptions, L"initrd=", L' ');
664 MergeStrings(&NewOptions, InitrdPath, 0);
665 }
666 return NewOptions;
667 } // CHAR16 *AddInitrdToOptions()
668
669 // Prepare a REFIT_MENU_SCREEN data structure for a subscreen entry. This sets up
670 // the default entry that launches the boot loader using the same options as the
671 // main Entry does. Subsequent options can be added by the calling function.
672 // If a subscreen already exists in the Entry that's passed to this function,
673 // it's left unchanged and a pointer to it is returned.
674 // Returns a pointer to the new subscreen data structure, or NULL if there
675 // were problems allocating memory.
676 REFIT_MENU_SCREEN *InitializeSubScreen(IN LOADER_ENTRY *Entry) {
677 CHAR16 *FileName, *MainOptions = NULL;
678 REFIT_MENU_SCREEN *SubScreen = NULL;
679 LOADER_ENTRY *SubEntry;
680
681 FileName = Basename(Entry->LoaderPath);
682 if (Entry->me.SubScreen == NULL) { // No subscreen yet; initialize default entry....
683 SubScreen = AllocateZeroPool(sizeof(REFIT_MENU_SCREEN));
684 if (SubScreen != NULL) {
685 SubScreen->Title = AllocateZeroPool(sizeof(CHAR16) * 256);
686 SPrint(SubScreen->Title, 255, L"Boot Options for %s on %s",
687 (Entry->Title != NULL) ? Entry->Title : FileName, Entry->VolName);
688 SubScreen->TitleImage = Entry->me.Image;
689 // default entry
690 SubEntry = InitializeLoaderEntry(Entry);
691 if (SubEntry != NULL) {
692 SubEntry->me.Title = StrDuplicate(L"Boot using default options");
693 MainOptions = SubEntry->LoadOptions;
694 SubEntry->LoadOptions = AddInitrdToOptions(MainOptions, SubEntry->InitrdPath);
695 MyFreePool(MainOptions);
696 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
697 } // if (SubEntry != NULL)
698 SubScreen->Hint1 = StrDuplicate(SUBSCREEN_HINT1);
699 if (GlobalConfig.HideUIFlags & HIDEUI_FLAG_EDITOR) {
700 SubScreen->Hint2 = StrDuplicate(SUBSCREEN_HINT2_NO_EDITOR);
701 } else {
702 SubScreen->Hint2 = StrDuplicate(SUBSCREEN_HINT2);
703 } // if/else
704 } // if (SubScreen != NULL)
705 } else { // existing subscreen; less initialization, and just add new entry later....
706 SubScreen = Entry->me.SubScreen;
707 } // if/else
708 return SubScreen;
709 } // REFIT_MENU_SCREEN *InitializeSubScreen()
710
711 VOID GenerateSubScreen(LOADER_ENTRY *Entry, IN REFIT_VOLUME *Volume, IN BOOLEAN GenerateReturn) {
712 REFIT_MENU_SCREEN *SubScreen;
713 LOADER_ENTRY *SubEntry;
714 CHAR16 *InitrdName;
715 CHAR16 DiagsFileName[256];
716 REFIT_FILE *File;
717 UINTN TokenCount;
718 CHAR16 **TokenList;
719
720 // create the submenu
721 if (StrLen(Entry->Title) == 0) {
722 MyFreePool(Entry->Title);
723 Entry->Title = NULL;
724 }
725 SubScreen = InitializeSubScreen(Entry);
726
727 // loader-specific submenu entries
728 if (Entry->OSType == 'M') { // entries for Mac OS X
729 #if defined(EFIX64)
730 SubEntry = InitializeLoaderEntry(Entry);
731 if (SubEntry != NULL) {
732 SubEntry->me.Title = L"Boot Mac OS X with a 64-bit kernel";
733 SubEntry->LoadOptions = L"arch=x86_64";
734 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_OSX;
735 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
736 } // if
737
738 SubEntry = InitializeLoaderEntry(Entry);
739 if (SubEntry != NULL) {
740 SubEntry->me.Title = L"Boot Mac OS X with a 32-bit kernel";
741 SubEntry->LoadOptions = L"arch=i386";
742 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_OSX;
743 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
744 } // if
745 #endif
746
747 if (!(GlobalConfig.HideUIFlags & HIDEUI_FLAG_SINGLEUSER)) {
748 SubEntry = InitializeLoaderEntry(Entry);
749 if (SubEntry != NULL) {
750 SubEntry->me.Title = L"Boot Mac OS X in verbose mode";
751 SubEntry->UseGraphicsMode = FALSE;
752 SubEntry->LoadOptions = L"-v";
753 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
754 } // if
755
756 #if defined(EFIX64)
757 SubEntry = InitializeLoaderEntry(Entry);
758 if (SubEntry != NULL) {
759 SubEntry->me.Title = L"Boot Mac OS X in verbose mode (64-bit)";
760 SubEntry->UseGraphicsMode = FALSE;
761 SubEntry->LoadOptions = L"-v arch=x86_64";
762 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
763 }
764
765 SubEntry = InitializeLoaderEntry(Entry);
766 if (SubEntry != NULL) {
767 SubEntry->me.Title = L"Boot Mac OS X in verbose mode (32-bit)";
768 SubEntry->UseGraphicsMode = FALSE;
769 SubEntry->LoadOptions = L"-v arch=i386";
770 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
771 }
772 #endif
773
774 SubEntry = InitializeLoaderEntry(Entry);
775 if (SubEntry != NULL) {
776 SubEntry->me.Title = L"Boot Mac OS X in single user mode";
777 SubEntry->UseGraphicsMode = FALSE;
778 SubEntry->LoadOptions = L"-v -s";
779 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
780 } // if
781 } // single-user mode allowed
782
783 if (!(GlobalConfig.HideUIFlags & HIDEUI_FLAG_SAFEMODE)) {
784 SubEntry = InitializeLoaderEntry(Entry);
785 if (SubEntry != NULL) {
786 SubEntry->me.Title = L"Boot Mac OS X in safe mode";
787 SubEntry->UseGraphicsMode = FALSE;
788 SubEntry->LoadOptions = L"-v -x";
789 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
790 } // if
791 } // safe mode allowed
792
793 // check for Apple hardware diagnostics
794 StrCpy(DiagsFileName, L"System\\Library\\CoreServices\\.diagnostics\\diags.efi");
795 if (FileExists(Volume->RootDir, DiagsFileName) && !(GlobalConfig.HideUIFlags & HIDEUI_FLAG_HWTEST)) {
796 SubEntry = InitializeLoaderEntry(Entry);
797 if (SubEntry != NULL) {
798 SubEntry->me.Title = L"Run Apple Hardware Test";
799 MyFreePool(SubEntry->LoaderPath);
800 SubEntry->LoaderPath = StrDuplicate(DiagsFileName);
801 SubEntry->DevicePath = FileDevicePath(Volume->DeviceHandle, SubEntry->LoaderPath);
802 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_OSX;
803 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
804 } // if
805 } // if diagnostics entry found
806
807 } else if (Entry->OSType == 'L') { // entries for Linux kernels with EFI stub loaders
808 File = ReadLinuxOptionsFile(Entry->LoaderPath, Volume);
809 if (File != NULL) {
810 InitrdName = FindInitrd(Entry->LoaderPath, Volume);
811 TokenCount = ReadTokenLine(File, &TokenList);
812 // first entry requires special processing, since it was initially set
813 // up with a default title but correct options by InitializeSubScreen(),
814 // earlier....
815 if ((TokenCount > 1) && (SubScreen->Entries != NULL) && (SubScreen->Entries[0] != NULL)) {
816 MyFreePool(SubScreen->Entries[0]->Title);
817 SubScreen->Entries[0]->Title = TokenList[0] ? StrDuplicate(TokenList[0]) : StrDuplicate(L"Boot Linux");
818 } // if
819 FreeTokenLine(&TokenList, &TokenCount);
820 while ((TokenCount = ReadTokenLine(File, &TokenList)) > 1) {
821 SubEntry = InitializeLoaderEntry(Entry);
822 SubEntry->me.Title = TokenList[0] ? StrDuplicate(TokenList[0]) : StrDuplicate(L"Boot Linux");
823 MyFreePool(SubEntry->LoadOptions);
824 SubEntry->LoadOptions = AddInitrdToOptions(TokenList[1], InitrdName);
825 FreeTokenLine(&TokenList, &TokenCount);
826 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_LINUX;
827 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
828 } // while
829 MyFreePool(InitrdName);
830 MyFreePool(File);
831 } // if
832
833 } else if (Entry->OSType == 'E') { // entries for ELILO
834 SubEntry = InitializeLoaderEntry(Entry);
835 if (SubEntry != NULL) {
836 SubEntry->me.Title = L"Run ELILO in interactive mode";
837 SubEntry->LoadOptions = L"-p";
838 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
839 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
840 }
841
842 SubEntry = InitializeLoaderEntry(Entry);
843 if (SubEntry != NULL) {
844 SubEntry->me.Title = L"Boot Linux for a 17\" iMac or a 15\" MacBook Pro (*)";
845 SubEntry->LoadOptions = L"-d 0 i17";
846 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
847 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
848 }
849
850 SubEntry = InitializeLoaderEntry(Entry);
851 if (SubEntry != NULL) {
852 SubEntry->me.Title = L"Boot Linux for a 20\" iMac (*)";
853 SubEntry->LoadOptions = L"-d 0 i20";
854 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
855 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
856 }
857
858 SubEntry = InitializeLoaderEntry(Entry);
859 if (SubEntry != NULL) {
860 SubEntry->me.Title = L"Boot Linux for a Mac Mini (*)";
861 SubEntry->LoadOptions = L"-d 0 mini";
862 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
863 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
864 }
865
866 AddMenuInfoLine(SubScreen, L"NOTE: This is an example. Entries");
867 AddMenuInfoLine(SubScreen, L"marked with (*) may not work.");
868
869 } else if (Entry->OSType == 'X') { // entries for xom.efi
870 // by default, skip the built-in selection and boot from hard disk only
871 Entry->LoadOptions = L"-s -h";
872
873 SubEntry = InitializeLoaderEntry(Entry);
874 if (SubEntry != NULL) {
875 SubEntry->me.Title = L"Boot Windows from Hard Disk";
876 SubEntry->LoadOptions = L"-s -h";
877 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
878 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
879 }
880
881 SubEntry = InitializeLoaderEntry(Entry);
882 if (SubEntry != NULL) {
883 SubEntry->me.Title = L"Boot Windows from CD-ROM";
884 SubEntry->LoadOptions = L"-s -c";
885 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
886 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
887 }
888
889 SubEntry = InitializeLoaderEntry(Entry);
890 if (SubEntry != NULL) {
891 SubEntry->me.Title = L"Run XOM in text mode";
892 SubEntry->LoadOptions = L"-v";
893 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
894 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
895 }
896 } // entries for xom.efi
897 if (GenerateReturn)
898 AddMenuEntry(SubScreen, &MenuEntryReturn);
899 Entry->me.SubScreen = SubScreen;
900 } // VOID GenerateSubScreen()
901
902 // Returns options for a Linux kernel. Reads them from an options file in the
903 // kernel's directory; and if present, adds an initrd= option for an initial
904 // RAM disk file with the same version number as the kernel file.
905 static CHAR16 * GetMainLinuxOptions(IN CHAR16 * LoaderPath, IN REFIT_VOLUME *Volume) {
906 CHAR16 *Options = NULL, *InitrdName, *FullOptions = NULL;
907
908 Options = GetFirstOptionsFromFile(LoaderPath, Volume);
909 InitrdName = FindInitrd(LoaderPath, Volume);
910 FullOptions = AddInitrdToOptions(Options, InitrdName);
911
912 MyFreePool(Options);
913 MyFreePool(InitrdName);
914 return (FullOptions);
915 } // static CHAR16 * GetMainLinuxOptions()
916
917 // Read the specified file and add values of "ID", "NAME", or "DISTRIB_ID" tokens to
918 // OSIconName list. Intended for adding Linux distribution clues gleaned from
919 // /etc/lsb-release and /etc/os-release files.
920 static VOID ParseReleaseFile(CHAR16 **OSIconName, REFIT_VOLUME *Volume, CHAR16 *FileName) {
921 UINTN FileSize = 0;
922 REFIT_FILE File;
923 CHAR16 **TokenList;
924 UINTN TokenCount = 0;
925
926 if ((Volume == NULL) || (FileName == NULL) || (OSIconName == NULL) || (*OSIconName == NULL))
927 return;
928
929 if (FileExists(Volume->RootDir, FileName) &&
930 (ReadFile(Volume->RootDir, FileName, &File, &FileSize) == EFI_SUCCESS)) {
931 do {
932 TokenCount = ReadTokenLine(&File, &TokenList);
933 if ((TokenCount > 1) && (MyStriCmp(TokenList[0], L"ID") ||
934 MyStriCmp(TokenList[0], L"NAME") ||
935 MyStriCmp(TokenList[0], L"DISTRIB_ID"))) {
936 MergeWords(OSIconName, TokenList[1], L',');
937 } // if
938 FreeTokenLine(&TokenList, &TokenCount);
939 } while (TokenCount > 0);
940 MyFreePool(File.Buffer);
941 } // if
942 } // VOID ParseReleaseFile()
943
944 // Try to guess the name of the Linux distribution & add that name to
945 // OSIconName list.
946 static VOID GuessLinuxDistribution(CHAR16 **OSIconName, REFIT_VOLUME *Volume, CHAR16 *LoaderPath) {
947 // If on Linux root fs, /etc/os-release or /etc/lsb-release file probably has clues....
948 ParseReleaseFile(OSIconName, Volume, L"etc\\lsb-release");
949 ParseReleaseFile(OSIconName, Volume, L"etc\\os-release");
950
951 // Search for clues in the kernel's filename....
952 if (StriSubCmp(L".fc", LoaderPath))
953 MergeStrings(OSIconName, L"fedora", L',');
954 if (StriSubCmp(L".el", LoaderPath))
955 MergeStrings(OSIconName, L"redhat", L',');
956 } // VOID GuessLinuxDistribution()
957
958 // Sets a few defaults for a loader entry -- mainly the icon, but also the OS type
959 // code and shortcut letter. For Linux EFI stub loaders, also sets kernel options
960 // that will (with luck) work fairly automatically.
961 VOID SetLoaderDefaults(LOADER_ENTRY *Entry, CHAR16 *LoaderPath, REFIT_VOLUME *Volume) {
962 CHAR16 *NameClues, *PathOnly, *NoExtension, *OSIconName = NULL, *Temp;
963 CHAR16 ShortcutLetter = 0;
964
965 NameClues = Basename(LoaderPath);
966 PathOnly = FindPath(LoaderPath);
967 NoExtension = StripEfiExtension(NameClues);
968
969 if (Volume->DiskKind == DISK_KIND_NET) {
970 MergeStrings(&NameClues, Entry->me.Title, L' ');
971 } else {
972 // locate a custom icon for the loader
973 // Anything found here takes precedence over the "hints" in the OSIconName variable
974 if (!Entry->me.Image) {
975 Entry->me.Image = egLoadIconAnyType(Volume->RootDir, PathOnly, NoExtension, GlobalConfig.IconSizes[ICON_SIZE_BIG]);
976 }
977 if (!Entry->me.Image) {
978 Entry->me.Image = egCopyImage(Volume->VolIconImage);
979 }
980
981 // Begin creating icon "hints" by using last part of directory path leading
982 // to the loader
983 Temp = FindLastDirName(LoaderPath);
984 MergeStrings(&OSIconName, Temp, L',');
985 MyFreePool(Temp);
986 Temp = NULL;
987 if (OSIconName != NULL) {
988 ShortcutLetter = OSIconName[0];
989 }
990
991 // Add every "word" in the volume label, delimited by spaces, dashes (-), or
992 // underscores (_), to the list of hints to be used in searching for OS
993 // icons.
994 MergeWords(&OSIconName, Volume->VolName, L',');
995 } // if/else network boot
996
997 // detect specific loaders
998 if (StriSubCmp(L"bzImage", NameClues) || StriSubCmp(L"vmlinuz", NameClues)) {
999 if (Volume->DiskKind != DISK_KIND_NET) {
1000 GuessLinuxDistribution(&OSIconName, Volume, LoaderPath);
1001 Entry->LoadOptions = GetMainLinuxOptions(LoaderPath, Volume);
1002 }
1003 MergeStrings(&OSIconName, L"linux", L',');
1004 Entry->OSType = 'L';
1005 if (ShortcutLetter == 0)
1006 ShortcutLetter = 'L';
1007 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_LINUX;
1008 } else if (StriSubCmp(L"refit", LoaderPath)) {
1009 MergeStrings(&OSIconName, L"refit", L',');
1010 Entry->OSType = 'R';
1011 ShortcutLetter = 'R';
1012 } else if (StriSubCmp(L"refind", LoaderPath)) {
1013 MergeStrings(&OSIconName, L"refind", L',');
1014 Entry->OSType = 'R';
1015 ShortcutLetter = 'R';
1016 } else if (MyStriCmp(LoaderPath, MACOSX_LOADER_PATH)) {
1017 MergeStrings(&OSIconName, L"mac", L',');
1018 Entry->OSType = 'M';
1019 ShortcutLetter = 'M';
1020 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_OSX;
1021 } else if (MyStriCmp(NameClues, L"diags.efi")) {
1022 MergeStrings(&OSIconName, L"hwtest", L',');
1023 } else if (MyStriCmp(NameClues, L"e.efi") || MyStriCmp(NameClues, L"elilo.efi") || StriSubCmp(L"elilo", NameClues)) {
1024 MergeStrings(&OSIconName, L"elilo,linux", L',');
1025 Entry->OSType = 'E';
1026 if (ShortcutLetter == 0)
1027 ShortcutLetter = 'L';
1028 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
1029 } else if (StriSubCmp(L"grub", NameClues)) {
1030 MergeStrings(&OSIconName, L"grub,linux", L',');
1031 Entry->OSType = 'G';
1032 ShortcutLetter = 'G';
1033 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_GRUB;
1034 } else if (MyStriCmp(NameClues, L"cdboot.efi") ||
1035 MyStriCmp(NameClues, L"bootmgr.efi") ||
1036 MyStriCmp(NameClues, L"bootmgfw.efi") ||
1037 MyStriCmp(NameClues, L"bkpbootmgfw.efi")) {
1038 MergeStrings(&OSIconName, L"win8", L',');
1039 Entry->OSType = 'W';
1040 ShortcutLetter = 'W';
1041 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
1042 } else if (MyStriCmp(NameClues, L"xom.efi")) {
1043 MergeStrings(&OSIconName, L"xom,win,win8", L',');
1044 Entry->OSType = 'X';
1045 ShortcutLetter = 'W';
1046 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
1047 }
1048 else if (StriSubCmp(L"ipxe", NameClues)) {
1049 Entry->OSType = 'N';
1050 ShortcutLetter = 'N';
1051 MergeStrings(&OSIconName, L"network", L',');
1052 }
1053
1054 if ((ShortcutLetter >= 'a') && (ShortcutLetter <= 'z'))
1055 ShortcutLetter = ShortcutLetter - 'a' + 'A'; // convert lowercase to uppercase
1056 Entry->me.ShortcutLetter = ShortcutLetter;
1057 if (Entry->me.Image == NULL)
1058 Entry->me.Image = LoadOSIcon(OSIconName, L"unknown", FALSE);
1059 MyFreePool(PathOnly);
1060 } // VOID SetLoaderDefaults()
1061
1062 // Add a specified EFI boot loader to the list, using automatic settings
1063 // for icons, options, etc.
1064 static LOADER_ENTRY * AddLoaderEntry(IN CHAR16 *LoaderPath, IN CHAR16 *LoaderTitle, IN REFIT_VOLUME *Volume, IN BOOLEAN SubScreenReturn) {
1065 LOADER_ENTRY *Entry;
1066
1067 CleanUpPathNameSlashes(LoaderPath);
1068 Entry = InitializeLoaderEntry(NULL);
1069 if (Entry != NULL) {
1070 Entry->Title = StrDuplicate((LoaderTitle != NULL) ? LoaderTitle : LoaderPath);
1071 Entry->me.Title = AllocateZeroPool(sizeof(CHAR16) * 256);
1072 // Extra space at end of Entry->me.Title enables searching on Volume->VolName even if another volume
1073 // name is identical except for something added to the end (e.g., VolB1 vs. VolB12).
1074 // Note: Volume->VolName will be NULL for network boot programs.
1075 if (Volume->VolName)
1076 SPrint(Entry->me.Title, 255, L"Boot %s from %s ", (LoaderTitle != NULL) ? LoaderTitle : LoaderPath, Volume->VolName);
1077 else
1078 SPrint(Entry->me.Title, 255, L"Boot %s ", (LoaderTitle != NULL) ? LoaderTitle : LoaderPath);
1079 Entry->me.Row = 0;
1080 Entry->me.BadgeImage = Volume->VolBadgeImage;
1081 if ((LoaderPath != NULL) && (LoaderPath[0] != L'\\')) {
1082 Entry->LoaderPath = StrDuplicate(L"\\");
1083 } else {
1084 Entry->LoaderPath = NULL;
1085 }
1086 MergeStrings(&(Entry->LoaderPath), LoaderPath, 0);
1087 Entry->VolName = Volume->VolName;
1088 Entry->DevicePath = FileDevicePath(Volume->DeviceHandle, Entry->LoaderPath);
1089 SetLoaderDefaults(Entry, LoaderPath, Volume);
1090 GenerateSubScreen(Entry, Volume, SubScreenReturn);
1091 AddMenuEntry(&MainMenu, (REFIT_MENU_ENTRY *)Entry);
1092 }
1093
1094 return(Entry);
1095 } // LOADER_ENTRY * AddLoaderEntry()
1096
1097 // Add a Linux kernel as a submenu entry for another (pre-existing) Linux kernel entry.
1098 static VOID AddKernelToSubmenu(LOADER_ENTRY * TargetLoader, CHAR16 *FileName, REFIT_VOLUME *Volume) {
1099 REFIT_FILE *File;
1100 CHAR16 **TokenList = NULL, *InitrdName, *SubmenuName = NULL, *VolName = NULL, *Path = NULL, *Title;
1101 REFIT_MENU_SCREEN *SubScreen;
1102 LOADER_ENTRY *SubEntry;
1103 UINTN TokenCount;
1104
1105 File = ReadLinuxOptionsFile(TargetLoader->LoaderPath, Volume);
1106 if (File != NULL) {
1107 SubScreen = TargetLoader->me.SubScreen;
1108 InitrdName = FindInitrd(FileName, Volume);
1109 while ((TokenCount = ReadTokenLine(File, &TokenList)) > 1) {
1110 SubEntry = InitializeLoaderEntry(TargetLoader);
1111 SplitPathName(FileName, &VolName, &Path, &SubmenuName);
1112 MergeStrings(&SubmenuName, L": ", '\0');
1113 MergeStrings(&SubmenuName, TokenList[0] ? StrDuplicate(TokenList[0]) : StrDuplicate(L"Boot Linux"), '\0');
1114 Title = StrDuplicate(SubmenuName);
1115 LimitStringLength(Title, MAX_LINE_LENGTH);
1116 SubEntry->me.Title = Title;
1117 MyFreePool(SubEntry->LoadOptions);
1118 SubEntry->LoadOptions = AddInitrdToOptions(TokenList[1], InitrdName);
1119 MyFreePool(SubEntry->LoaderPath);
1120 SubEntry->LoaderPath = StrDuplicate(FileName);
1121 CleanUpPathNameSlashes(SubEntry->LoaderPath);
1122 SubEntry->DevicePath = FileDevicePath(Volume->DeviceHandle, SubEntry->LoaderPath);
1123 FreeTokenLine(&TokenList, &TokenCount);
1124 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_LINUX;
1125 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
1126 } // while
1127 MyFreePool(VolName);
1128 MyFreePool(Path);
1129 MyFreePool(SubmenuName);
1130 MyFreePool(InitrdName);
1131 MyFreePool(File);
1132 } // if
1133 } // static VOID AddKernelToSubmenu()
1134
1135 // Returns -1 if (Time1 < Time2), +1 if (Time1 > Time2), or 0 if
1136 // (Time1 == Time2). Precision is only to the nearest second; since
1137 // this is used for sorting boot loader entries, differences smaller
1138 // than this are likely to be meaningless (and unlikely!).
1139 INTN TimeComp(IN EFI_TIME *Time1, IN EFI_TIME *Time2) {
1140 INT64 Time1InSeconds, Time2InSeconds;
1141
1142 // Following values are overestimates; I'm assuming 31 days in every month.
1143 // This is fine for the purpose of this function, which is limited
1144 Time1InSeconds = Time1->Second + (Time1->Minute * 60) + (Time1->Hour * 3600) + (Time1->Day * 86400) +
1145 (Time1->Month * 2678400) + ((Time1->Year - 1998) * 32140800);
1146 Time2InSeconds = Time2->Second + (Time2->Minute * 60) + (Time2->Hour * 3600) + (Time2->Day * 86400) +
1147 (Time2->Month * 2678400) + ((Time2->Year - 1998) * 32140800);
1148 if (Time1InSeconds < Time2InSeconds)
1149 return (-1);
1150 else if (Time1InSeconds > Time2InSeconds)
1151 return (1);
1152
1153 return 0;
1154 } // INTN TimeComp()
1155
1156 // Adds a loader list element, keeping it sorted by date. Returns the new
1157 // first element (the one with the most recent date).
1158 static struct LOADER_LIST * AddLoaderListEntry(struct LOADER_LIST *LoaderList, struct LOADER_LIST *NewEntry) {
1159 struct LOADER_LIST *LatestEntry, *CurrentEntry, *PrevEntry = NULL;
1160
1161 LatestEntry = CurrentEntry = LoaderList;
1162 if (LoaderList == NULL) {
1163 LatestEntry = NewEntry;
1164 } else {
1165 while ((CurrentEntry != NULL) && (TimeComp(&(NewEntry->TimeStamp), &(CurrentEntry->TimeStamp)) < 0)) {
1166 PrevEntry = CurrentEntry;
1167 CurrentEntry = CurrentEntry->NextEntry;
1168 } // while
1169 NewEntry->NextEntry = CurrentEntry;
1170 if (PrevEntry == NULL) {
1171 LatestEntry = NewEntry;
1172 } else {
1173 PrevEntry->NextEntry = NewEntry;
1174 } // if/else
1175 } // if/else
1176 return (LatestEntry);
1177 } // static VOID AddLoaderListEntry()
1178
1179 // Delete the LOADER_LIST linked list
1180 static VOID CleanUpLoaderList(struct LOADER_LIST *LoaderList) {
1181 struct LOADER_LIST *Temp;
1182
1183 while (LoaderList != NULL) {
1184 Temp = LoaderList;
1185 LoaderList = LoaderList->NextEntry;
1186 MyFreePool(Temp->FileName);
1187 MyFreePool(Temp);
1188 } // while
1189 } // static VOID CleanUpLoaderList()
1190
1191 // Returns FALSE if the specified file/volume matches the GlobalConfig.DontScanDirs
1192 // or GlobalConfig.DontScanVolumes specification, or if Path points to a volume
1193 // other than the one specified by Volume, or if the specified path is SelfDir.
1194 // Returns TRUE if none of these conditions is met -- that is, if the path is
1195 // eligible for scanning.
1196 static BOOLEAN ShouldScan(REFIT_VOLUME *Volume, CHAR16 *Path) {
1197 CHAR16 *VolName = NULL, *DontScanDir, *PathCopy = NULL;
1198 UINTN i = 0;
1199 BOOLEAN ScanIt = TRUE;
1200
1201 if ((IsIn(Volume->VolName, GlobalConfig.DontScanVolumes)) || (IsIn(Volume->PartName, GlobalConfig.DontScanVolumes)))
1202 return FALSE;
1203
1204 if (MyStriCmp(Path, SelfDirPath) && (Volume->DeviceHandle == SelfVolume->DeviceHandle))
1205 return FALSE;
1206
1207 // See if Path includes an explicit volume declaration that's NOT Volume....
1208 PathCopy = StrDuplicate(Path);
1209 if (SplitVolumeAndFilename(&PathCopy, &VolName)) {
1210 VolumeNumberToName(Volume, &VolName);
1211 if (VolName && !MyStriCmp(VolName, Volume->VolName)) {
1212 ScanIt = FALSE;
1213 } // if
1214 } // if Path includes volume specification
1215 MyFreePool(PathCopy);
1216 MyFreePool(VolName);
1217 VolName = NULL;
1218
1219 // See if Volume is in GlobalConfig.DontScanDirs....
1220 while (ScanIt && (DontScanDir = FindCommaDelimited(GlobalConfig.DontScanDirs, i++))) {
1221 SplitVolumeAndFilename(&DontScanDir, &VolName);
1222 CleanUpPathNameSlashes(DontScanDir);
1223 VolumeNumberToName(Volume, &VolName);
1224 if (VolName != NULL) {
1225 if (MyStriCmp(VolName, Volume->VolName) && MyStriCmp(DontScanDir, Path))
1226 ScanIt = FALSE;
1227 } else {
1228 if (MyStriCmp(DontScanDir, Path))
1229 ScanIt = FALSE;
1230 }
1231 MyFreePool(DontScanDir);
1232 MyFreePool(VolName);
1233 DontScanDir = NULL;
1234 VolName = NULL;
1235 } // while()
1236
1237 return ScanIt;
1238 } // BOOLEAN ShouldScan()
1239
1240 // Returns TRUE if the file is byte-for-byte identical with the fallback file
1241 // on the volume AND if the file is not itself the fallback file; returns
1242 // FALSE if the file is not identical to the fallback file OR if the file
1243 // IS the fallback file. Intended for use in excluding the fallback boot
1244 // loader when it's a duplicate of another boot loader.
1245 static BOOLEAN DuplicatesFallback(IN REFIT_VOLUME *Volume, IN CHAR16 *FileName) {
1246 CHAR8 *FileContents, *FallbackContents;
1247 EFI_FILE_HANDLE FileHandle, FallbackHandle;
1248 EFI_FILE_INFO *FileInfo, *FallbackInfo;
1249 UINTN FileSize = 0, FallbackSize = 0;
1250 EFI_STATUS Status;
1251 BOOLEAN AreIdentical = FALSE;
1252
1253 if (!FileExists(Volume->RootDir, FileName) || !FileExists(Volume->RootDir, FALLBACK_FULLNAME))
1254 return FALSE;
1255
1256 CleanUpPathNameSlashes(FileName);
1257
1258 if (MyStriCmp(FileName, FALLBACK_FULLNAME))
1259 return FALSE; // identical filenames, so not a duplicate....
1260
1261 Status = refit_call5_wrapper(Volume->RootDir->Open, Volume->RootDir, &FileHandle, FileName, EFI_FILE_MODE_READ, 0);
1262 if (Status == EFI_SUCCESS) {
1263 FileInfo = LibFileInfo(FileHandle);
1264 FileSize = FileInfo->FileSize;
1265 } else {
1266 return FALSE;
1267 }
1268
1269 Status = refit_call5_wrapper(Volume->RootDir->Open, Volume->RootDir, &FallbackHandle, FALLBACK_FULLNAME, EFI_FILE_MODE_READ, 0);
1270 if (Status == EFI_SUCCESS) {
1271 FallbackInfo = LibFileInfo(FallbackHandle);
1272 FallbackSize = FallbackInfo->FileSize;
1273 } else {
1274 refit_call1_wrapper(FileHandle->Close, FileHandle);
1275 return FALSE;
1276 }
1277
1278 if (FallbackSize != FileSize) { // not same size, so can't be identical
1279 AreIdentical = FALSE;
1280 } else { // could be identical; do full check....
1281 FileContents = AllocatePool(FileSize);
1282 FallbackContents = AllocatePool(FallbackSize);
1283 if (FileContents && FallbackContents) {
1284 Status = refit_call3_wrapper(FileHandle->Read, FileHandle, &FileSize, FileContents);
1285 if (Status == EFI_SUCCESS) {
1286 Status = refit_call3_wrapper(FallbackHandle->Read, FallbackHandle, &FallbackSize, FallbackContents);
1287 }
1288 if (Status == EFI_SUCCESS) {
1289 AreIdentical = (CompareMem(FileContents, FallbackContents, FileSize) == 0);
1290 } // if
1291 } // if
1292 MyFreePool(FileContents);
1293 MyFreePool(FallbackContents);
1294 } // if/else
1295
1296 // BUG ALERT: Some systems (e.g., DUET, some Macs with large displays) crash if the
1297 // following two calls are reversed. Go figure....
1298 refit_call1_wrapper(FileHandle->Close, FallbackHandle);
1299 refit_call1_wrapper(FileHandle->Close, FileHandle);
1300 return AreIdentical;
1301 } // BOOLEAN DuplicatesFallback()
1302
1303 // Returns FALSE if two measures of file size are identical for a single file,
1304 // TRUE if not or if the file can't be opened and the other measure is non-0.
1305 // Despite the function's name, this isn't really a direct test of symbolic
1306 // link status, since EFI doesn't officially support symlinks. It does seem
1307 // to be a reliable indicator, though. (OTOH, some disk errors might cause a
1308 // file to fail to open, which would return a false positive -- but as I use
1309 // this function to exclude symbolic links from the list of boot loaders,
1310 // that would be fine, since such boot loaders wouldn't work.)
1311 static BOOLEAN IsSymbolicLink(REFIT_VOLUME *Volume, CHAR16 *Path, EFI_FILE_INFO *DirEntry) {
1312 EFI_FILE_HANDLE FileHandle;
1313 EFI_FILE_INFO *FileInfo = NULL;
1314 EFI_STATUS Status;
1315 UINTN FileSize2 = 0;
1316 CHAR16 *FileName;
1317
1318 FileName = StrDuplicate(Path);
1319 MergeStrings(&FileName, DirEntry->FileName, L'\\');
1320 CleanUpPathNameSlashes(FileName);
1321
1322 Status = refit_call5_wrapper(Volume->RootDir->Open, Volume->RootDir, &FileHandle, FileName, EFI_FILE_MODE_READ, 0);
1323 if (Status == EFI_SUCCESS) {
1324 FileInfo = LibFileInfo(FileHandle);
1325 if (FileInfo != NULL)
1326 FileSize2 = FileInfo->FileSize;
1327 }
1328
1329 MyFreePool(FileName);
1330 MyFreePool(FileInfo);
1331
1332 return (DirEntry->FileSize != FileSize2);
1333 } // BOOLEAN IsSymbolicLink()
1334
1335 // Returns TRUE if a file with the same name as the original but with
1336 // ".efi.signed" is also present in the same directory. Ubuntu is using
1337 // this filename as a signed version of the original unsigned kernel, and
1338 // there's no point in cluttering the display with two kernels that will
1339 // behave identically on non-SB systems, or when one will fail when SB
1340 // is active.
1341 static BOOLEAN HasSignedCounterpart(IN REFIT_VOLUME *Volume, IN CHAR16 *Path, IN CHAR16 *Filename) {
1342 CHAR16 *NewFile = NULL;
1343 BOOLEAN retval = FALSE;
1344
1345 MergeStrings(&NewFile, Path, 0);
1346 MergeStrings(&NewFile, Filename, L'\\');
1347 MergeStrings(&NewFile, L".efi.signed", 0);
1348 if (NewFile != NULL) {
1349 CleanUpPathNameSlashes(NewFile);
1350 if (FileExists(Volume->RootDir, NewFile))
1351 retval = TRUE;
1352 MyFreePool(NewFile);
1353 } // if
1354
1355 return retval;
1356 } // BOOLEAN HasSignedCounterpart()
1357
1358 // Scan an individual directory for EFI boot loader files and, if found,
1359 // add them to the list. Exception: Ignores FALLBACK_FULLNAME, which is picked
1360 // up in ScanEfiFiles(). Sorts the entries within the loader directory so that
1361 // the most recent one appears first in the list.
1362 // Returns TRUE if a duplicate for FALLBACK_FILENAME was found, FALSE if not.
1363 static BOOLEAN ScanLoaderDir(IN REFIT_VOLUME *Volume, IN CHAR16 *Path, IN CHAR16 *Pattern)
1364 {
1365 EFI_STATUS Status;
1366 REFIT_DIR_ITER DirIter;
1367 EFI_FILE_INFO *DirEntry;
1368 CHAR16 FileName[256], *Extension;
1369 struct LOADER_LIST *LoaderList = NULL, *NewLoader;
1370 LOADER_ENTRY *FirstKernel = NULL, *LatestEntry = NULL;
1371 BOOLEAN FoundFallbackDuplicate = FALSE, IsLinux = FALSE, InSelfPath;
1372
1373 InSelfPath = MyStriCmp(Path, SelfDirPath);
1374 if ((!SelfDirPath || !Path || (InSelfPath && (Volume->DeviceHandle != SelfVolume->DeviceHandle)) ||
1375 (!InSelfPath)) && (ShouldScan(Volume, Path))) {
1376 // look through contents of the directory
1377 DirIterOpen(Volume->RootDir, Path, &DirIter);
1378 while (DirIterNext(&DirIter, 2, Pattern, &DirEntry)) {
1379 Extension = FindExtension(DirEntry->FileName);
1380 if (DirEntry->FileName[0] == '.' ||
1381 MyStriCmp(Extension, L".icns") ||
1382 MyStriCmp(Extension, L".png") ||
1383 (MyStriCmp(DirEntry->FileName, FALLBACK_BASENAME) && (MyStriCmp(Path, L"EFI\\BOOT"))) ||
1384 StriSubCmp(L"shell", DirEntry->FileName) ||
1385 IsSymbolicLink(Volume, Path, DirEntry) || /* is symbolic link */
1386 HasSignedCounterpart(Volume, Path, DirEntry->FileName) || /* a file with same name plus ".efi.signed" is present */
1387 FilenameIn(Volume, Path, DirEntry->FileName, GlobalConfig.DontScanFiles))
1388 continue; // skip this
1389
1390 if (Path)
1391 SPrint(FileName, 255, L"\\%s\\%s", Path, DirEntry->FileName);
1392 else
1393 SPrint(FileName, 255, L"\\%s", DirEntry->FileName);
1394 CleanUpPathNameSlashes(FileName);
1395
1396 if(!IsValidLoader(Volume->RootDir, FileName))
1397 continue;
1398
1399 NewLoader = AllocateZeroPool(sizeof(struct LOADER_LIST));
1400 if (NewLoader != NULL) {
1401 NewLoader->FileName = StrDuplicate(FileName);
1402 NewLoader->TimeStamp = DirEntry->ModificationTime;
1403 LoaderList = AddLoaderListEntry(LoaderList, NewLoader);
1404 if (DuplicatesFallback(Volume, FileName))
1405 FoundFallbackDuplicate = TRUE;
1406 } // if
1407 MyFreePool(Extension);
1408 } // while
1409
1410 NewLoader = LoaderList;
1411 while (NewLoader != NULL) {
1412 IsLinux = (StriSubCmp(L"bzImage", NewLoader->FileName) || StriSubCmp(L"vmlinuz", NewLoader->FileName));
1413 if ((FirstKernel != NULL) && IsLinux && GlobalConfig.FoldLinuxKernels) {
1414 AddKernelToSubmenu(FirstKernel, NewLoader->FileName, Volume);
1415 } else {
1416 LatestEntry = AddLoaderEntry(NewLoader->FileName, NULL, Volume, !(IsLinux && GlobalConfig.FoldLinuxKernels));
1417 if (IsLinux && (FirstKernel == NULL))
1418 FirstKernel = LatestEntry;
1419 }
1420 NewLoader = NewLoader->NextEntry;
1421 } // while
1422 if ((NewLoader != NULL) && (FirstKernel != NULL) && IsLinux && GlobalConfig.FoldLinuxKernels)
1423 AddMenuEntry(FirstKernel->me.SubScreen, &MenuEntryReturn);
1424
1425 CleanUpLoaderList(LoaderList);
1426 Status = DirIterClose(&DirIter);
1427 // NOTE: EFI_INVALID_PARAMETER really is an error that should be reported;
1428 // but I've gotten reports from users who are getting this error occasionally
1429 // and I can't find anything wrong or reproduce the problem, so I'm putting
1430 // it down to buggy EFI implementations and ignoring that particular error....
1431 if ((Status != EFI_NOT_FOUND) && (Status != EFI_INVALID_PARAMETER)) {
1432 if (Path)
1433 SPrint(FileName, 255, L"while scanning the %s directory", Path);
1434 else
1435 StrCpy(FileName, L"while scanning the root directory");
1436 CheckError(Status, FileName);
1437 } // if (Status != EFI_NOT_FOUND)
1438 } // if not scanning a blacklisted directory
1439
1440 return FoundFallbackDuplicate;
1441 } /* static VOID ScanLoaderDir() */
1442
1443 // Run the IPXE_DISCOVER_NAME program, which obtains the IP address of the boot
1444 // server and the name of the boot file it delivers.
1445 CHAR16* RuniPXEDiscover(EFI_HANDLE Volume)
1446 {
1447 EFI_STATUS Status;
1448 EFI_DEVICE_PATH *FilePath;
1449 EFI_HANDLE iPXEHandle;
1450 CHAR16 *boot_info = NULL;
1451 UINTN boot_info_size = 0;
1452
1453 FilePath = FileDevicePath (Volume, IPXE_DISCOVER_NAME);
1454 Status = refit_call6_wrapper(BS->LoadImage, FALSE, SelfImageHandle, FilePath, NULL, 0, &iPXEHandle);
1455 if (Status != 0)
1456 return NULL;
1457
1458 Status = refit_call3_wrapper(BS->StartImage, iPXEHandle, &boot_info_size, &boot_info);
1459
1460 return boot_info;
1461 } // RuniPXEDiscover()
1462
1463 // Scan for network (PXE) boot servers. This function relies on the presence
1464 // of the IPXE_DISCOVER_NAME and IPXE_NAME program files on the volume from
1465 // which rEFInd launched. As of December 6, 2014, these tools aren't entirely
1466 // reliable. See BUILDING.txt for information on building them.
1467 static VOID ScanNetboot() {
1468 CHAR16 *iPXEFileName = IPXE_NAME;
1469 CHAR16 *Location;
1470 REFIT_VOLUME *NetVolume;
1471
1472 if (FileExists(SelfVolume->RootDir, IPXE_DISCOVER_NAME) &&
1473 FileExists(SelfVolume->RootDir, IPXE_NAME) &&
1474 IsValidLoader(SelfVolume->RootDir, IPXE_DISCOVER_NAME) &&
1475 IsValidLoader(SelfVolume->RootDir, IPXE_NAME)) {
1476 Location = RuniPXEDiscover(SelfVolume->DeviceHandle);
1477 if (Location != NULL && FileExists(SelfVolume->RootDir, iPXEFileName)) {
1478 NetVolume = AllocatePool(sizeof(REFIT_VOLUME));
1479 CopyMem(NetVolume, SelfVolume, sizeof(REFIT_VOLUME));
1480 NetVolume->DiskKind = DISK_KIND_NET;
1481 NetVolume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_NET);
1482 NetVolume->PartName = NetVolume->VolName = NULL;
1483 AddLoaderEntry(iPXEFileName, Location, NetVolume, TRUE);
1484 MyFreePool(NetVolume);
1485 } // if support files exist and are valid
1486 }
1487 } // VOID ScanNetBoot()
1488
1489 static VOID ScanEfiFiles(REFIT_VOLUME *Volume) {
1490 EFI_STATUS Status;
1491 REFIT_DIR_ITER EfiDirIter;
1492 EFI_FILE_INFO *EfiDirEntry;
1493 CHAR16 FileName[256], *Directory = NULL, *MatchPatterns, *VolName = NULL, *SelfPath;
1494 UINTN i, Length;
1495 BOOLEAN ScanFallbackLoader = TRUE;
1496 BOOLEAN FoundBRBackup = FALSE;
1497
1498 if (Volume && (Volume->RootDir != NULL) && (Volume->VolName != NULL) && (Volume->IsReadable)) {
1499 MatchPatterns = StrDuplicate(LOADER_MATCH_PATTERNS);
1500 if (GlobalConfig.ScanAllLinux)
1501 MergeStrings(&MatchPatterns, LINUX_MATCH_PATTERNS, L',');
1502
1503 // check for Mac OS X boot loader
1504 if (ShouldScan(Volume, MACOSX_LOADER_DIR)) {
1505 StrCpy(FileName, MACOSX_LOADER_PATH);
1506 if (FileExists(Volume->RootDir, FileName) && !FilenameIn(Volume, MACOSX_LOADER_DIR, L"boot.efi", GlobalConfig.DontScanFiles)) {
1507 AddLoaderEntry(FileName, L"Mac OS X", Volume, TRUE);
1508 if (DuplicatesFallback(Volume, FileName))
1509 ScanFallbackLoader = FALSE;
1510 }
1511
1512 // check for XOM
1513 StrCpy(FileName, L"System\\Library\\CoreServices\\xom.efi");
1514 if (FileExists(Volume->RootDir, FileName) && !FilenameIn(Volume, MACOSX_LOADER_DIR, L"xom.efi", GlobalConfig.DontScanFiles)) {
1515 AddLoaderEntry(FileName, L"Windows XP (XoM)", Volume, TRUE);
1516 if (DuplicatesFallback(Volume, FileName))
1517 ScanFallbackLoader = FALSE;
1518 }
1519 } // if should scan Mac directory
1520
1521 // check for Microsoft boot loader/menu
1522 if (ShouldScan(Volume, L"EFI\\Microsoft\\Boot")) {
1523 StrCpy(FileName, L"EFI\\Microsoft\\Boot\\bkpbootmgfw.efi");
1524 if (FileExists(Volume->RootDir, FileName) && !FilenameIn(Volume, L"EFI\\Microsoft\\Boot", L"bkpbootmgfw.efi",
1525 GlobalConfig.DontScanFiles)) {
1526 AddLoaderEntry(FileName, L"Microsoft EFI boot (Boot Repair backup)", Volume, TRUE);
1527 FoundBRBackup = TRUE;
1528 if (DuplicatesFallback(Volume, FileName))
1529 ScanFallbackLoader = FALSE;
1530 }
1531 StrCpy(FileName, L"EFI\\Microsoft\\Boot\\bootmgfw.efi");
1532 if (FileExists(Volume->RootDir, FileName) &&
1533 !FilenameIn(Volume, L"EFI\\Microsoft\\Boot", L"bootmgfw.efi", GlobalConfig.DontScanFiles)) {
1534 if (FoundBRBackup)
1535 AddLoaderEntry(FileName, L"Supposed Microsoft EFI boot (probably GRUB)", Volume, TRUE);
1536 else
1537 AddLoaderEntry(FileName, L"Microsoft EFI boot", Volume, TRUE);
1538 if (DuplicatesFallback(Volume, FileName))
1539 ScanFallbackLoader = FALSE;
1540 }
1541 } // if
1542
1543 // scan the root directory for EFI executables
1544 if (ScanLoaderDir(Volume, L"\\", MatchPatterns))
1545 ScanFallbackLoader = FALSE;
1546
1547 // scan subdirectories of the EFI directory (as per the standard)
1548 DirIterOpen(Volume->RootDir, L"EFI", &EfiDirIter);
1549 while (DirIterNext(&EfiDirIter, 1, NULL, &EfiDirEntry)) {
1550 if (MyStriCmp(EfiDirEntry->FileName, L"tools") || EfiDirEntry->FileName[0] == '.')
1551 continue; // skip this, doesn't contain boot loaders or is scanned later
1552 SPrint(FileName, 255, L"EFI\\%s", EfiDirEntry->FileName);
1553 if (ScanLoaderDir(Volume, FileName, MatchPatterns))
1554 ScanFallbackLoader = FALSE;
1555 } // while()
1556 Status = DirIterClose(&EfiDirIter);
1557 if ((Status != EFI_NOT_FOUND) && (Status != EFI_INVALID_PARAMETER))
1558 CheckError(Status, L"while scanning the EFI directory");
1559
1560 // Scan user-specified (or additional default) directories....
1561 i = 0;
1562 while ((Directory = FindCommaDelimited(GlobalConfig.AlsoScan, i++)) != NULL) {
1563 if (ShouldScan(Volume, Directory)) {
1564 SplitVolumeAndFilename(&Directory, &VolName);
1565 CleanUpPathNameSlashes(Directory);
1566 Length = StrLen(Directory);
1567 if ((Length > 0) && ScanLoaderDir(Volume, Directory, MatchPatterns))
1568 ScanFallbackLoader = FALSE;
1569 MyFreePool(VolName);
1570 } // if should scan dir
1571 MyFreePool(Directory);
1572 } // while
1573
1574 // Don't scan the fallback loader if it's on the same volume and a duplicate of rEFInd itself....
1575 SelfPath = DevicePathToStr(SelfLoadedImage->FilePath);
1576 CleanUpPathNameSlashes(SelfPath);
1577 if ((Volume->DeviceHandle == SelfLoadedImage->DeviceHandle) && DuplicatesFallback(Volume, SelfPath))
1578 ScanFallbackLoader = FALSE;
1579
1580 // If not a duplicate & if it exists & if it's not us, create an entry
1581 // for the fallback boot loader
1582 if (ScanFallbackLoader && FileExists(Volume->RootDir, FALLBACK_FULLNAME) && ShouldScan(Volume, L"EFI\\BOOT")) {
1583 AddLoaderEntry(FALLBACK_FULLNAME, L"Fallback boot loader", Volume, TRUE);
1584 }
1585 } // if
1586 } // static VOID ScanEfiFiles()
1587
1588 // Scan internal disks for valid EFI boot loaders....
1589 static VOID ScanInternal(VOID) {
1590 UINTN VolumeIndex;
1591
1592 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1593 if (Volumes[VolumeIndex]->DiskKind == DISK_KIND_INTERNAL) {
1594 ScanEfiFiles(Volumes[VolumeIndex]);
1595 }
1596 } // for
1597 } // static VOID ScanInternal()
1598
1599 // Scan external disks for valid EFI boot loaders....
1600 static VOID ScanExternal(VOID) {
1601 UINTN VolumeIndex;
1602
1603 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1604 if (Volumes[VolumeIndex]->DiskKind == DISK_KIND_EXTERNAL) {
1605 ScanEfiFiles(Volumes[VolumeIndex]);
1606 }
1607 } // for
1608 } // static VOID ScanExternal()
1609
1610 // Scan internal disks for valid EFI boot loaders....
1611 static VOID ScanOptical(VOID) {
1612 UINTN VolumeIndex;
1613
1614 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1615 if (Volumes[VolumeIndex]->DiskKind == DISK_KIND_OPTICAL) {
1616 ScanEfiFiles(Volumes[VolumeIndex]);
1617 }
1618 } // for
1619 } // static VOID ScanOptical()
1620
1621 // default volume badge icon based on disk kind
1622 EG_IMAGE * GetDiskBadge(IN UINTN DiskType) {
1623 EG_IMAGE * Badge = NULL;
1624
1625 switch (DiskType) {
1626 case BBS_HARDDISK:
1627 Badge = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
1628 break;
1629 case BBS_USB:
1630 Badge = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
1631 break;
1632 case BBS_CDROM:
1633 Badge = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
1634 break;
1635 } // switch()
1636 return Badge;
1637 } // EG_IMAGE * GetDiskBadge()
1638
1639 //
1640 // pre-boot tool functions
1641 //
1642
1643 static VOID StartTool(IN LOADER_ENTRY *Entry)
1644 {
1645 BeginExternalScreen(Entry->UseGraphicsMode, Entry->me.Title + 6); // assumes "Start <title>" as assigned below
1646 StoreLoaderName(Entry->me.Title);
1647 StartEFIImage(Entry->DevicePath, Entry->LoadOptions, TYPE_EFI,
1648 Basename(Entry->LoaderPath), Entry->OSType, NULL, TRUE, FALSE);
1649 FinishExternalScreen();
1650 } /* static VOID StartTool() */
1651
1652 static LOADER_ENTRY * AddToolEntry(EFI_HANDLE DeviceHandle, IN CHAR16 *LoaderPath, IN CHAR16 *LoaderTitle, IN EG_IMAGE *Image,
1653 IN CHAR16 ShortcutLetter, IN BOOLEAN UseGraphicsMode)
1654 {
1655 LOADER_ENTRY *Entry;
1656 CHAR16 *TitleStr = NULL;
1657
1658 Entry = AllocateZeroPool(sizeof(LOADER_ENTRY));
1659
1660 TitleStr = PoolPrint(L"Start %s", LoaderTitle);
1661 Entry->me.Title = TitleStr;
1662 Entry->me.Tag = TAG_TOOL;
1663 Entry->me.Row = 1;
1664 Entry->me.ShortcutLetter = ShortcutLetter;
1665 Entry->me.Image = Image;
1666 Entry->LoaderPath = (LoaderPath) ? StrDuplicate(LoaderPath) : NULL;
1667 Entry->DevicePath = FileDevicePath(DeviceHandle, Entry->LoaderPath);
1668 Entry->UseGraphicsMode = UseGraphicsMode;
1669
1670 AddMenuEntry(&MainMenu, (REFIT_MENU_ENTRY *)Entry);
1671 return Entry;
1672 } /* static LOADER_ENTRY * AddToolEntry() */
1673
1674 //
1675 // pre-boot driver functions
1676 //
1677
1678 static UINTN ScanDriverDir(IN CHAR16 *Path)
1679 {
1680 EFI_STATUS Status;
1681 REFIT_DIR_ITER DirIter;
1682 UINTN NumFound = 0;
1683 EFI_FILE_INFO *DirEntry;
1684 CHAR16 FileName[256];
1685
1686 CleanUpPathNameSlashes(Path);
1687 // look through contents of the directory
1688 DirIterOpen(SelfRootDir, Path, &DirIter);
1689 while (DirIterNext(&DirIter, 2, LOADER_MATCH_PATTERNS, &DirEntry)) {
1690 if (DirEntry->FileName[0] == '.')
1691 continue; // skip this
1692
1693 SPrint(FileName, 255, L"%s\\%s", Path, DirEntry->FileName);
1694 NumFound++;
1695 Status = StartEFIImage(FileDevicePath(SelfLoadedImage->DeviceHandle, FileName),
1696 L"", TYPE_EFI, DirEntry->FileName, 0, NULL, FALSE, TRUE);
1697 }
1698 Status = DirIterClose(&DirIter);
1699 if ((Status != EFI_NOT_FOUND) && (Status != EFI_INVALID_PARAMETER)) {
1700 SPrint(FileName, 255, L"while scanning the %s directory", Path);
1701 CheckError(Status, FileName);
1702 }
1703 return (NumFound);
1704 }
1705
1706 #ifdef __MAKEWITH_GNUEFI
1707 static EFI_STATUS ConnectAllDriversToAllControllers(VOID)
1708 {
1709 EFI_STATUS Status;
1710 UINTN AllHandleCount;
1711 EFI_HANDLE *AllHandleBuffer;
1712 UINTN Index;
1713 UINTN HandleCount;
1714 EFI_HANDLE *HandleBuffer;
1715 UINT32 *HandleType;
1716 UINTN HandleIndex;
1717 BOOLEAN Parent;
1718 BOOLEAN Device;
1719
1720 Status = LibLocateHandle(AllHandles,
1721 NULL,
1722 NULL,
1723 &AllHandleCount,
1724 &AllHandleBuffer);
1725 if (EFI_ERROR(Status))
1726 return Status;
1727
1728 for (Index = 0; Index < AllHandleCount; Index++) {
1729 //
1730 // Scan the handle database
1731 //
1732 Status = LibScanHandleDatabase(NULL,
1733 NULL,
1734 AllHandleBuffer[Index],
1735 NULL,
1736 &HandleCount,
1737 &HandleBuffer,
1738 &HandleType);
1739 if (EFI_ERROR (Status))
1740 goto Done;
1741
1742 Device = TRUE;
1743 if (HandleType[Index] & EFI_HANDLE_TYPE_DRIVER_BINDING_HANDLE)
1744 Device = FALSE;
1745 if (HandleType[Index] & EFI_HANDLE_TYPE_IMAGE_HANDLE)
1746 Device = FALSE;
1747
1748 if (Device) {
1749 Parent = FALSE;
1750 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1751 if (HandleType[HandleIndex] & EFI_HANDLE_TYPE_PARENT_HANDLE)
1752 Parent = TRUE;
1753 } // for
1754
1755 if (!Parent) {
1756 if (HandleType[Index] & EFI_HANDLE_TYPE_DEVICE_HANDLE) {
1757 Status = refit_call4_wrapper(BS->ConnectController,
1758 AllHandleBuffer[Index],
1759 NULL,
1760 NULL,
1761 TRUE);
1762 }
1763 }
1764 }
1765
1766 MyFreePool (HandleBuffer);
1767 MyFreePool (HandleType);
1768 }
1769
1770 Done:
1771 MyFreePool (AllHandleBuffer);
1772 return Status;
1773 } /* EFI_STATUS ConnectAllDriversToAllControllers() */
1774 #else
1775 static EFI_STATUS ConnectAllDriversToAllControllers(VOID) {
1776 BdsLibConnectAllDriversToAllControllers();
1777 return 0;
1778 }
1779 #endif
1780
1781 // Load all EFI drivers from rEFInd's "drivers" subdirectory and from the
1782 // directories specified by the user in the "scan_driver_dirs" configuration
1783 // file line.
1784 static VOID LoadDrivers(VOID)
1785 {
1786 CHAR16 *Directory, *SelfDirectory;
1787 UINTN i = 0, Length, NumFound = 0;
1788
1789 // load drivers from the subdirectories of rEFInd's home directory specified
1790 // in the DRIVER_DIRS constant.
1791 while ((Directory = FindCommaDelimited(DRIVER_DIRS, i++)) != NULL) {
1792 SelfDirectory = SelfDirPath ? StrDuplicate(SelfDirPath) : NULL;
1793 CleanUpPathNameSlashes(SelfDirectory);
1794 MergeStrings(&SelfDirectory, Directory, L'\\');
1795 NumFound += ScanDriverDir(SelfDirectory);
1796 MyFreePool(Directory);
1797 MyFreePool(SelfDirectory);
1798 }
1799
1800 // Scan additional user-specified driver directories....
1801 i = 0;
1802 while ((Directory = FindCommaDelimited(GlobalConfig.DriverDirs, i++)) != NULL) {
1803 CleanUpPathNameSlashes(Directory);
1804 Length = StrLen(Directory);
1805 if (Length > 0) {
1806 NumFound += ScanDriverDir(Directory);
1807 } // if
1808 MyFreePool(Directory);
1809 } // while
1810
1811 // connect all devices
1812 if (NumFound > 0) {
1813 ConnectAllDriversToAllControllers();
1814 }
1815 } /* static VOID LoadDrivers() */
1816
1817 // Locates boot loaders. NOTE: This assumes that GlobalConfig.LegacyType is set correctly.
1818 static VOID ScanForBootloaders(VOID) {
1819 UINTN i;
1820 CHAR8 s;
1821 BOOLEAN ScanForLegacy = FALSE;
1822
1823 // Determine up-front if we'll be scanning for legacy loaders....
1824 for (i = 0; i < NUM_SCAN_OPTIONS; i++) {
1825 s = GlobalConfig.ScanFor[i];
1826 if ((s == 'c') || (s == 'C') || (s == 'h') || (s == 'H') || (s == 'b') || (s == 'B'))
1827 ScanForLegacy = TRUE;
1828 } // for
1829
1830 // If UEFI & scanning for legacy loaders & deep legacy scan, update NVRAM boot manager list
1831 if ((GlobalConfig.LegacyType == LEGACY_TYPE_UEFI) && ScanForLegacy && GlobalConfig.DeepLegacyScan) {
1832 BdsDeleteAllInvalidLegacyBootOptions();
1833 BdsAddNonExistingLegacyBootOptions();
1834 } // if
1835
1836 // scan for loaders and tools, add them to the menu
1837 for (i = 0; i < NUM_SCAN_OPTIONS; i++) {
1838 switch(GlobalConfig.ScanFor[i]) {
1839 case 'c': case 'C':
1840 ScanLegacyDisc();
1841 break;
1842 case 'h': case 'H':
1843 ScanLegacyInternal();
1844 break;
1845 case 'b': case 'B':
1846 ScanLegacyExternal();
1847 break;
1848 case 'm': case 'M':
1849 ScanUserConfigured(GlobalConfig.ConfigFilename);
1850 break;
1851 case 'e': case 'E':
1852 ScanExternal();
1853 break;
1854 case 'i': case 'I':
1855 ScanInternal();
1856 break;
1857 case 'o': case 'O':
1858 ScanOptical();
1859 break;
1860 case 'n': case 'N':
1861 ScanNetboot();
1862 break;
1863 } // switch()
1864 } // for
1865
1866 // assign shortcut keys
1867 for (i = 0; i < MainMenu.EntryCount && MainMenu.Entries[i]->Row == 0 && i < 9; i++)
1868 MainMenu.Entries[i]->ShortcutDigit = (CHAR16)('1' + i);
1869
1870 // wait for user ACK when there were errors
1871 FinishTextScreen(FALSE);
1872 } // static VOID ScanForBootloaders()
1873
1874 // Locate a single tool from the specified Locations using one of the
1875 // specified Names and add it to the menu.
1876 static VOID FindTool(CHAR16 *Locations, CHAR16 *Names, CHAR16 *Description, UINTN Icon) {
1877 UINTN j = 0, k, VolumeIndex;
1878 CHAR16 *DirName, *FileName, *PathName, FullDescription[256];
1879
1880 while ((DirName = FindCommaDelimited(Locations, j++)) != NULL) {
1881 k = 0;
1882 while ((FileName = FindCommaDelimited(Names, k++)) != NULL) {
1883 PathName = StrDuplicate(DirName);
1884 MergeStrings(&PathName, FileName, MyStriCmp(PathName, L"\\") ? 0 : L'\\');
1885 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1886 if ((Volumes[VolumeIndex]->RootDir != NULL) &&
1887 (FileExists(Volumes[VolumeIndex]->RootDir, PathName)) &&
1888 IsValidLoader(Volumes[VolumeIndex]->RootDir, PathName)) {
1889 SPrint(FullDescription, 255, L"%s at %s on %s", Description, PathName, Volumes[VolumeIndex]->VolName);
1890 AddToolEntry(Volumes[VolumeIndex]->DeviceHandle, PathName, FullDescription, BuiltinIcon(Icon), 'S', FALSE);
1891 } // if
1892 } // for
1893 MyFreePool(PathName);
1894 MyFreePool(FileName);
1895 } // while Names
1896 MyFreePool(DirName);
1897 } // while Locations
1898 } // VOID FindTool()
1899
1900 // Add the second-row tags containing built-in and external tools (EFI shell,
1901 // reboot, etc.)
1902 static VOID ScanForTools(VOID) {
1903 CHAR16 *FileName = NULL, *VolName = NULL, *MokLocations, Description[256];
1904 REFIT_MENU_ENTRY *TempMenuEntry;
1905 UINTN i, j, VolumeIndex;
1906 UINT64 osind;
1907 CHAR8 *b = 0;
1908
1909 MokLocations = StrDuplicate(MOK_LOCATIONS);
1910 if (MokLocations != NULL)
1911 MergeStrings(&MokLocations, SelfDirPath, L',');
1912
1913 for (i = 0; i < NUM_TOOLS; i++) {
1914 switch(GlobalConfig.ShowTools[i]) {
1915 // NOTE: Be sure that FileName is NULL at the end of each case.
1916 case TAG_SHUTDOWN:
1917 TempMenuEntry = CopyMenuEntry(&MenuEntryShutdown);
1918 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_SHUTDOWN);
1919 AddMenuEntry(&MainMenu, TempMenuEntry);
1920 break;
1921
1922 case TAG_REBOOT:
1923 TempMenuEntry = CopyMenuEntry(&MenuEntryReset);
1924 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_RESET);
1925 AddMenuEntry(&MainMenu, TempMenuEntry);
1926 break;
1927
1928 case TAG_ABOUT:
1929 TempMenuEntry = CopyMenuEntry(&MenuEntryAbout);
1930 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_ABOUT);
1931 AddMenuEntry(&MainMenu, TempMenuEntry);
1932 break;
1933
1934 case TAG_EXIT:
1935 TempMenuEntry = CopyMenuEntry(&MenuEntryExit);
1936 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_EXIT);
1937 AddMenuEntry(&MainMenu, TempMenuEntry);
1938 break;
1939
1940 case TAG_FIRMWARE:
1941 if (EfivarGetRaw(&GlobalGuid, L"OsIndicationsSupported", &b, &j) == EFI_SUCCESS) {
1942 osind = (UINT64)*b;
1943 if (osind & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) {
1944 TempMenuEntry = CopyMenuEntry(&MenuEntryFirmware);
1945 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_FIRMWARE);
1946 AddMenuEntry(&MainMenu, TempMenuEntry);
1947 } // if
1948 } // if
1949 break;
1950
1951 case TAG_SHELL:
1952 j = 0;
1953 while ((FileName = FindCommaDelimited(SHELL_NAMES, j++)) != NULL) {
1954 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1955 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"EFI Shell", BuiltinIcon(BUILTIN_ICON_TOOL_SHELL),
1956 'S', FALSE);
1957 }
1958 MyFreePool(FileName);
1959 } // while
1960 break;
1961
1962 case TAG_GPTSYNC:
1963 j = 0;
1964 while ((FileName = FindCommaDelimited(GPTSYNC_NAMES, j++)) != NULL) {
1965 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1966 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"Hybrid MBR tool", BuiltinIcon(BUILTIN_ICON_TOOL_PART),
1967 'P', FALSE);
1968 } // if
1969 MyFreePool(FileName);
1970 } // while
1971 FileName = NULL;
1972 break;
1973
1974 case TAG_GDISK:
1975 j = 0;
1976 while ((FileName = FindCommaDelimited(GDISK_NAMES, j++)) != NULL) {
1977 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1978 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"disk partitioning tool",
1979 BuiltinIcon(BUILTIN_ICON_TOOL_PART), 'G', FALSE);
1980 } // if
1981 MyFreePool(FileName);
1982 } // while
1983 FileName = NULL;
1984 break;
1985
1986 case TAG_NETBOOT:
1987 j = 0;
1988 while ((FileName = FindCommaDelimited(NETBOOT_NAMES, j++)) != NULL) {
1989 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1990 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"Netboot",
1991 BuiltinIcon(BUILTIN_ICON_TOOL_NETBOOT), 'N', FALSE);
1992 } // if
1993 MyFreePool(FileName);
1994 } // while
1995 FileName = NULL;
1996 break;
1997
1998 case TAG_APPLE_RECOVERY:
1999 FileName = StrDuplicate(L"\\com.apple.recovery.boot\\boot.efi");
2000 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
2001 if ((Volumes[VolumeIndex]->RootDir != NULL) &&
2002 (FileExists(Volumes[VolumeIndex]->RootDir, FileName)) &&
2003 IsValidLoader(Volumes[VolumeIndex]->RootDir, FileName)) {
2004 SPrint(Description, 255, L"Apple Recovery on %s", Volumes[VolumeIndex]->VolName);
2005 AddToolEntry(Volumes[VolumeIndex]->DeviceHandle, FileName, Description,
2006 BuiltinIcon(BUILTIN_ICON_TOOL_APPLE_RESCUE), 'R', TRUE);
2007 } // if
2008 } // for
2009 MyFreePool(FileName);
2010 FileName = NULL;
2011 break;
2012
2013 case TAG_WINDOWS_RECOVERY:
2014 j = 0;
2015 while ((FileName = FindCommaDelimited(GlobalConfig.WindowsRecoveryFiles, j++)) != NULL) {
2016 SplitVolumeAndFilename(&FileName, &VolName);
2017 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
2018 if ((Volumes[VolumeIndex]->RootDir != NULL) &&
2019 (FileExists(Volumes[VolumeIndex]->RootDir, FileName)) &&
2020 IsValidLoader(Volumes[VolumeIndex]->RootDir, FileName) &&
2021 ((VolName == NULL) || MyStriCmp(VolName, Volumes[VolumeIndex]->VolName))) {
2022 SPrint(Description, 255, L"Microsoft Recovery on %s", Volumes[VolumeIndex]->VolName);
2023 AddToolEntry(Volumes[VolumeIndex]->DeviceHandle, FileName, Description,
2024 BuiltinIcon(BUILTIN_ICON_TOOL_WINDOWS_RESCUE), 'R', TRUE);
2025 } // if
2026 } // for
2027 } // while
2028 MyFreePool(FileName);
2029 FileName = NULL;
2030 MyFreePool(VolName);
2031 VolName = NULL;
2032 break;
2033
2034 case TAG_MOK_TOOL:
2035 FindTool(MokLocations, MOK_NAMES, L"MOK utility", BUILTIN_ICON_TOOL_MOK_TOOL);
2036 break;
2037
2038 case TAG_MEMTEST:
2039 FindTool(MEMTEST_LOCATIONS, MEMTEST_NAMES, L"Memory test utility", BUILTIN_ICON_TOOL_MEMTEST);
2040 break;
2041
2042 } // switch()
2043 } // for
2044 } // static VOID ScanForTools
2045
2046 // Rescan for boot loaders
2047 static VOID RescanAll(BOOLEAN DisplayMessage) {
2048 EG_PIXEL BGColor;
2049
2050 BGColor.b = 255;
2051 BGColor.g = 175;
2052 BGColor.r = 100;
2053 BGColor.a = 0;
2054 if (DisplayMessage)
2055 egDisplayMessage(L"Scanning for new boot loaders; please wait....", &BGColor);
2056 FreeList((VOID ***) &(MainMenu.Entries), &MainMenu.EntryCount);
2057 MainMenu.Entries = NULL;
2058 MainMenu.EntryCount = 0;
2059 ReadConfig(GlobalConfig.ConfigFilename);
2060 ConnectAllDriversToAllControllers();
2061 ScanVolumes();
2062 ScanForBootloaders();
2063 ScanForTools();
2064 SetupScreen();
2065 } // VOID RescanAll()
2066
2067 #ifdef __MAKEWITH_TIANO
2068
2069 // Minimal initialization function
2070 static VOID InitializeLib(IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable) {
2071 gST = SystemTable;
2072 // gImageHandle = ImageHandle;
2073 gBS = SystemTable->BootServices;
2074 // gRS = SystemTable->RuntimeServices;
2075 gRT = SystemTable->RuntimeServices; // Some BDS functions need gRT to be set
2076 EfiGetSystemConfigurationTable (&gEfiDxeServicesTableGuid, (VOID **) &gDS);
2077 }
2078
2079 #endif
2080
2081 // Set up our own Secure Boot extensions....
2082 // Returns TRUE on success, FALSE otherwise
2083 static BOOLEAN SecureBootSetup(VOID) {
2084 EFI_STATUS Status;
2085 BOOLEAN Success = FALSE;
2086
2087 if (secure_mode() && ShimLoaded()) {
2088 Status = security_policy_install();
2089 if (Status == EFI_SUCCESS) {
2090 Success = TRUE;
2091 } else {
2092 Print(L"Failed to install MOK Secure Boot extensions");
2093 PauseForKey();
2094 }
2095 }
2096 return Success;
2097 } // VOID SecureBootSetup()
2098
2099 // Remove our own Secure Boot extensions....
2100 // Returns TRUE on success, FALSE otherwise
2101 static BOOLEAN SecureBootUninstall(VOID) {
2102 EFI_STATUS Status;
2103 BOOLEAN Success = TRUE;
2104
2105 if (secure_mode()) {
2106 Status = security_policy_uninstall();
2107 if (Status != EFI_SUCCESS) {
2108 Success = FALSE;
2109 BeginTextScreen(L"Secure Boot Policy Failure");
2110 Print(L"Failed to uninstall MOK Secure Boot extensions; forcing a reboot.");
2111 PauseForKey();
2112 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
2113 }
2114 }
2115 return Success;
2116 } // VOID SecureBootUninstall
2117
2118 // Sets the global configuration filename; will be CONFIG_FILE_NAME unless the
2119 // "-c" command-line option is set, in which case that takes precedence.
2120 // If an error is encountered, leaves the value alone (it should be set to
2121 // CONFIG_FILE_NAME when GlobalConfig is initialized).
2122 static VOID SetConfigFilename(EFI_HANDLE ImageHandle) {
2123 EFI_LOADED_IMAGE *Info;
2124 CHAR16 *Options, *FileName, *SubString;
2125 EFI_STATUS Status;
2126
2127 Status = refit_call3_wrapper(BS->HandleProtocol, ImageHandle, &LoadedImageProtocol, (VOID **) &Info);
2128 if ((Status == EFI_SUCCESS) && (Info->LoadOptionsSize > 0)) {
2129 Options = (CHAR16 *) Info->LoadOptions;
2130 SubString = MyStrStr(Options, L" -c ");
2131 if (SubString) {
2132 FileName = StrDuplicate(&SubString[4]);
2133 if (FileName) {
2134 LimitStringLength(FileName, 256);
2135 }
2136
2137 if (FileExists(SelfDir, FileName)) {
2138 GlobalConfig.ConfigFilename = FileName;
2139 } else {
2140 Print(L"Specified configuration file (%s) doesn't exist; using\n'refind.conf' default\n", FileName);
2141 MyFreePool(FileName);
2142 } // if/else
2143 } // if
2144 } // if
2145 } // VOID SetConfigFilename()
2146
2147
2148 #define EFI_APPLE_SET_OS_PROTOCOL_GUID \
2149 { 0xc5c5da95, 0x7d5c, 0x45e6, \
2150 { 0xb2, 0xf1, 0x3f, 0xd5, 0x2b, 0xb1, 0x00, 0x77 } \
2151 }
2152
2153 typedef struct EfiAppleSetOsInterface {
2154 UINT64 Version;
2155 EFI_STATUS EFIAPI (*SetOsVersion) (IN CHAR8 *Version);
2156 EFI_STATUS EFIAPI (*SetOsVendor) (IN CHAR8 *Vendor);
2157 } EfiAppleSetOsInterface;
2158
2159 // Function to tell the firmware that OS X is being launched. This is
2160 // required to work around problems on some Macs that don't fully
2161 // initialize some hardware (especially video displays) when third-party
2162 // OSes are launched in EFI mode.
2163 static EFI_STATUS SetAppleOSInfo() {
2164 CHAR16 *AppleOSVersion = NULL;
2165 CHAR8 *AppleOSVersion8 = NULL;
2166 EFI_STATUS Status;
2167 EFI_GUID apple_set_os_guid = EFI_APPLE_SET_OS_PROTOCOL_GUID;
2168 EfiAppleSetOsInterface *SetOs = NULL;
2169
2170 Status = refit_call3_wrapper(BS->LocateProtocol, &apple_set_os_guid, NULL, (VOID**) &SetOs);
2171
2172 // Not a Mac, so ignore the call....
2173 if ((Status != EFI_SUCCESS) || (!SetOs))
2174 return EFI_SUCCESS;
2175
2176 if ((SetOs->Version != 0) && GlobalConfig.SpoofOSXVersion) {
2177 AppleOSVersion = StrDuplicate(L"Mac OS X");
2178 MergeStrings(&AppleOSVersion, GlobalConfig.SpoofOSXVersion, ' ');
2179 AppleOSVersion8 = AllocateZeroPool((StrLen(AppleOSVersion) + 1) * sizeof(CHAR8));
2180 UnicodeStrToAsciiStr(AppleOSVersion, AppleOSVersion8);
2181 if (AppleOSVersion8) {
2182 Status = refit_call1_wrapper (SetOs->SetOsVersion, AppleOSVersion8);
2183 if (!EFI_ERROR(Status))
2184 Status = EFI_SUCCESS;
2185 } else {
2186 Status = EFI_OUT_OF_RESOURCES;
2187 Print(L"Out of resources!\n");
2188 }
2189 if ((Status == EFI_SUCCESS) && (SetOs->Version == 2))
2190 Status = refit_call1_wrapper (SetOs->SetOsVendor, "Apple Inc.");
2191 } // if
2192
2193 if (Status != EFI_SUCCESS)
2194 Print(L"Unable to set firmware boot type!\n");
2195
2196 MyFreePool(AppleOSVersion);
2197 MyFreePool(AppleOSVersion8);
2198 return (Status);
2199 } // EFI_STATUS SetAppleOSInfo()
2200
2201 //
2202 // main entry point
2203 //
2204 EFI_STATUS
2205 EFIAPI
2206 efi_main (EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable)
2207 {
2208 EFI_STATUS Status;
2209 BOOLEAN MainLoopRunning = TRUE;
2210 BOOLEAN MokProtocol;
2211 REFIT_MENU_ENTRY *ChosenEntry;
2212 UINTN MenuExit, i;
2213 CHAR16 *SelectionName = NULL;
2214 EG_PIXEL BGColor;
2215
2216 // bootstrap
2217 InitializeLib(ImageHandle, SystemTable);
2218 Status = InitRefitLib(ImageHandle);
2219 if (EFI_ERROR(Status))
2220 return Status;
2221
2222 // read configuration
2223 CopyMem(GlobalConfig.ScanFor, "ieom ", NUM_SCAN_OPTIONS);
2224 FindLegacyBootType();
2225 if (GlobalConfig.LegacyType == LEGACY_TYPE_MAC)
2226 CopyMem(GlobalConfig.ScanFor, "ihebocm ", NUM_SCAN_OPTIONS);
2227 SetConfigFilename(ImageHandle);
2228 ReadConfig(GlobalConfig.ConfigFilename);
2229
2230 if (GlobalConfig.SpoofOSXVersion && GlobalConfig.SpoofOSXVersion[0] != L'\0')
2231 SetAppleOSInfo();
2232
2233 InitScreen();
2234 WarnIfLegacyProblems();
2235 MainMenu.TimeoutSeconds = GlobalConfig.Timeout;
2236
2237 // disable EFI watchdog timer
2238 refit_call4_wrapper(BS->SetWatchdogTimer, 0x0000, 0x0000, 0x0000, NULL);
2239
2240 // further bootstrap (now with config available)
2241 MokProtocol = SecureBootSetup();
2242 LoadDrivers();
2243 ScanVolumes();
2244 ScanForBootloaders();
2245 ScanForTools();
2246 SetupScreen();
2247
2248 if (GlobalConfig.ScanDelay > 0) {
2249 BGColor.b = 255;
2250 BGColor.g = 175;
2251 BGColor.r = 100;
2252 BGColor.a = 0;
2253 if (GlobalConfig.ScanDelay > 1)
2254 egDisplayMessage(L"Pausing before disk scan; please wait....", &BGColor);
2255 for (i = 0; i < GlobalConfig.ScanDelay; i++)
2256 refit_call1_wrapper(BS->Stall, 1000000);
2257 RescanAll(GlobalConfig.ScanDelay > 1);
2258 } // if
2259
2260 if (GlobalConfig.DefaultSelection)
2261 SelectionName = StrDuplicate(GlobalConfig.DefaultSelection);
2262
2263 while (MainLoopRunning) {
2264 MenuExit = RunMainMenu(&MainMenu, &SelectionName, &ChosenEntry);
2265
2266 // The Escape key triggers a re-scan operation....
2267 if (MenuExit == MENU_EXIT_ESCAPE) {
2268 MenuExit = 0;
2269 RescanAll(TRUE);
2270 continue;
2271 }
2272
2273 switch (ChosenEntry->Tag) {
2274
2275 case TAG_REBOOT: // Reboot
2276 TerminateScreen();
2277 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
2278 MainLoopRunning = FALSE; // just in case we get this far
2279 break;
2280
2281 case TAG_SHUTDOWN: // Shut Down
2282 TerminateScreen();
2283 refit_call4_wrapper(RT->ResetSystem, EfiResetShutdown, EFI_SUCCESS, 0, NULL);
2284 MainLoopRunning = FALSE; // just in case we get this far
2285 break;
2286
2287 case TAG_ABOUT: // About rEFInd
2288 AboutrEFInd();
2289 break;
2290
2291 case TAG_LOADER: // Boot OS via .EFI loader
2292 StartLoader((LOADER_ENTRY *)ChosenEntry, SelectionName);
2293 break;
2294
2295 case TAG_LEGACY: // Boot legacy OS
2296 StartLegacy((LEGACY_ENTRY *)ChosenEntry, SelectionName);
2297 break;
2298
2299 case TAG_LEGACY_UEFI: // Boot a legacy OS on a non-Mac
2300 StartLegacyUEFI((LEGACY_ENTRY *)ChosenEntry, SelectionName);
2301 break;
2302
2303 case TAG_TOOL: // Start a EFI tool
2304 StartTool((LOADER_ENTRY *)ChosenEntry);
2305 break;
2306
2307 case TAG_EXIT: // Terminate rEFInd
2308 if ((MokProtocol) && !SecureBootUninstall()) {
2309 MainLoopRunning = FALSE; // just in case we get this far
2310 } else {
2311 BeginTextScreen(L" ");
2312 return EFI_SUCCESS;
2313 }
2314 break;
2315
2316 case TAG_FIRMWARE: // Reboot into firmware's user interface
2317 RebootIntoFirmware();
2318 break;
2319
2320 } // switch()
2321 } // while()
2322
2323 // If we end up here, things have gone wrong. Try to reboot, and if that
2324 // fails, go into an endless loop.
2325 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
2326 EndlessIdleLoop();
2327
2328 return EFI_SUCCESS;
2329 } /* efi_main() */