]> code.delx.au - refind/blob - refind/main.c
bdfa6acaa0f1c69b1ba6646a7c866cf87bbdca3a
[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-2017 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, Tab, or F2 for more options; Esc or Backspace 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, FALSE, 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, TAG_FWUPDATE_TOOL,
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 // If more than one initrd file matches the extracted version string, the one
535 // that matches more characters AFTER (actually, from the start of) the version
536 // string is used.
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 CHAR16 *KernelPostNum, *InitrdPostNum;
541 UINTN MaxSharedChars, SharedChars;
542 STRING_LIST *InitrdNames = NULL, *FinalInitrdName = NULL, *CurrentInitrdName = NULL, *MaxSharedInitrd;
543 REFIT_DIR_ITER DirIter;
544 EFI_FILE_INFO *DirEntry;
545
546 FileName = Basename(LoaderPath);
547 KernelVersion = FindNumbers(FileName);
548 Path = FindPath(LoaderPath);
549
550 // Add trailing backslash for root directory; necessary on some systems, but must
551 // NOT be added to all directories, since on other systems, a trailing backslash on
552 // anything but the root directory causes them to flake out!
553 if (StrLen(Path) == 0) {
554 MergeStrings(&Path, L"\\", 0);
555 } // if
556 DirIterOpen(Volume->RootDir, Path, &DirIter);
557 // Now add a trailing backslash if it was NOT added earlier, for consistency in
558 // building the InitrdName later....
559 if ((StrLen(Path) > 0) && (Path[StrLen(Path) - 1] != L'\\'))
560 MergeStrings(&Path, L"\\", 0);
561 while (DirIterNext(&DirIter, 2, L"init*", &DirEntry)) {
562 InitrdVersion = FindNumbers(DirEntry->FileName);
563 if (((KernelVersion != NULL) && (MyStriCmp(InitrdVersion, KernelVersion))) ||
564 ((KernelVersion == NULL) && (InitrdVersion == NULL))) {
565 CurrentInitrdName = AllocateZeroPool(sizeof(STRING_LIST));
566 if (InitrdNames == NULL)
567 InitrdNames = FinalInitrdName = CurrentInitrdName;
568 if (CurrentInitrdName) {
569 CurrentInitrdName->Value = PoolPrint(L"%s%s", Path, DirEntry->FileName);
570 if (CurrentInitrdName != FinalInitrdName) {
571 FinalInitrdName->Next = CurrentInitrdName;
572 FinalInitrdName = CurrentInitrdName;
573 } // if
574 } // if
575 } // if
576 } // while
577 if (InitrdNames) {
578 if (InitrdNames->Next == NULL) {
579 InitrdName = StrDuplicate(InitrdNames -> Value);
580 } else {
581 MaxSharedInitrd = CurrentInitrdName = InitrdNames;
582 MaxSharedChars = 0;
583 while (CurrentInitrdName != NULL) {
584 KernelPostNum = MyStrStr(LoaderPath, KernelVersion);
585 InitrdPostNum = MyStrStr(CurrentInitrdName->Value, KernelVersion);
586 SharedChars = NumCharsInCommon(KernelPostNum, InitrdPostNum);
587 if (SharedChars > MaxSharedChars) {
588 MaxSharedChars = SharedChars;
589 MaxSharedInitrd = CurrentInitrdName;
590 } // if
591 // TODO: Compute number of shared characters & compare with max.
592 CurrentInitrdName = CurrentInitrdName->Next;
593 }
594 if (MaxSharedInitrd)
595 InitrdName = StrDuplicate(MaxSharedInitrd->Value);
596 } // if/else
597 } // if
598 DeleteStringList(InitrdNames);
599
600 // Note: Don't FreePool(FileName), since Basename returns a pointer WITHIN the string it's passed.
601 MyFreePool(KernelVersion);
602 MyFreePool(Path);
603 return (InitrdName);
604 } // static CHAR16 * FindInitrd()
605
606 LOADER_ENTRY * AddPreparedLoaderEntry(LOADER_ENTRY *Entry) {
607 AddMenuEntry(&MainMenu, (REFIT_MENU_ENTRY *)Entry);
608
609 return(Entry);
610 } // LOADER_ENTRY * AddPreparedLoaderEntry()
611
612 // Creates a copy of a menu screen.
613 // Returns a pointer to the copy of the menu screen.
614 static REFIT_MENU_SCREEN* CopyMenuScreen(REFIT_MENU_SCREEN *Entry) {
615 REFIT_MENU_SCREEN *NewEntry;
616 UINTN i;
617
618 NewEntry = AllocateZeroPool(sizeof(REFIT_MENU_SCREEN));
619 if ((Entry != NULL) && (NewEntry != NULL)) {
620 CopyMem(NewEntry, Entry, sizeof(REFIT_MENU_SCREEN));
621 NewEntry->Title = (Entry->Title) ? StrDuplicate(Entry->Title) : NULL;
622 NewEntry->TimeoutText = (Entry->TimeoutText) ? StrDuplicate(Entry->TimeoutText) : NULL;
623 if (Entry->TitleImage != NULL) {
624 NewEntry->TitleImage = AllocatePool(sizeof(EG_IMAGE));
625 if (NewEntry->TitleImage != NULL)
626 CopyMem(NewEntry->TitleImage, Entry->TitleImage, sizeof(EG_IMAGE));
627 } // if
628 NewEntry->InfoLines = (CHAR16**) AllocateZeroPool(Entry->InfoLineCount * (sizeof(CHAR16*)));
629 for (i = 0; i < Entry->InfoLineCount && NewEntry->InfoLines; i++) {
630 NewEntry->InfoLines[i] = (Entry->InfoLines[i]) ? StrDuplicate(Entry->InfoLines[i]) : NULL;
631 } // for
632 NewEntry->Entries = (REFIT_MENU_ENTRY**) AllocateZeroPool(Entry->EntryCount * (sizeof (REFIT_MENU_ENTRY*)));
633 for (i = 0; i < Entry->EntryCount && NewEntry->Entries; i++) {
634 AddMenuEntry(NewEntry, Entry->Entries[i]);
635 } // for
636 NewEntry->Hint1 = (Entry->Hint1) ? StrDuplicate(Entry->Hint1) : NULL;
637 NewEntry->Hint2 = (Entry->Hint2) ? StrDuplicate(Entry->Hint2) : NULL;
638 } // if
639 return (NewEntry);
640 } // static REFIT_MENU_SCREEN* CopyMenuScreen()
641
642 // Creates a copy of a menu entry. Intended to enable moving a stack-based
643 // menu entry (such as the ones for the "reboot" and "exit" functions) to
644 // to the heap. This enables easier deletion of the whole set of menu
645 // entries when re-scanning.
646 // Returns a pointer to the copy of the menu entry.
647 static REFIT_MENU_ENTRY* CopyMenuEntry(REFIT_MENU_ENTRY *Entry) {
648 REFIT_MENU_ENTRY *NewEntry;
649
650 NewEntry = AllocateZeroPool(sizeof(REFIT_MENU_ENTRY));
651 if ((Entry != NULL) && (NewEntry != NULL)) {
652 CopyMem(NewEntry, Entry, sizeof(REFIT_MENU_ENTRY));
653 NewEntry->Title = (Entry->Title) ? StrDuplicate(Entry->Title) : NULL;
654 if (Entry->BadgeImage != NULL) {
655 NewEntry->BadgeImage = AllocatePool(sizeof(EG_IMAGE));
656 if (NewEntry->BadgeImage != NULL)
657 CopyMem(NewEntry->BadgeImage, Entry->BadgeImage, sizeof(EG_IMAGE));
658 }
659 if (Entry->Image != NULL) {
660 NewEntry->Image = AllocatePool(sizeof(EG_IMAGE));
661 if (NewEntry->Image != NULL)
662 CopyMem(NewEntry->Image, Entry->Image, sizeof(EG_IMAGE));
663 }
664 if (Entry->SubScreen != NULL) {
665 NewEntry->SubScreen = CopyMenuScreen(Entry->SubScreen);
666 }
667 } // if
668 return (NewEntry);
669 } // REFIT_MENU_ENTRY* CopyMenuEntry()
670
671 // Creates a new LOADER_ENTRY data structure and populates it with
672 // default values from the specified Entry, or NULL values if Entry
673 // is unspecified (NULL).
674 // Returns a pointer to the new data structure, or NULL if it
675 // couldn't be allocated
676 LOADER_ENTRY *InitializeLoaderEntry(IN LOADER_ENTRY *Entry) {
677 LOADER_ENTRY *NewEntry = NULL;
678
679 NewEntry = AllocateZeroPool(sizeof(LOADER_ENTRY));
680 if (NewEntry != NULL) {
681 NewEntry->me.Title = NULL;
682 NewEntry->me.Tag = TAG_LOADER;
683 NewEntry->Enabled = TRUE;
684 NewEntry->UseGraphicsMode = FALSE;
685 NewEntry->OSType = 0;
686 if (Entry != NULL) {
687 NewEntry->LoaderPath = (Entry->LoaderPath) ? StrDuplicate(Entry->LoaderPath) : NULL;
688 NewEntry->VolName = (Entry->VolName) ? StrDuplicate(Entry->VolName) : NULL;
689 NewEntry->DevicePath = Entry->DevicePath;
690 NewEntry->UseGraphicsMode = Entry->UseGraphicsMode;
691 NewEntry->LoadOptions = (Entry->LoadOptions) ? StrDuplicate(Entry->LoadOptions) : NULL;
692 NewEntry->InitrdPath = (Entry->InitrdPath) ? StrDuplicate(Entry->InitrdPath) : NULL;
693 }
694 } // if
695 return (NewEntry);
696 } // LOADER_ENTRY *InitializeLoaderEntry()
697
698 // Adds InitrdPath to Options, but only if Options doesn't already include an
699 // initrd= line. Done to enable overriding the default initrd selection in a
700 // refind_linux.conf file's options list.
701 // Returns a pointer to a new string. The calling function is responsible for
702 // freeing its memory.
703 static CHAR16 *AddInitrdToOptions(CHAR16 *Options, CHAR16 *InitrdPath) {
704 CHAR16 *NewOptions = NULL;
705
706 if (Options != NULL)
707 NewOptions = StrDuplicate(Options);
708 if ((InitrdPath != NULL) && !StriSubCmp(L"initrd=", Options)) {
709 MergeStrings(&NewOptions, L"initrd=", L' ');
710 MergeStrings(&NewOptions, InitrdPath, 0);
711 }
712 return NewOptions;
713 } // CHAR16 *AddInitrdToOptions()
714
715 // Prepare a REFIT_MENU_SCREEN data structure for a subscreen entry. This sets up
716 // the default entry that launches the boot loader using the same options as the
717 // main Entry does. Subsequent options can be added by the calling function.
718 // If a subscreen already exists in the Entry that's passed to this function,
719 // it's left unchanged and a pointer to it is returned.
720 // Returns a pointer to the new subscreen data structure, or NULL if there
721 // were problems allocating memory.
722 REFIT_MENU_SCREEN *InitializeSubScreen(IN LOADER_ENTRY *Entry) {
723 CHAR16 *FileName, *MainOptions = NULL;
724 REFIT_MENU_SCREEN *SubScreen = NULL;
725 LOADER_ENTRY *SubEntry;
726
727 FileName = Basename(Entry->LoaderPath);
728 if (Entry->me.SubScreen == NULL) { // No subscreen yet; initialize default entry....
729 SubScreen = AllocateZeroPool(sizeof(REFIT_MENU_SCREEN));
730 if (SubScreen != NULL) {
731 SubScreen->Title = AllocateZeroPool(sizeof(CHAR16) * 256);
732 SPrint(SubScreen->Title, 255, L"Boot Options for %s on %s",
733 (Entry->Title != NULL) ? Entry->Title : FileName, Entry->VolName);
734 SubScreen->TitleImage = Entry->me.Image;
735 // default entry
736 SubEntry = InitializeLoaderEntry(Entry);
737 if (SubEntry != NULL) {
738 SubEntry->me.Title = StrDuplicate(L"Boot using default options");
739 MainOptions = SubEntry->LoadOptions;
740 SubEntry->LoadOptions = AddInitrdToOptions(MainOptions, SubEntry->InitrdPath);
741 MyFreePool(MainOptions);
742 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
743 } // if (SubEntry != NULL)
744 SubScreen->Hint1 = StrDuplicate(SUBSCREEN_HINT1);
745 if (GlobalConfig.HideUIFlags & HIDEUI_FLAG_EDITOR) {
746 SubScreen->Hint2 = StrDuplicate(SUBSCREEN_HINT2_NO_EDITOR);
747 } else {
748 SubScreen->Hint2 = StrDuplicate(SUBSCREEN_HINT2);
749 } // if/else
750 } // if (SubScreen != NULL)
751 } else { // existing subscreen; less initialization, and just add new entry later....
752 SubScreen = Entry->me.SubScreen;
753 } // if/else
754 return SubScreen;
755 } // REFIT_MENU_SCREEN *InitializeSubScreen()
756
757 VOID GenerateSubScreen(LOADER_ENTRY *Entry, IN REFIT_VOLUME *Volume, IN BOOLEAN GenerateReturn) {
758 REFIT_MENU_SCREEN *SubScreen;
759 LOADER_ENTRY *SubEntry;
760 CHAR16 *InitrdName;
761 CHAR16 DiagsFileName[256];
762 REFIT_FILE *File;
763 UINTN TokenCount;
764 CHAR16 **TokenList;
765
766 // create the submenu
767 if (StrLen(Entry->Title) == 0) {
768 MyFreePool(Entry->Title);
769 Entry->Title = NULL;
770 }
771 SubScreen = InitializeSubScreen(Entry);
772
773 // loader-specific submenu entries
774 if (Entry->OSType == 'M') { // entries for Mac OS X
775 #if defined(EFIX64)
776 SubEntry = InitializeLoaderEntry(Entry);
777 if (SubEntry != NULL) {
778 SubEntry->me.Title = L"Boot Mac OS X with a 64-bit kernel";
779 SubEntry->LoadOptions = L"arch=x86_64";
780 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_OSX;
781 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
782 } // if
783
784 SubEntry = InitializeLoaderEntry(Entry);
785 if (SubEntry != NULL) {
786 SubEntry->me.Title = L"Boot Mac OS X with a 32-bit kernel";
787 SubEntry->LoadOptions = L"arch=i386";
788 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_OSX;
789 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
790 } // if
791 #endif
792
793 if (!(GlobalConfig.HideUIFlags & HIDEUI_FLAG_SINGLEUSER)) {
794 SubEntry = InitializeLoaderEntry(Entry);
795 if (SubEntry != NULL) {
796 SubEntry->me.Title = L"Boot Mac OS X in verbose mode";
797 SubEntry->UseGraphicsMode = FALSE;
798 SubEntry->LoadOptions = L"-v";
799 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
800 } // if
801
802 #if defined(EFIX64)
803 SubEntry = InitializeLoaderEntry(Entry);
804 if (SubEntry != NULL) {
805 SubEntry->me.Title = L"Boot Mac OS X in verbose mode (64-bit)";
806 SubEntry->UseGraphicsMode = FALSE;
807 SubEntry->LoadOptions = L"-v arch=x86_64";
808 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
809 }
810
811 SubEntry = InitializeLoaderEntry(Entry);
812 if (SubEntry != NULL) {
813 SubEntry->me.Title = L"Boot Mac OS X in verbose mode (32-bit)";
814 SubEntry->UseGraphicsMode = FALSE;
815 SubEntry->LoadOptions = L"-v arch=i386";
816 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
817 }
818 #endif
819
820 SubEntry = InitializeLoaderEntry(Entry);
821 if (SubEntry != NULL) {
822 SubEntry->me.Title = L"Boot Mac OS X in single user mode";
823 SubEntry->UseGraphicsMode = FALSE;
824 SubEntry->LoadOptions = L"-v -s";
825 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
826 } // if
827 } // single-user mode allowed
828
829 if (!(GlobalConfig.HideUIFlags & HIDEUI_FLAG_SAFEMODE)) {
830 SubEntry = InitializeLoaderEntry(Entry);
831 if (SubEntry != NULL) {
832 SubEntry->me.Title = L"Boot Mac OS X in safe mode";
833 SubEntry->UseGraphicsMode = FALSE;
834 SubEntry->LoadOptions = L"-v -x";
835 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
836 } // if
837 } // safe mode allowed
838
839 // check for Apple hardware diagnostics
840 StrCpy(DiagsFileName, L"System\\Library\\CoreServices\\.diagnostics\\diags.efi");
841 if (FileExists(Volume->RootDir, DiagsFileName) && !(GlobalConfig.HideUIFlags & HIDEUI_FLAG_HWTEST)) {
842 SubEntry = InitializeLoaderEntry(Entry);
843 if (SubEntry != NULL) {
844 SubEntry->me.Title = L"Run Apple Hardware Test";
845 MyFreePool(SubEntry->LoaderPath);
846 SubEntry->LoaderPath = StrDuplicate(DiagsFileName);
847 SubEntry->DevicePath = FileDevicePath(Volume->DeviceHandle, SubEntry->LoaderPath);
848 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_OSX;
849 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
850 } // if
851 } // if diagnostics entry found
852
853 } else if (Entry->OSType == 'L') { // entries for Linux kernels with EFI stub loaders
854 File = ReadLinuxOptionsFile(Entry->LoaderPath, Volume);
855 if (File != NULL) {
856 InitrdName = FindInitrd(Entry->LoaderPath, Volume);
857 TokenCount = ReadTokenLine(File, &TokenList);
858 // first entry requires special processing, since it was initially set
859 // up with a default title but correct options by InitializeSubScreen(),
860 // earlier....
861 if ((TokenCount > 1) && (SubScreen->Entries != NULL) && (SubScreen->Entries[0] != NULL)) {
862 MyFreePool(SubScreen->Entries[0]->Title);
863 SubScreen->Entries[0]->Title = TokenList[0] ? StrDuplicate(TokenList[0]) : StrDuplicate(L"Boot Linux");
864 } // if
865 FreeTokenLine(&TokenList, &TokenCount);
866 while ((TokenCount = ReadTokenLine(File, &TokenList)) > 1) {
867 SubEntry = InitializeLoaderEntry(Entry);
868 SubEntry->me.Title = TokenList[0] ? StrDuplicate(TokenList[0]) : StrDuplicate(L"Boot Linux");
869 MyFreePool(SubEntry->LoadOptions);
870 SubEntry->LoadOptions = AddInitrdToOptions(TokenList[1], InitrdName);
871 FreeTokenLine(&TokenList, &TokenCount);
872 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_LINUX;
873 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
874 } // while
875 MyFreePool(InitrdName);
876 MyFreePool(File);
877 } // if
878
879 } else if (Entry->OSType == 'E') { // entries for ELILO
880 SubEntry = InitializeLoaderEntry(Entry);
881 if (SubEntry != NULL) {
882 SubEntry->me.Title = L"Run ELILO in interactive mode";
883 SubEntry->LoadOptions = L"-p";
884 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
885 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
886 }
887
888 SubEntry = InitializeLoaderEntry(Entry);
889 if (SubEntry != NULL) {
890 SubEntry->me.Title = L"Boot Linux for a 17\" iMac or a 15\" MacBook Pro (*)";
891 SubEntry->LoadOptions = L"-d 0 i17";
892 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
893 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
894 }
895
896 SubEntry = InitializeLoaderEntry(Entry);
897 if (SubEntry != NULL) {
898 SubEntry->me.Title = L"Boot Linux for a 20\" iMac (*)";
899 SubEntry->LoadOptions = L"-d 0 i20";
900 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
901 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
902 }
903
904 SubEntry = InitializeLoaderEntry(Entry);
905 if (SubEntry != NULL) {
906 SubEntry->me.Title = L"Boot Linux for a Mac Mini (*)";
907 SubEntry->LoadOptions = L"-d 0 mini";
908 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
909 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
910 }
911
912 AddMenuInfoLine(SubScreen, L"NOTE: This is an example. Entries");
913 AddMenuInfoLine(SubScreen, L"marked with (*) may not work.");
914
915 } else if (Entry->OSType == 'X') { // entries for xom.efi
916 // by default, skip the built-in selection and boot from hard disk only
917 Entry->LoadOptions = L"-s -h";
918
919 SubEntry = InitializeLoaderEntry(Entry);
920 if (SubEntry != NULL) {
921 SubEntry->me.Title = L"Boot Windows from Hard Disk";
922 SubEntry->LoadOptions = L"-s -h";
923 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
924 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
925 }
926
927 SubEntry = InitializeLoaderEntry(Entry);
928 if (SubEntry != NULL) {
929 SubEntry->me.Title = L"Boot Windows from CD-ROM";
930 SubEntry->LoadOptions = L"-s -c";
931 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
932 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
933 }
934
935 SubEntry = InitializeLoaderEntry(Entry);
936 if (SubEntry != NULL) {
937 SubEntry->me.Title = L"Run XOM in text mode";
938 SubEntry->LoadOptions = L"-v";
939 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
940 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
941 }
942 } // entries for xom.efi
943 if (GenerateReturn)
944 AddMenuEntry(SubScreen, &MenuEntryReturn);
945 Entry->me.SubScreen = SubScreen;
946 } // VOID GenerateSubScreen()
947
948 // Returns options for a Linux kernel. Reads them from an options file in the
949 // kernel's directory; and if present, adds an initrd= option for an initial
950 // RAM disk file with the same version number as the kernel file.
951 static CHAR16 * GetMainLinuxOptions(IN CHAR16 * LoaderPath, IN REFIT_VOLUME *Volume) {
952 CHAR16 *Options = NULL, *InitrdName, *FullOptions = NULL;
953
954 Options = GetFirstOptionsFromFile(LoaderPath, Volume);
955 InitrdName = FindInitrd(LoaderPath, Volume);
956 FullOptions = AddInitrdToOptions(Options, InitrdName);
957
958 MyFreePool(Options);
959 MyFreePool(InitrdName);
960 return (FullOptions);
961 } // static CHAR16 * GetMainLinuxOptions()
962
963 // Read the specified file and add values of "ID", "NAME", or "DISTRIB_ID" tokens to
964 // OSIconName list. Intended for adding Linux distribution clues gleaned from
965 // /etc/lsb-release and /etc/os-release files.
966 static VOID ParseReleaseFile(CHAR16 **OSIconName, REFIT_VOLUME *Volume, CHAR16 *FileName) {
967 UINTN FileSize = 0;
968 REFIT_FILE File;
969 CHAR16 **TokenList;
970 UINTN TokenCount = 0;
971
972 if ((Volume == NULL) || (FileName == NULL) || (OSIconName == NULL) || (*OSIconName == NULL))
973 return;
974
975 if (FileExists(Volume->RootDir, FileName) &&
976 (ReadFile(Volume->RootDir, FileName, &File, &FileSize) == EFI_SUCCESS)) {
977 do {
978 TokenCount = ReadTokenLine(&File, &TokenList);
979 if ((TokenCount > 1) && (MyStriCmp(TokenList[0], L"ID") ||
980 MyStriCmp(TokenList[0], L"NAME") ||
981 MyStriCmp(TokenList[0], L"DISTRIB_ID"))) {
982 MergeWords(OSIconName, TokenList[1], L',');
983 } // if
984 FreeTokenLine(&TokenList, &TokenCount);
985 } while (TokenCount > 0);
986 MyFreePool(File.Buffer);
987 } // if
988 } // VOID ParseReleaseFile()
989
990 // Try to guess the name of the Linux distribution & add that name to
991 // OSIconName list.
992 static VOID GuessLinuxDistribution(CHAR16 **OSIconName, REFIT_VOLUME *Volume, CHAR16 *LoaderPath) {
993 // If on Linux root fs, /etc/os-release or /etc/lsb-release file probably has clues....
994 ParseReleaseFile(OSIconName, Volume, L"etc\\lsb-release");
995 ParseReleaseFile(OSIconName, Volume, L"etc\\os-release");
996
997 // Search for clues in the kernel's filename....
998 if (StriSubCmp(L".fc", LoaderPath))
999 MergeStrings(OSIconName, L"fedora", L',');
1000 if (StriSubCmp(L".el", LoaderPath))
1001 MergeStrings(OSIconName, L"redhat", L',');
1002 } // VOID GuessLinuxDistribution()
1003
1004 // Sets a few defaults for a loader entry -- mainly the icon, but also the OS type
1005 // code and shortcut letter. For Linux EFI stub loaders, also sets kernel options
1006 // that will (with luck) work fairly automatically.
1007 VOID SetLoaderDefaults(LOADER_ENTRY *Entry, CHAR16 *LoaderPath, REFIT_VOLUME *Volume) {
1008 CHAR16 *NameClues, *PathOnly, *NoExtension, *OSIconName = NULL, *Temp;
1009 CHAR16 ShortcutLetter = 0;
1010
1011 NameClues = Basename(LoaderPath);
1012 PathOnly = FindPath(LoaderPath);
1013 NoExtension = StripEfiExtension(NameClues);
1014
1015 if (Volume->DiskKind == DISK_KIND_NET) {
1016 MergeStrings(&NameClues, Entry->me.Title, L' ');
1017 } else {
1018 // locate a custom icon for the loader
1019 // Anything found here takes precedence over the "hints" in the OSIconName variable
1020 if (!Entry->me.Image) {
1021 Entry->me.Image = egLoadIconAnyType(Volume->RootDir, PathOnly, NoExtension, GlobalConfig.IconSizes[ICON_SIZE_BIG]);
1022 }
1023 if (!Entry->me.Image) {
1024 Entry->me.Image = egCopyImage(Volume->VolIconImage);
1025 }
1026
1027 // Begin creating icon "hints" by using last part of directory path leading
1028 // to the loader
1029 Temp = FindLastDirName(LoaderPath);
1030 MergeStrings(&OSIconName, Temp, L',');
1031 MyFreePool(Temp);
1032 Temp = NULL;
1033 if (OSIconName != NULL) {
1034 ShortcutLetter = OSIconName[0];
1035 }
1036
1037 // Add every "word" in the volume label, delimited by spaces, dashes (-), or
1038 // underscores (_), to the list of hints to be used in searching for OS
1039 // icons.
1040 MergeWords(&OSIconName, Volume->VolName, L',');
1041 } // if/else network boot
1042
1043 // detect specific loaders
1044 if (StriSubCmp(L"bzImage", NameClues) || StriSubCmp(L"vmlinuz", NameClues) || StriSubCmp(L"kernel", NameClues)) {
1045 if (Volume->DiskKind != DISK_KIND_NET) {
1046 GuessLinuxDistribution(&OSIconName, Volume, LoaderPath);
1047 Entry->LoadOptions = GetMainLinuxOptions(LoaderPath, Volume);
1048 }
1049 MergeStrings(&OSIconName, L"linux", L',');
1050 Entry->OSType = 'L';
1051 if (ShortcutLetter == 0)
1052 ShortcutLetter = 'L';
1053 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_LINUX;
1054 } else if (StriSubCmp(L"refit", LoaderPath)) {
1055 MergeStrings(&OSIconName, L"refit", L',');
1056 Entry->OSType = 'R';
1057 ShortcutLetter = 'R';
1058 } else if (StriSubCmp(L"refind", LoaderPath)) {
1059 MergeStrings(&OSIconName, L"refind", L',');
1060 Entry->OSType = 'R';
1061 ShortcutLetter = 'R';
1062 } else if (MyStriCmp(LoaderPath, MACOSX_LOADER_PATH)) {
1063 MergeStrings(&OSIconName, L"mac", L',');
1064 Entry->OSType = 'M';
1065 ShortcutLetter = 'M';
1066 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_OSX;
1067 } else if (MyStriCmp(NameClues, L"diags.efi")) {
1068 MergeStrings(&OSIconName, L"hwtest", L',');
1069 } else if (MyStriCmp(NameClues, L"e.efi") || MyStriCmp(NameClues, L"elilo.efi") || StriSubCmp(L"elilo", NameClues)) {
1070 MergeStrings(&OSIconName, L"elilo,linux", L',');
1071 Entry->OSType = 'E';
1072 if (ShortcutLetter == 0)
1073 ShortcutLetter = 'L';
1074 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_ELILO;
1075 } else if (StriSubCmp(L"grub", NameClues)) {
1076 MergeStrings(&OSIconName, L"grub,linux", L',');
1077 Entry->OSType = 'G';
1078 ShortcutLetter = 'G';
1079 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_GRUB;
1080 } else if (MyStriCmp(NameClues, L"cdboot.efi") ||
1081 MyStriCmp(NameClues, L"bootmgr.efi") ||
1082 MyStriCmp(NameClues, L"bootmgfw.efi") ||
1083 MyStriCmp(NameClues, L"bkpbootmgfw.efi")) {
1084 MergeStrings(&OSIconName, L"win8", L',');
1085 Entry->OSType = 'W';
1086 ShortcutLetter = 'W';
1087 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
1088 } else if (MyStriCmp(NameClues, L"xom.efi")) {
1089 MergeStrings(&OSIconName, L"xom,win,win8", L',');
1090 Entry->OSType = 'X';
1091 ShortcutLetter = 'W';
1092 Entry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_WINDOWS;
1093 }
1094 else if (StriSubCmp(L"ipxe", NameClues)) {
1095 Entry->OSType = 'N';
1096 ShortcutLetter = 'N';
1097 MergeStrings(&OSIconName, L"network", L',');
1098 }
1099
1100 if ((ShortcutLetter >= 'a') && (ShortcutLetter <= 'z'))
1101 ShortcutLetter = ShortcutLetter - 'a' + 'A'; // convert lowercase to uppercase
1102 Entry->me.ShortcutLetter = ShortcutLetter;
1103 if (Entry->me.Image == NULL)
1104 Entry->me.Image = LoadOSIcon(OSIconName, L"unknown", FALSE);
1105 MyFreePool(PathOnly);
1106 } // VOID SetLoaderDefaults()
1107
1108 // Add a specified EFI boot loader to the list, using automatic settings
1109 // for icons, options, etc.
1110 static LOADER_ENTRY * AddLoaderEntry(IN CHAR16 *LoaderPath, IN CHAR16 *LoaderTitle, IN REFIT_VOLUME *Volume, IN BOOLEAN SubScreenReturn) {
1111 LOADER_ENTRY *Entry;
1112
1113 CleanUpPathNameSlashes(LoaderPath);
1114 Entry = InitializeLoaderEntry(NULL);
1115 if (Entry != NULL) {
1116 Entry->Title = StrDuplicate((LoaderTitle != NULL) ? LoaderTitle : LoaderPath);
1117 Entry->me.Title = AllocateZeroPool(sizeof(CHAR16) * 256);
1118 // Extra space at end of Entry->me.Title enables searching on Volume->VolName even if another volume
1119 // name is identical except for something added to the end (e.g., VolB1 vs. VolB12).
1120 // Note: Volume->VolName will be NULL for network boot programs.
1121 if (Volume->VolName)
1122 SPrint(Entry->me.Title, 255, L"Boot %s from %s ", (LoaderTitle != NULL) ? LoaderTitle : LoaderPath, Volume->VolName);
1123 else
1124 SPrint(Entry->me.Title, 255, L"Boot %s ", (LoaderTitle != NULL) ? LoaderTitle : LoaderPath);
1125 Entry->me.Row = 0;
1126 Entry->me.BadgeImage = Volume->VolBadgeImage;
1127 if ((LoaderPath != NULL) && (LoaderPath[0] != L'\\')) {
1128 Entry->LoaderPath = StrDuplicate(L"\\");
1129 } else {
1130 Entry->LoaderPath = NULL;
1131 }
1132 MergeStrings(&(Entry->LoaderPath), LoaderPath, 0);
1133 Entry->VolName = Volume->VolName;
1134 Entry->DevicePath = FileDevicePath(Volume->DeviceHandle, Entry->LoaderPath);
1135 SetLoaderDefaults(Entry, LoaderPath, Volume);
1136 GenerateSubScreen(Entry, Volume, SubScreenReturn);
1137 AddMenuEntry(&MainMenu, (REFIT_MENU_ENTRY *)Entry);
1138 }
1139
1140 return(Entry);
1141 } // LOADER_ENTRY * AddLoaderEntry()
1142
1143 // Add a Linux kernel as a submenu entry for another (pre-existing) Linux kernel entry.
1144 static VOID AddKernelToSubmenu(LOADER_ENTRY * TargetLoader, CHAR16 *FileName, REFIT_VOLUME *Volume) {
1145 REFIT_FILE *File;
1146 CHAR16 **TokenList = NULL, *InitrdName, *SubmenuName = NULL, *VolName = NULL, *Path = NULL, *Title;
1147 REFIT_MENU_SCREEN *SubScreen;
1148 LOADER_ENTRY *SubEntry;
1149 UINTN TokenCount;
1150
1151 File = ReadLinuxOptionsFile(TargetLoader->LoaderPath, Volume);
1152 if (File != NULL) {
1153 SubScreen = TargetLoader->me.SubScreen;
1154 InitrdName = FindInitrd(FileName, Volume);
1155 while ((TokenCount = ReadTokenLine(File, &TokenList)) > 1) {
1156 SubEntry = InitializeLoaderEntry(TargetLoader);
1157 SplitPathName(FileName, &VolName, &Path, &SubmenuName);
1158 MergeStrings(&SubmenuName, L": ", '\0');
1159 MergeStrings(&SubmenuName, TokenList[0] ? StrDuplicate(TokenList[0]) : StrDuplicate(L"Boot Linux"), '\0');
1160 Title = StrDuplicate(SubmenuName);
1161 LimitStringLength(Title, MAX_LINE_LENGTH);
1162 SubEntry->me.Title = Title;
1163 MyFreePool(SubEntry->LoadOptions);
1164 SubEntry->LoadOptions = AddInitrdToOptions(TokenList[1], InitrdName);
1165 MyFreePool(SubEntry->LoaderPath);
1166 SubEntry->LoaderPath = StrDuplicate(FileName);
1167 CleanUpPathNameSlashes(SubEntry->LoaderPath);
1168 SubEntry->DevicePath = FileDevicePath(Volume->DeviceHandle, SubEntry->LoaderPath);
1169 FreeTokenLine(&TokenList, &TokenCount);
1170 SubEntry->UseGraphicsMode = GlobalConfig.GraphicsFor & GRAPHICS_FOR_LINUX;
1171 AddMenuEntry(SubScreen, (REFIT_MENU_ENTRY *)SubEntry);
1172 } // while
1173 MyFreePool(VolName);
1174 MyFreePool(Path);
1175 MyFreePool(SubmenuName);
1176 MyFreePool(InitrdName);
1177 MyFreePool(File);
1178 } // if
1179 } // static VOID AddKernelToSubmenu()
1180
1181 // Returns -1 if (Time1 < Time2), +1 if (Time1 > Time2), or 0 if
1182 // (Time1 == Time2). Precision is only to the nearest second; since
1183 // this is used for sorting boot loader entries, differences smaller
1184 // than this are likely to be meaningless (and unlikely!).
1185 INTN TimeComp(IN EFI_TIME *Time1, IN EFI_TIME *Time2) {
1186 INT64 Time1InSeconds, Time2InSeconds;
1187
1188 // Following values are overestimates; I'm assuming 31 days in every month.
1189 // This is fine for the purpose of this function, which is limited
1190 Time1InSeconds = Time1->Second + (Time1->Minute * 60) + (Time1->Hour * 3600) + (Time1->Day * 86400) +
1191 (Time1->Month * 2678400) + ((Time1->Year - 1998) * 32140800);
1192 Time2InSeconds = Time2->Second + (Time2->Minute * 60) + (Time2->Hour * 3600) + (Time2->Day * 86400) +
1193 (Time2->Month * 2678400) + ((Time2->Year - 1998) * 32140800);
1194 if (Time1InSeconds < Time2InSeconds)
1195 return (-1);
1196 else if (Time1InSeconds > Time2InSeconds)
1197 return (1);
1198
1199 return 0;
1200 } // INTN TimeComp()
1201
1202 // Adds a loader list element, keeping it sorted by date. EXCEPTION: Fedora's rescue
1203 // kernel, which begins with "vmlinuz-0-rescue," should not be at the top of the list,
1204 // since that will make it the default if kernel folding is enabled, so float it to
1205 // the end.
1206 // Returns the new first element (the one with the most recent date).
1207 static struct LOADER_LIST * AddLoaderListEntry(struct LOADER_LIST *LoaderList, struct LOADER_LIST *NewEntry) {
1208 struct LOADER_LIST *LatestEntry, *CurrentEntry, *PrevEntry = NULL;
1209 BOOLEAN LinuxRescue = FALSE;
1210
1211 LatestEntry = CurrentEntry = LoaderList;
1212 if (LoaderList == NULL) {
1213 LatestEntry = NewEntry;
1214 } else {
1215 if (StriSubCmp(L"vmlinuz-0-rescue", NewEntry->FileName))
1216 LinuxRescue = TRUE;
1217 while ((CurrentEntry != NULL) && (LinuxRescue || (TimeComp(&(NewEntry->TimeStamp), &(CurrentEntry->TimeStamp)) < 0))) {
1218 PrevEntry = CurrentEntry;
1219 CurrentEntry = CurrentEntry->NextEntry;
1220 } // while
1221 NewEntry->NextEntry = CurrentEntry;
1222 if (PrevEntry == NULL) {
1223 LatestEntry = NewEntry;
1224 } else {
1225 PrevEntry->NextEntry = NewEntry;
1226 } // if/else
1227 } // if/else
1228 return (LatestEntry);
1229 } // static VOID AddLoaderListEntry()
1230
1231 // Delete the LOADER_LIST linked list
1232 static VOID CleanUpLoaderList(struct LOADER_LIST *LoaderList) {
1233 struct LOADER_LIST *Temp;
1234
1235 while (LoaderList != NULL) {
1236 Temp = LoaderList;
1237 LoaderList = LoaderList->NextEntry;
1238 MyFreePool(Temp->FileName);
1239 MyFreePool(Temp);
1240 } // while
1241 } // static VOID CleanUpLoaderList()
1242
1243 // Returns FALSE if the specified file/volume matches the GlobalConfig.DontScanDirs
1244 // or GlobalConfig.DontScanVolumes specification, or if Path points to a volume
1245 // other than the one specified by Volume, or if the specified path is SelfDir.
1246 // Returns TRUE if none of these conditions is met -- that is, if the path is
1247 // eligible for scanning.
1248 static BOOLEAN ShouldScan(REFIT_VOLUME *Volume, CHAR16 *Path) {
1249 CHAR16 *VolName = NULL, *DontScanDir, *PathCopy = NULL;
1250 UINTN i = 0;
1251 BOOLEAN ScanIt = TRUE;
1252
1253 if ((IsIn(Volume->VolName, GlobalConfig.DontScanVolumes)) || (IsIn(Volume->PartName, GlobalConfig.DontScanVolumes)))
1254 return FALSE;
1255
1256 if (MyStriCmp(Path, SelfDirPath) && (Volume->DeviceHandle == SelfVolume->DeviceHandle))
1257 return FALSE;
1258
1259 // See if Path includes an explicit volume declaration that's NOT Volume....
1260 PathCopy = StrDuplicate(Path);
1261 if (SplitVolumeAndFilename(&PathCopy, &VolName)) {
1262 VolumeNumberToName(Volume, &VolName);
1263 if (VolName && !MyStriCmp(VolName, Volume->VolName)) {
1264 ScanIt = FALSE;
1265 } // if
1266 } // if Path includes volume specification
1267 MyFreePool(PathCopy);
1268 MyFreePool(VolName);
1269 VolName = NULL;
1270
1271 // See if Volume is in GlobalConfig.DontScanDirs....
1272 while (ScanIt && (DontScanDir = FindCommaDelimited(GlobalConfig.DontScanDirs, i++))) {
1273 SplitVolumeAndFilename(&DontScanDir, &VolName);
1274 CleanUpPathNameSlashes(DontScanDir);
1275 VolumeNumberToName(Volume, &VolName);
1276 if (VolName != NULL) {
1277 if (MyStriCmp(VolName, Volume->VolName) && MyStriCmp(DontScanDir, Path))
1278 ScanIt = FALSE;
1279 } else {
1280 if (MyStriCmp(DontScanDir, Path))
1281 ScanIt = FALSE;
1282 }
1283 MyFreePool(DontScanDir);
1284 MyFreePool(VolName);
1285 DontScanDir = NULL;
1286 VolName = NULL;
1287 } // while()
1288
1289 return ScanIt;
1290 } // BOOLEAN ShouldScan()
1291
1292 // Returns TRUE if the file is byte-for-byte identical with the fallback file
1293 // on the volume AND if the file is not itself the fallback file; returns
1294 // FALSE if the file is not identical to the fallback file OR if the file
1295 // IS the fallback file. Intended for use in excluding the fallback boot
1296 // loader when it's a duplicate of another boot loader.
1297 static BOOLEAN DuplicatesFallback(IN REFIT_VOLUME *Volume, IN CHAR16 *FileName) {
1298 CHAR8 *FileContents, *FallbackContents;
1299 EFI_FILE_HANDLE FileHandle, FallbackHandle;
1300 EFI_FILE_INFO *FileInfo, *FallbackInfo;
1301 UINTN FileSize = 0, FallbackSize = 0;
1302 EFI_STATUS Status;
1303 BOOLEAN AreIdentical = FALSE;
1304
1305 if (!FileExists(Volume->RootDir, FileName) || !FileExists(Volume->RootDir, FALLBACK_FULLNAME))
1306 return FALSE;
1307
1308 CleanUpPathNameSlashes(FileName);
1309
1310 if (MyStriCmp(FileName, FALLBACK_FULLNAME))
1311 return FALSE; // identical filenames, so not a duplicate....
1312
1313 Status = refit_call5_wrapper(Volume->RootDir->Open, Volume->RootDir, &FileHandle, FileName, EFI_FILE_MODE_READ, 0);
1314 if (Status == EFI_SUCCESS) {
1315 FileInfo = LibFileInfo(FileHandle);
1316 FileSize = FileInfo->FileSize;
1317 } else {
1318 return FALSE;
1319 }
1320
1321 Status = refit_call5_wrapper(Volume->RootDir->Open, Volume->RootDir, &FallbackHandle, FALLBACK_FULLNAME, EFI_FILE_MODE_READ, 0);
1322 if (Status == EFI_SUCCESS) {
1323 FallbackInfo = LibFileInfo(FallbackHandle);
1324 FallbackSize = FallbackInfo->FileSize;
1325 } else {
1326 refit_call1_wrapper(FileHandle->Close, FileHandle);
1327 return FALSE;
1328 }
1329
1330 if (FallbackSize == FileSize) { // could be identical; do full check....
1331 FileContents = AllocatePool(FileSize);
1332 FallbackContents = AllocatePool(FallbackSize);
1333 if (FileContents && FallbackContents) {
1334 Status = refit_call3_wrapper(FileHandle->Read, FileHandle, &FileSize, FileContents);
1335 if (Status == EFI_SUCCESS) {
1336 Status = refit_call3_wrapper(FallbackHandle->Read, FallbackHandle, &FallbackSize, FallbackContents);
1337 }
1338 if (Status == EFI_SUCCESS) {
1339 AreIdentical = (CompareMem(FileContents, FallbackContents, FileSize) == 0);
1340 } // if
1341 } // if
1342 MyFreePool(FileContents);
1343 MyFreePool(FallbackContents);
1344 } // if/else
1345
1346 // BUG ALERT: Some systems (e.g., DUET, some Macs with large displays) crash if the
1347 // following two calls are reversed. Go figure....
1348 refit_call1_wrapper(FileHandle->Close, FallbackHandle);
1349 refit_call1_wrapper(FileHandle->Close, FileHandle);
1350 return AreIdentical;
1351 } // BOOLEAN DuplicatesFallback()
1352
1353 // Returns FALSE if two measures of file size are identical for a single file,
1354 // TRUE if not or if the file can't be opened and the other measure is non-0.
1355 // Despite the function's name, this isn't really a direct test of symbolic
1356 // link status, since EFI doesn't officially support symlinks. It does seem
1357 // to be a reliable indicator, though. (OTOH, some disk errors might cause a
1358 // file to fail to open, which would return a false positive -- but as I use
1359 // this function to exclude symbolic links from the list of boot loaders,
1360 // that would be fine, since such boot loaders wouldn't work.)
1361 // CAUTION: *FullName MUST be properly cleaned up (via CleanUpPathNameSlashes())
1362 static BOOLEAN IsSymbolicLink(REFIT_VOLUME *Volume, CHAR16 *FullName, EFI_FILE_INFO *DirEntry) {
1363 EFI_FILE_HANDLE FileHandle;
1364 EFI_FILE_INFO *FileInfo = NULL;
1365 EFI_STATUS Status;
1366 UINTN FileSize2 = 0;
1367
1368 Status = refit_call5_wrapper(Volume->RootDir->Open, Volume->RootDir, &FileHandle, FullName, EFI_FILE_MODE_READ, 0);
1369 if (Status == EFI_SUCCESS) {
1370 FileInfo = LibFileInfo(FileHandle);
1371 if (FileInfo != NULL)
1372 FileSize2 = FileInfo->FileSize;
1373 }
1374
1375 MyFreePool(FileInfo);
1376
1377 return (DirEntry->FileSize != FileSize2);
1378 } // BOOLEAN IsSymbolicLink()
1379
1380 // Returns TRUE if a file with the same name as the original but with
1381 // ".efi.signed" is also present in the same directory. Ubuntu is using
1382 // this filename as a signed version of the original unsigned kernel, and
1383 // there's no point in cluttering the display with two kernels that will
1384 // behave identically on non-SB systems, or when one will fail when SB
1385 // is active.
1386 // CAUTION: *FullName MUST be properly cleaned up (via CleanUpPathNameSlashes())
1387 static BOOLEAN HasSignedCounterpart(IN REFIT_VOLUME *Volume, IN CHAR16 *FullName) {
1388 CHAR16 *NewFile = NULL;
1389 BOOLEAN retval = FALSE;
1390
1391 MergeStrings(&NewFile, FullName, 0);
1392 MergeStrings(&NewFile, L".efi.signed", 0);
1393 if (NewFile != NULL) {
1394 if (FileExists(Volume->RootDir, NewFile))
1395 retval = TRUE;
1396 MyFreePool(NewFile);
1397 } // if
1398
1399 return retval;
1400 } // BOOLEAN HasSignedCounterpart()
1401
1402 // Scan an individual directory for EFI boot loader files and, if found,
1403 // add them to the list. Exception: Ignores FALLBACK_FULLNAME, which is picked
1404 // up in ScanEfiFiles(). Sorts the entries within the loader directory so that
1405 // the most recent one appears first in the list.
1406 // Returns TRUE if a duplicate for FALLBACK_FILENAME was found, FALSE if not.
1407 static BOOLEAN ScanLoaderDir(IN REFIT_VOLUME *Volume, IN CHAR16 *Path, IN CHAR16 *Pattern)
1408 {
1409 EFI_STATUS Status;
1410 REFIT_DIR_ITER DirIter;
1411 EFI_FILE_INFO *DirEntry;
1412 CHAR16 Message[256], *Extension, *FullName;
1413 struct LOADER_LIST *LoaderList = NULL, *NewLoader;
1414 LOADER_ENTRY *FirstKernel = NULL, *LatestEntry = NULL;
1415 BOOLEAN FoundFallbackDuplicate = FALSE, IsLinux = FALSE, InSelfPath;
1416
1417 InSelfPath = MyStriCmp(Path, SelfDirPath);
1418 if ((!SelfDirPath || !Path || (InSelfPath && (Volume->DeviceHandle != SelfVolume->DeviceHandle)) ||
1419 (!InSelfPath)) && (ShouldScan(Volume, Path))) {
1420 // look through contents of the directory
1421 DirIterOpen(Volume->RootDir, Path, &DirIter);
1422 while (DirIterNext(&DirIter, 2, Pattern, &DirEntry)) {
1423 Extension = FindExtension(DirEntry->FileName);
1424 FullName = StrDuplicate(Path);
1425 MergeStrings(&FullName, DirEntry->FileName, L'\\');
1426 CleanUpPathNameSlashes(FullName);
1427 if (DirEntry->FileName[0] == '.' ||
1428 MyStriCmp(Extension, L".icns") ||
1429 MyStriCmp(Extension, L".png") ||
1430 (MyStriCmp(DirEntry->FileName, FALLBACK_BASENAME) && (MyStriCmp(Path, L"EFI\\BOOT"))) ||
1431 FilenameIn(Volume, Path, DirEntry->FileName, SHELL_NAMES) ||
1432 IsSymbolicLink(Volume, FullName, DirEntry) || /* is symbolic link */
1433 HasSignedCounterpart(Volume, FullName) || /* a file with same name plus ".efi.signed" is present */
1434 FilenameIn(Volume, Path, DirEntry->FileName, GlobalConfig.DontScanFiles) ||
1435 !IsValidLoader(Volume->RootDir, FullName)) {
1436 continue; // skip this
1437 }
1438
1439 NewLoader = AllocateZeroPool(sizeof(struct LOADER_LIST));
1440 if (NewLoader != NULL) {
1441 NewLoader->FileName = StrDuplicate(FullName);
1442 NewLoader->TimeStamp = DirEntry->ModificationTime;
1443 LoaderList = AddLoaderListEntry(LoaderList, NewLoader);
1444 if (DuplicatesFallback(Volume, FullName))
1445 FoundFallbackDuplicate = TRUE;
1446 } // if
1447 MyFreePool(Extension);
1448 MyFreePool(FullName);
1449 } // while
1450
1451 NewLoader = LoaderList;
1452 while (NewLoader != NULL) {
1453 IsLinux = (StriSubCmp(L"bzImage", NewLoader->FileName) ||
1454 StriSubCmp(L"vmlinuz", NewLoader->FileName) ||
1455 StriSubCmp(L"kernel", NewLoader->FileName));
1456 if ((FirstKernel != NULL) && IsLinux && GlobalConfig.FoldLinuxKernels) {
1457 AddKernelToSubmenu(FirstKernel, NewLoader->FileName, Volume);
1458 } else {
1459 LatestEntry = AddLoaderEntry(NewLoader->FileName, NULL, Volume, !(IsLinux && GlobalConfig.FoldLinuxKernels));
1460 if (IsLinux && (FirstKernel == NULL))
1461 FirstKernel = LatestEntry;
1462 }
1463 NewLoader = NewLoader->NextEntry;
1464 } // while
1465 if ((NewLoader != NULL) && (FirstKernel != NULL) && IsLinux && GlobalConfig.FoldLinuxKernels)
1466 AddMenuEntry(FirstKernel->me.SubScreen, &MenuEntryReturn);
1467
1468 CleanUpLoaderList(LoaderList);
1469 Status = DirIterClose(&DirIter);
1470 // NOTE: EFI_INVALID_PARAMETER really is an error that should be reported;
1471 // but I've gotten reports from users who are getting this error occasionally
1472 // and I can't find anything wrong or reproduce the problem, so I'm putting
1473 // it down to buggy EFI implementations and ignoring that particular error....
1474 if ((Status != EFI_NOT_FOUND) && (Status != EFI_INVALID_PARAMETER)) {
1475 if (Path)
1476 SPrint(Message, 255, L"while scanning the %s directory", Path);
1477 else
1478 StrCpy(Message, L"while scanning the root directory");
1479 CheckError(Status, Message);
1480 } // if (Status != EFI_NOT_FOUND)
1481 } // if not scanning a blacklisted directory
1482
1483 return FoundFallbackDuplicate;
1484 } /* static VOID ScanLoaderDir() */
1485
1486 // Run the IPXE_DISCOVER_NAME program, which obtains the IP address of the boot
1487 // server and the name of the boot file it delivers.
1488 CHAR16* RuniPXEDiscover(EFI_HANDLE Volume)
1489 {
1490 EFI_STATUS Status;
1491 EFI_DEVICE_PATH *FilePath;
1492 EFI_HANDLE iPXEHandle;
1493 CHAR16 *boot_info = NULL;
1494 UINTN boot_info_size = 0;
1495
1496 FilePath = FileDevicePath (Volume, IPXE_DISCOVER_NAME);
1497 Status = refit_call6_wrapper(BS->LoadImage, FALSE, SelfImageHandle, FilePath, NULL, 0, &iPXEHandle);
1498 if (Status != 0)
1499 return NULL;
1500
1501 Status = refit_call3_wrapper(BS->StartImage, iPXEHandle, &boot_info_size, &boot_info);
1502
1503 return boot_info;
1504 } // RuniPXEDiscover()
1505
1506 // Scan for network (PXE) boot servers. This function relies on the presence
1507 // of the IPXE_DISCOVER_NAME and IPXE_NAME program files on the volume from
1508 // which rEFInd launched. As of December 6, 2014, these tools aren't entirely
1509 // reliable. See BUILDING.txt for information on building them.
1510 static VOID ScanNetboot() {
1511 CHAR16 *iPXEFileName = IPXE_NAME;
1512 CHAR16 *Location;
1513 REFIT_VOLUME *NetVolume;
1514
1515 if (FileExists(SelfVolume->RootDir, IPXE_DISCOVER_NAME) &&
1516 FileExists(SelfVolume->RootDir, IPXE_NAME) &&
1517 IsValidLoader(SelfVolume->RootDir, IPXE_DISCOVER_NAME) &&
1518 IsValidLoader(SelfVolume->RootDir, IPXE_NAME)) {
1519 Location = RuniPXEDiscover(SelfVolume->DeviceHandle);
1520 if (Location != NULL && FileExists(SelfVolume->RootDir, iPXEFileName)) {
1521 NetVolume = AllocatePool(sizeof(REFIT_VOLUME));
1522 CopyMem(NetVolume, SelfVolume, sizeof(REFIT_VOLUME));
1523 NetVolume->DiskKind = DISK_KIND_NET;
1524 NetVolume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_NET);
1525 NetVolume->PartName = NetVolume->VolName = NULL;
1526 AddLoaderEntry(iPXEFileName, Location, NetVolume, TRUE);
1527 MyFreePool(NetVolume);
1528 } // if support files exist and are valid
1529 }
1530 } // VOID ScanNetBoot()
1531
1532 static VOID ScanEfiFiles(REFIT_VOLUME *Volume) {
1533 EFI_STATUS Status;
1534 REFIT_DIR_ITER EfiDirIter;
1535 EFI_FILE_INFO *EfiDirEntry;
1536 CHAR16 FileName[256], *Directory = NULL, *MatchPatterns, *VolName = NULL, *SelfPath;
1537 UINTN i, Length;
1538 BOOLEAN ScanFallbackLoader = TRUE;
1539 BOOLEAN FoundBRBackup = FALSE;
1540
1541 if (Volume && (Volume->RootDir != NULL) && (Volume->VolName != NULL) && (Volume->IsReadable)) {
1542 MatchPatterns = StrDuplicate(LOADER_MATCH_PATTERNS);
1543 if (GlobalConfig.ScanAllLinux)
1544 MergeStrings(&MatchPatterns, LINUX_MATCH_PATTERNS, L',');
1545
1546 // check for Mac OS X boot loader
1547 if (ShouldScan(Volume, MACOSX_LOADER_DIR)) {
1548 StrCpy(FileName, MACOSX_LOADER_PATH);
1549 if (FileExists(Volume->RootDir, FileName) && !FilenameIn(Volume, MACOSX_LOADER_DIR, L"boot.efi", GlobalConfig.DontScanFiles)) {
1550 AddLoaderEntry(FileName, L"Mac OS X", Volume, TRUE);
1551 if (DuplicatesFallback(Volume, FileName))
1552 ScanFallbackLoader = FALSE;
1553 }
1554
1555 // check for XOM
1556 StrCpy(FileName, L"System\\Library\\CoreServices\\xom.efi");
1557 if (FileExists(Volume->RootDir, FileName) && !FilenameIn(Volume, MACOSX_LOADER_DIR, L"xom.efi", GlobalConfig.DontScanFiles)) {
1558 AddLoaderEntry(FileName, L"Windows XP (XoM)", Volume, TRUE);
1559 if (DuplicatesFallback(Volume, FileName))
1560 ScanFallbackLoader = FALSE;
1561 }
1562 } // if should scan Mac directory
1563
1564 // check for Microsoft boot loader/menu
1565 if (ShouldScan(Volume, L"EFI\\Microsoft\\Boot")) {
1566 StrCpy(FileName, L"EFI\\Microsoft\\Boot\\bkpbootmgfw.efi");
1567 if (FileExists(Volume->RootDir, FileName) && !FilenameIn(Volume, L"EFI\\Microsoft\\Boot", L"bkpbootmgfw.efi",
1568 GlobalConfig.DontScanFiles)) {
1569 AddLoaderEntry(FileName, L"Microsoft EFI boot (Boot Repair backup)", Volume, TRUE);
1570 FoundBRBackup = TRUE;
1571 if (DuplicatesFallback(Volume, FileName))
1572 ScanFallbackLoader = FALSE;
1573 }
1574 StrCpy(FileName, L"EFI\\Microsoft\\Boot\\bootmgfw.efi");
1575 if (FileExists(Volume->RootDir, FileName) &&
1576 !FilenameIn(Volume, L"EFI\\Microsoft\\Boot", L"bootmgfw.efi", GlobalConfig.DontScanFiles)) {
1577 if (FoundBRBackup)
1578 AddLoaderEntry(FileName, L"Supposed Microsoft EFI boot (probably GRUB)", Volume, TRUE);
1579 else
1580 AddLoaderEntry(FileName, L"Microsoft EFI boot", Volume, TRUE);
1581 if (DuplicatesFallback(Volume, FileName))
1582 ScanFallbackLoader = FALSE;
1583 }
1584 } // if
1585
1586 // scan the root directory for EFI executables
1587 if (ScanLoaderDir(Volume, L"\\", MatchPatterns))
1588 ScanFallbackLoader = FALSE;
1589
1590 // scan subdirectories of the EFI directory (as per the standard)
1591 DirIterOpen(Volume->RootDir, L"EFI", &EfiDirIter);
1592 while (DirIterNext(&EfiDirIter, 1, NULL, &EfiDirEntry)) {
1593 if (MyStriCmp(EfiDirEntry->FileName, L"tools") || EfiDirEntry->FileName[0] == '.')
1594 continue; // skip this, doesn't contain boot loaders or is scanned later
1595 SPrint(FileName, 255, L"EFI\\%s", EfiDirEntry->FileName);
1596 if (ScanLoaderDir(Volume, FileName, MatchPatterns))
1597 ScanFallbackLoader = FALSE;
1598 } // while()
1599 Status = DirIterClose(&EfiDirIter);
1600 if ((Status != EFI_NOT_FOUND) && (Status != EFI_INVALID_PARAMETER))
1601 CheckError(Status, L"while scanning the EFI directory");
1602
1603 // Scan user-specified (or additional default) directories....
1604 i = 0;
1605 while ((Directory = FindCommaDelimited(GlobalConfig.AlsoScan, i++)) != NULL) {
1606 if (ShouldScan(Volume, Directory)) {
1607 SplitVolumeAndFilename(&Directory, &VolName);
1608 CleanUpPathNameSlashes(Directory);
1609 Length = StrLen(Directory);
1610 if ((Length > 0) && ScanLoaderDir(Volume, Directory, MatchPatterns))
1611 ScanFallbackLoader = FALSE;
1612 MyFreePool(VolName);
1613 } // if should scan dir
1614 MyFreePool(Directory);
1615 } // while
1616
1617 // Don't scan the fallback loader if it's on the same volume and a duplicate of rEFInd itself....
1618 SelfPath = DevicePathToStr(SelfLoadedImage->FilePath);
1619 CleanUpPathNameSlashes(SelfPath);
1620 if ((Volume->DeviceHandle == SelfLoadedImage->DeviceHandle) && DuplicatesFallback(Volume, SelfPath))
1621 ScanFallbackLoader = FALSE;
1622
1623 // If not a duplicate & if it exists & if it's not us, create an entry
1624 // for the fallback boot loader
1625 if (ScanFallbackLoader && FileExists(Volume->RootDir, FALLBACK_FULLNAME) && ShouldScan(Volume, L"EFI\\BOOT")) {
1626 AddLoaderEntry(FALLBACK_FULLNAME, L"Fallback boot loader", Volume, TRUE);
1627 }
1628 } // if
1629 } // static VOID ScanEfiFiles()
1630
1631 // Scan internal disks for valid EFI boot loaders....
1632 static VOID ScanInternal(VOID) {
1633 UINTN VolumeIndex;
1634
1635 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1636 if (Volumes[VolumeIndex]->DiskKind == DISK_KIND_INTERNAL) {
1637 ScanEfiFiles(Volumes[VolumeIndex]);
1638 }
1639 } // for
1640 } // static VOID ScanInternal()
1641
1642 // Scan external disks for valid EFI boot loaders....
1643 static VOID ScanExternal(VOID) {
1644 UINTN VolumeIndex;
1645
1646 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1647 if (Volumes[VolumeIndex]->DiskKind == DISK_KIND_EXTERNAL) {
1648 ScanEfiFiles(Volumes[VolumeIndex]);
1649 }
1650 } // for
1651 } // static VOID ScanExternal()
1652
1653 // Scan internal disks for valid EFI boot loaders....
1654 static VOID ScanOptical(VOID) {
1655 UINTN VolumeIndex;
1656
1657 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1658 if (Volumes[VolumeIndex]->DiskKind == DISK_KIND_OPTICAL) {
1659 ScanEfiFiles(Volumes[VolumeIndex]);
1660 }
1661 } // for
1662 } // static VOID ScanOptical()
1663
1664 // default volume badge icon based on disk kind
1665 EG_IMAGE * GetDiskBadge(IN UINTN DiskType) {
1666 EG_IMAGE * Badge = NULL;
1667
1668 switch (DiskType) {
1669 case BBS_HARDDISK:
1670 Badge = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
1671 break;
1672 case BBS_USB:
1673 Badge = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
1674 break;
1675 case BBS_CDROM:
1676 Badge = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
1677 break;
1678 } // switch()
1679 return Badge;
1680 } // EG_IMAGE * GetDiskBadge()
1681
1682 //
1683 // pre-boot tool functions
1684 //
1685
1686 static VOID StartTool(IN LOADER_ENTRY *Entry)
1687 {
1688 BeginExternalScreen(Entry->UseGraphicsMode, Entry->me.Title + 6); // assumes "Start <title>" as assigned below
1689 StoreLoaderName(Entry->me.Title);
1690 StartEFIImage(Entry->DevicePath, Entry->LoadOptions, TYPE_EFI,
1691 Basename(Entry->LoaderPath), Entry->OSType, NULL, TRUE, FALSE);
1692 FinishExternalScreen();
1693 } /* static VOID StartTool() */
1694
1695 static LOADER_ENTRY * AddToolEntry(EFI_HANDLE DeviceHandle, IN CHAR16 *LoaderPath, IN CHAR16 *LoaderTitle, IN EG_IMAGE *Image,
1696 IN CHAR16 ShortcutLetter, IN BOOLEAN UseGraphicsMode)
1697 {
1698 LOADER_ENTRY *Entry;
1699 CHAR16 *TitleStr = NULL;
1700
1701 Entry = AllocateZeroPool(sizeof(LOADER_ENTRY));
1702
1703 TitleStr = PoolPrint(L"Start %s", LoaderTitle);
1704 Entry->me.Title = TitleStr;
1705 Entry->me.Tag = TAG_TOOL;
1706 Entry->me.Row = 1;
1707 Entry->me.ShortcutLetter = ShortcutLetter;
1708 Entry->me.Image = Image;
1709 Entry->LoaderPath = (LoaderPath) ? StrDuplicate(LoaderPath) : NULL;
1710 Entry->DevicePath = FileDevicePath(DeviceHandle, Entry->LoaderPath);
1711 Entry->UseGraphicsMode = UseGraphicsMode;
1712
1713 AddMenuEntry(&MainMenu, (REFIT_MENU_ENTRY *)Entry);
1714 return Entry;
1715 } /* static LOADER_ENTRY * AddToolEntry() */
1716
1717 // Locates boot loaders. NOTE: This assumes that GlobalConfig.LegacyType is set correctly.
1718 static VOID ScanForBootloaders(VOID) {
1719 UINTN i;
1720 CHAR8 s;
1721 BOOLEAN ScanForLegacy = FALSE;
1722
1723 // Determine up-front if we'll be scanning for legacy loaders....
1724 for (i = 0; i < NUM_SCAN_OPTIONS; i++) {
1725 s = GlobalConfig.ScanFor[i];
1726 if ((s == 'c') || (s == 'C') || (s == 'h') || (s == 'H') || (s == 'b') || (s == 'B'))
1727 ScanForLegacy = TRUE;
1728 } // for
1729
1730 // If UEFI & scanning for legacy loaders & deep legacy scan, update NVRAM boot manager list
1731 if ((GlobalConfig.LegacyType == LEGACY_TYPE_UEFI) && ScanForLegacy && GlobalConfig.DeepLegacyScan) {
1732 BdsDeleteAllInvalidLegacyBootOptions();
1733 BdsAddNonExistingLegacyBootOptions();
1734 } // if
1735
1736 // scan for loaders and tools, add them to the menu
1737 for (i = 0; i < NUM_SCAN_OPTIONS; i++) {
1738 switch(GlobalConfig.ScanFor[i]) {
1739 case 'c': case 'C':
1740 ScanLegacyDisc();
1741 break;
1742 case 'h': case 'H':
1743 ScanLegacyInternal();
1744 break;
1745 case 'b': case 'B':
1746 ScanLegacyExternal();
1747 break;
1748 case 'm': case 'M':
1749 ScanUserConfigured(GlobalConfig.ConfigFilename);
1750 break;
1751 case 'e': case 'E':
1752 ScanExternal();
1753 break;
1754 case 'i': case 'I':
1755 ScanInternal();
1756 break;
1757 case 'o': case 'O':
1758 ScanOptical();
1759 break;
1760 case 'n': case 'N':
1761 ScanNetboot();
1762 break;
1763 } // switch()
1764 } // for
1765
1766 // assign shortcut keys
1767 for (i = 0; i < MainMenu.EntryCount && MainMenu.Entries[i]->Row == 0 && i < 9; i++)
1768 MainMenu.Entries[i]->ShortcutDigit = (CHAR16)('1' + i);
1769
1770 // wait for user ACK when there were errors
1771 FinishTextScreen(FALSE);
1772 } // static VOID ScanForBootloaders()
1773
1774 // Locate a single tool from the specified Locations using one of the
1775 // specified Names and add it to the menu.
1776 static VOID FindTool(CHAR16 *Locations, CHAR16 *Names, CHAR16 *Description, UINTN Icon) {
1777 UINTN j = 0, k, VolumeIndex;
1778 CHAR16 *DirName, *FileName, *PathName, FullDescription[256];
1779
1780 while ((DirName = FindCommaDelimited(Locations, j++)) != NULL) {
1781 k = 0;
1782 while ((FileName = FindCommaDelimited(Names, k++)) != NULL) {
1783 PathName = StrDuplicate(DirName);
1784 MergeStrings(&PathName, FileName, MyStriCmp(PathName, L"\\") ? 0 : L'\\');
1785 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1786 if ((Volumes[VolumeIndex]->RootDir != NULL) &&
1787 (FileExists(Volumes[VolumeIndex]->RootDir, PathName)) &&
1788 IsValidLoader(Volumes[VolumeIndex]->RootDir, PathName)) {
1789 SPrint(FullDescription, 255, L"%s at %s on %s", Description, PathName, Volumes[VolumeIndex]->VolName);
1790 AddToolEntry(Volumes[VolumeIndex]->DeviceHandle, PathName, FullDescription, BuiltinIcon(Icon), 'S', FALSE);
1791 } // if
1792 } // for
1793 MyFreePool(PathName);
1794 MyFreePool(FileName);
1795 } // while Names
1796 MyFreePool(DirName);
1797 } // while Locations
1798 } // VOID FindTool()
1799
1800 // Add the second-row tags containing built-in and external tools (EFI shell,
1801 // reboot, etc.)
1802 static VOID ScanForTools(VOID) {
1803 CHAR16 *FileName = NULL, *VolName = NULL, *MokLocations, Description[256];
1804 REFIT_MENU_ENTRY *TempMenuEntry;
1805 UINTN i, j, VolumeIndex;
1806 UINT64 osind;
1807 CHAR8 *b = 0;
1808 UINT32 CsrValue;
1809
1810 MokLocations = StrDuplicate(MOK_LOCATIONS);
1811 if (MokLocations != NULL)
1812 MergeStrings(&MokLocations, SelfDirPath, L',');
1813
1814 for (i = 0; i < NUM_TOOLS; i++) {
1815 switch(GlobalConfig.ShowTools[i]) {
1816 // NOTE: Be sure that FileName is NULL at the end of each case.
1817 case TAG_SHUTDOWN:
1818 TempMenuEntry = CopyMenuEntry(&MenuEntryShutdown);
1819 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_SHUTDOWN);
1820 AddMenuEntry(&MainMenu, TempMenuEntry);
1821 break;
1822
1823 case TAG_REBOOT:
1824 TempMenuEntry = CopyMenuEntry(&MenuEntryReset);
1825 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_RESET);
1826 AddMenuEntry(&MainMenu, TempMenuEntry);
1827 break;
1828
1829 case TAG_ABOUT:
1830 TempMenuEntry = CopyMenuEntry(&MenuEntryAbout);
1831 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_ABOUT);
1832 AddMenuEntry(&MainMenu, TempMenuEntry);
1833 break;
1834
1835 case TAG_EXIT:
1836 TempMenuEntry = CopyMenuEntry(&MenuEntryExit);
1837 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_EXIT);
1838 AddMenuEntry(&MainMenu, TempMenuEntry);
1839 break;
1840
1841 case TAG_FIRMWARE:
1842 if (EfivarGetRaw(&GlobalGuid, L"OsIndicationsSupported", &b, &j) == EFI_SUCCESS) {
1843 osind = (UINT64)*b;
1844 if (osind & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) {
1845 TempMenuEntry = CopyMenuEntry(&MenuEntryFirmware);
1846 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_FIRMWARE);
1847 AddMenuEntry(&MainMenu, TempMenuEntry);
1848 } // if
1849 } // if
1850 break;
1851
1852 case TAG_SHELL:
1853 j = 0;
1854 while ((FileName = FindCommaDelimited(SHELL_NAMES, j++)) != NULL) {
1855 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1856 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"EFI Shell", BuiltinIcon(BUILTIN_ICON_TOOL_SHELL),
1857 'S', FALSE);
1858 }
1859 MyFreePool(FileName);
1860 } // while
1861 break;
1862
1863 case TAG_GPTSYNC:
1864 j = 0;
1865 while ((FileName = FindCommaDelimited(GPTSYNC_NAMES, j++)) != NULL) {
1866 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1867 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"Hybrid MBR tool", BuiltinIcon(BUILTIN_ICON_TOOL_PART),
1868 'P', FALSE);
1869 } // if
1870 MyFreePool(FileName);
1871 } // while
1872 FileName = NULL;
1873 break;
1874
1875 case TAG_GDISK:
1876 j = 0;
1877 while ((FileName = FindCommaDelimited(GDISK_NAMES, j++)) != NULL) {
1878 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1879 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"disk partitioning tool",
1880 BuiltinIcon(BUILTIN_ICON_TOOL_PART), 'G', FALSE);
1881 } // if
1882 MyFreePool(FileName);
1883 } // while
1884 FileName = NULL;
1885 break;
1886
1887 case TAG_NETBOOT:
1888 j = 0;
1889 while ((FileName = FindCommaDelimited(NETBOOT_NAMES, j++)) != NULL) {
1890 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1891 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"Netboot",
1892 BuiltinIcon(BUILTIN_ICON_TOOL_NETBOOT), 'N', FALSE);
1893 } // if
1894 MyFreePool(FileName);
1895 } // while
1896 FileName = NULL;
1897 break;
1898
1899 case TAG_APPLE_RECOVERY:
1900 FileName = StrDuplicate(L"\\com.apple.recovery.boot\\boot.efi");
1901 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1902 if ((Volumes[VolumeIndex]->RootDir != NULL) &&
1903 (FileExists(Volumes[VolumeIndex]->RootDir, FileName)) &&
1904 IsValidLoader(Volumes[VolumeIndex]->RootDir, FileName)) {
1905 SPrint(Description, 255, L"Apple Recovery on %s", Volumes[VolumeIndex]->VolName);
1906 AddToolEntry(Volumes[VolumeIndex]->DeviceHandle, FileName, Description,
1907 BuiltinIcon(BUILTIN_ICON_TOOL_APPLE_RESCUE), 'R', TRUE);
1908 } // if
1909 } // for
1910 MyFreePool(FileName);
1911 FileName = NULL;
1912 break;
1913
1914 case TAG_WINDOWS_RECOVERY:
1915 j = 0;
1916 while ((FileName = FindCommaDelimited(GlobalConfig.WindowsRecoveryFiles, j++)) != NULL) {
1917 SplitVolumeAndFilename(&FileName, &VolName);
1918 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1919 if ((Volumes[VolumeIndex]->RootDir != NULL) &&
1920 (FileExists(Volumes[VolumeIndex]->RootDir, FileName)) &&
1921 IsValidLoader(Volumes[VolumeIndex]->RootDir, FileName) &&
1922 ((VolName == NULL) || MyStriCmp(VolName, Volumes[VolumeIndex]->VolName))) {
1923 SPrint(Description, 255, L"Microsoft Recovery on %s", Volumes[VolumeIndex]->VolName);
1924 AddToolEntry(Volumes[VolumeIndex]->DeviceHandle, FileName, Description,
1925 BuiltinIcon(BUILTIN_ICON_TOOL_WINDOWS_RESCUE), 'R', TRUE);
1926 } // if
1927 } // for
1928 } // while
1929 MyFreePool(FileName);
1930 FileName = NULL;
1931 MyFreePool(VolName);
1932 VolName = NULL;
1933 break;
1934
1935 case TAG_MOK_TOOL:
1936 FindTool(MokLocations, MOK_NAMES, L"MOK utility", BUILTIN_ICON_TOOL_MOK_TOOL);
1937 break;
1938
1939 case TAG_FWUPDATE_TOOL:
1940 FindTool(MokLocations, FWUPDATE_NAMES, L"firmware update utility", BUILTIN_ICON_TOOL_FWUPDATE);
1941 break;
1942
1943 case TAG_CSR_ROTATE:
1944 if ((GetCsrStatus(&CsrValue) == EFI_SUCCESS) && (GlobalConfig.CsrValues)) {
1945 TempMenuEntry = CopyMenuEntry(&MenuEntryRotateCsr);
1946 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_CSR_ROTATE);
1947 AddMenuEntry(&MainMenu, TempMenuEntry);
1948 } // if
1949 break;
1950
1951 case TAG_MEMTEST:
1952 FindTool(MEMTEST_LOCATIONS, MEMTEST_NAMES, L"Memory test utility", BUILTIN_ICON_TOOL_MEMTEST);
1953 break;
1954
1955 } // switch()
1956 } // for
1957 } // static VOID ScanForTools
1958
1959 // Rescan for boot loaders
1960 static VOID RescanAll(BOOLEAN DisplayMessage) {
1961 EG_PIXEL BGColor;
1962
1963 BGColor.b = 255;
1964 BGColor.g = 175;
1965 BGColor.r = 100;
1966 BGColor.a = 0;
1967 if (DisplayMessage)
1968 egDisplayMessage(L"Scanning for new boot loaders; please wait....", &BGColor);
1969 FreeList((VOID ***) &(MainMenu.Entries), &MainMenu.EntryCount);
1970 MainMenu.Entries = NULL;
1971 MainMenu.EntryCount = 0;
1972 ConnectAllDriversToAllControllers();
1973 ScanVolumes();
1974 ReadConfig(GlobalConfig.ConfigFilename);
1975 SetVolumeIcons();
1976 ScanForBootloaders();
1977 ScanForTools();
1978 SetupScreen();
1979 } // VOID RescanAll()
1980
1981 #ifdef __MAKEWITH_TIANO
1982
1983 // Minimal initialization function
1984 static VOID InitializeLib(IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable) {
1985 gST = SystemTable;
1986 // gImageHandle = ImageHandle;
1987 gBS = SystemTable->BootServices;
1988 // gRS = SystemTable->RuntimeServices;
1989 gRT = SystemTable->RuntimeServices; // Some BDS functions need gRT to be set
1990 EfiGetSystemConfigurationTable (&gEfiDxeServicesTableGuid, (VOID **) &gDS);
1991 }
1992
1993 #endif
1994
1995 // Set up our own Secure Boot extensions....
1996 // Returns TRUE on success, FALSE otherwise
1997 static BOOLEAN SecureBootSetup(VOID) {
1998 EFI_STATUS Status;
1999 BOOLEAN Success = FALSE;
2000
2001 if (secure_mode() && ShimLoaded()) {
2002 Status = security_policy_install();
2003 if (Status == EFI_SUCCESS) {
2004 Success = TRUE;
2005 } else {
2006 Print(L"Failed to install MOK Secure Boot extensions");
2007 PauseForKey();
2008 }
2009 }
2010 return Success;
2011 } // VOID SecureBootSetup()
2012
2013 // Remove our own Secure Boot extensions....
2014 // Returns TRUE on success, FALSE otherwise
2015 static BOOLEAN SecureBootUninstall(VOID) {
2016 EFI_STATUS Status;
2017 BOOLEAN Success = TRUE;
2018
2019 if (secure_mode()) {
2020 Status = security_policy_uninstall();
2021 if (Status != EFI_SUCCESS) {
2022 Success = FALSE;
2023 BeginTextScreen(L"Secure Boot Policy Failure");
2024 Print(L"Failed to uninstall MOK Secure Boot extensions; forcing a reboot.");
2025 PauseForKey();
2026 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
2027 }
2028 }
2029 return Success;
2030 } // VOID SecureBootUninstall
2031
2032 // Sets the global configuration filename; will be CONFIG_FILE_NAME unless the
2033 // "-c" command-line option is set, in which case that takes precedence.
2034 // If an error is encountered, leaves the value alone (it should be set to
2035 // CONFIG_FILE_NAME when GlobalConfig is initialized).
2036 static VOID SetConfigFilename(EFI_HANDLE ImageHandle) {
2037 EFI_LOADED_IMAGE *Info;
2038 CHAR16 *Options, *FileName, *SubString;
2039 EFI_STATUS Status;
2040
2041 Status = refit_call3_wrapper(BS->HandleProtocol, ImageHandle, &LoadedImageProtocol, (VOID **) &Info);
2042 if ((Status == EFI_SUCCESS) && (Info->LoadOptionsSize > 0)) {
2043 Options = (CHAR16 *) Info->LoadOptions;
2044 SubString = MyStrStr(Options, L" -c ");
2045 if (SubString) {
2046 FileName = StrDuplicate(&SubString[4]);
2047 if (FileName) {
2048 LimitStringLength(FileName, 256);
2049 }
2050
2051 if (FileExists(SelfDir, FileName)) {
2052 GlobalConfig.ConfigFilename = FileName;
2053 } else {
2054 Print(L"Specified configuration file (%s) doesn't exist; using\n'refind.conf' default\n", FileName);
2055 MyFreePool(FileName);
2056 } // if/else
2057 } // if
2058 } // if
2059 } // VOID SetConfigFilename()
2060
2061 //
2062 // main entry point
2063 //
2064 EFI_STATUS
2065 EFIAPI
2066 efi_main (EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable)
2067 {
2068 EFI_STATUS Status;
2069 BOOLEAN MainLoopRunning = TRUE;
2070 BOOLEAN MokProtocol;
2071 REFIT_MENU_ENTRY *ChosenEntry;
2072 UINTN MenuExit, i;
2073 CHAR16 *SelectionName = NULL;
2074 EG_PIXEL BGColor;
2075
2076 // bootstrap
2077 InitializeLib(ImageHandle, SystemTable);
2078 Status = InitRefitLib(ImageHandle);
2079 if (EFI_ERROR(Status))
2080 return Status;
2081
2082 // read configuration
2083 CopyMem(GlobalConfig.ScanFor, "ieom ", NUM_SCAN_OPTIONS);
2084 FindLegacyBootType();
2085 if (GlobalConfig.LegacyType == LEGACY_TYPE_MAC)
2086 CopyMem(GlobalConfig.ScanFor, "ihebocm ", NUM_SCAN_OPTIONS);
2087 SetConfigFilename(ImageHandle);
2088 MokProtocol = SecureBootSetup();
2089 LoadDrivers();
2090 ScanVolumes(); // Do before ReadConfig() because it needs SelfVolume->VolName
2091 ReadConfig(GlobalConfig.ConfigFilename);
2092 SetVolumeIcons();
2093
2094 if (GlobalConfig.SpoofOSXVersion && GlobalConfig.SpoofOSXVersion[0] != L'\0')
2095 SetAppleOSInfo();
2096
2097 InitScreen();
2098 WarnIfLegacyProblems();
2099 MainMenu.TimeoutSeconds = GlobalConfig.Timeout;
2100
2101 // disable EFI watchdog timer
2102 refit_call4_wrapper(BS->SetWatchdogTimer, 0x0000, 0x0000, 0x0000, NULL);
2103
2104 // further bootstrap (now with config available)
2105 ScanForBootloaders();
2106 ScanForTools();
2107 SetupScreen();
2108
2109 if (GlobalConfig.ScanDelay > 0) {
2110 BGColor.b = 255;
2111 BGColor.g = 175;
2112 BGColor.r = 100;
2113 BGColor.a = 0;
2114 if (GlobalConfig.ScanDelay > 1)
2115 egDisplayMessage(L"Pausing before disk scan; please wait....", &BGColor);
2116 for (i = 0; i < GlobalConfig.ScanDelay; i++)
2117 refit_call1_wrapper(BS->Stall, 1000000);
2118 RescanAll(GlobalConfig.ScanDelay > 1);
2119 } // if
2120
2121 if (GlobalConfig.DefaultSelection)
2122 SelectionName = StrDuplicate(GlobalConfig.DefaultSelection);
2123
2124 while (MainLoopRunning) {
2125 MenuExit = RunMainMenu(&MainMenu, &SelectionName, &ChosenEntry);
2126
2127 // The Escape key triggers a re-scan operation....
2128 if (MenuExit == MENU_EXIT_ESCAPE) {
2129 MenuExit = 0;
2130 RescanAll(TRUE);
2131 continue;
2132 }
2133
2134 switch (ChosenEntry->Tag) {
2135
2136 case TAG_REBOOT: // Reboot
2137 TerminateScreen();
2138 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
2139 MainLoopRunning = FALSE; // just in case we get this far
2140 break;
2141
2142 case TAG_SHUTDOWN: // Shut Down
2143 TerminateScreen();
2144 refit_call4_wrapper(RT->ResetSystem, EfiResetShutdown, EFI_SUCCESS, 0, NULL);
2145 MainLoopRunning = FALSE; // just in case we get this far
2146 break;
2147
2148 case TAG_ABOUT: // About rEFInd
2149 AboutrEFInd();
2150 break;
2151
2152 case TAG_LOADER: // Boot OS via .EFI loader
2153 StartLoader((LOADER_ENTRY *)ChosenEntry, SelectionName);
2154 break;
2155
2156 case TAG_LEGACY: // Boot legacy OS
2157 StartLegacy((LEGACY_ENTRY *)ChosenEntry, SelectionName);
2158 break;
2159
2160 case TAG_LEGACY_UEFI: // Boot a legacy OS on a non-Mac
2161 StartLegacyUEFI((LEGACY_ENTRY *)ChosenEntry, SelectionName);
2162 break;
2163
2164 case TAG_TOOL: // Start a EFI tool
2165 StartTool((LOADER_ENTRY *)ChosenEntry);
2166 break;
2167
2168 case TAG_EXIT: // Terminate rEFInd
2169 if ((MokProtocol) && !SecureBootUninstall()) {
2170 MainLoopRunning = FALSE; // just in case we get this far
2171 } else {
2172 BeginTextScreen(L" ");
2173 return EFI_SUCCESS;
2174 }
2175 break;
2176
2177 case TAG_FIRMWARE: // Reboot into firmware's user interface
2178 RebootIntoFirmware();
2179 break;
2180
2181 case TAG_CSR_ROTATE:
2182 RotateCsrValue();
2183 break;
2184
2185 } // switch()
2186 } // while()
2187
2188 // If we end up here, things have gone wrong. Try to reboot, and if that
2189 // fails, go into an endless loop.
2190 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
2191 EndlessIdleLoop();
2192
2193 return EFI_SUCCESS;
2194 } /* efi_main() */