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