]> code.delx.au - refind/blob - refind/main.c
Fixed uninitialized-pointer bug that manifested as a crash with
[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, 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 // 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 FilenameIn(Volume, Path, DirEntry->FileName, SHELL_NAMES) ||
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
1416 if (Path)
1417 SPrint(FileName, 255, L"\\%s\\%s", Path, DirEntry->FileName);
1418 else
1419 SPrint(FileName, 255, L"\\%s", DirEntry->FileName);
1420 CleanUpPathNameSlashes(FileName);
1421
1422 if(!IsValidLoader(Volume->RootDir, FileName))
1423 continue;
1424
1425 NewLoader = AllocateZeroPool(sizeof(struct LOADER_LIST));
1426 if (NewLoader != NULL) {
1427 NewLoader->FileName = StrDuplicate(FileName);
1428 NewLoader->TimeStamp = DirEntry->ModificationTime;
1429 LoaderList = AddLoaderListEntry(LoaderList, NewLoader);
1430 if (DuplicatesFallback(Volume, FileName))
1431 FoundFallbackDuplicate = TRUE;
1432 } // if
1433 MyFreePool(Extension);
1434 } // while
1435
1436 NewLoader = LoaderList;
1437 while (NewLoader != NULL) {
1438 IsLinux = (StriSubCmp(L"bzImage", NewLoader->FileName) ||
1439 StriSubCmp(L"vmlinuz", NewLoader->FileName) ||
1440 StriSubCmp(L"kernel", NewLoader->FileName));
1441 if ((FirstKernel != NULL) && IsLinux && GlobalConfig.FoldLinuxKernels) {
1442 AddKernelToSubmenu(FirstKernel, NewLoader->FileName, Volume);
1443 } else {
1444 LatestEntry = AddLoaderEntry(NewLoader->FileName, NULL, Volume, !(IsLinux && GlobalConfig.FoldLinuxKernels));
1445 if (IsLinux && (FirstKernel == NULL))
1446 FirstKernel = LatestEntry;
1447 }
1448 NewLoader = NewLoader->NextEntry;
1449 } // while
1450 if ((NewLoader != NULL) && (FirstKernel != NULL) && IsLinux && GlobalConfig.FoldLinuxKernels)
1451 AddMenuEntry(FirstKernel->me.SubScreen, &MenuEntryReturn);
1452
1453 CleanUpLoaderList(LoaderList);
1454 Status = DirIterClose(&DirIter);
1455 // NOTE: EFI_INVALID_PARAMETER really is an error that should be reported;
1456 // but I've gotten reports from users who are getting this error occasionally
1457 // and I can't find anything wrong or reproduce the problem, so I'm putting
1458 // it down to buggy EFI implementations and ignoring that particular error....
1459 if ((Status != EFI_NOT_FOUND) && (Status != EFI_INVALID_PARAMETER)) {
1460 if (Path)
1461 SPrint(FileName, 255, L"while scanning the %s directory", Path);
1462 else
1463 StrCpy(FileName, L"while scanning the root directory");
1464 CheckError(Status, FileName);
1465 } // if (Status != EFI_NOT_FOUND)
1466 } // if not scanning a blacklisted directory
1467
1468 return FoundFallbackDuplicate;
1469 } /* static VOID ScanLoaderDir() */
1470
1471 // Run the IPXE_DISCOVER_NAME program, which obtains the IP address of the boot
1472 // server and the name of the boot file it delivers.
1473 CHAR16* RuniPXEDiscover(EFI_HANDLE Volume)
1474 {
1475 EFI_STATUS Status;
1476 EFI_DEVICE_PATH *FilePath;
1477 EFI_HANDLE iPXEHandle;
1478 CHAR16 *boot_info = NULL;
1479 UINTN boot_info_size = 0;
1480
1481 FilePath = FileDevicePath (Volume, IPXE_DISCOVER_NAME);
1482 Status = refit_call6_wrapper(BS->LoadImage, FALSE, SelfImageHandle, FilePath, NULL, 0, &iPXEHandle);
1483 if (Status != 0)
1484 return NULL;
1485
1486 Status = refit_call3_wrapper(BS->StartImage, iPXEHandle, &boot_info_size, &boot_info);
1487
1488 return boot_info;
1489 } // RuniPXEDiscover()
1490
1491 // Scan for network (PXE) boot servers. This function relies on the presence
1492 // of the IPXE_DISCOVER_NAME and IPXE_NAME program files on the volume from
1493 // which rEFInd launched. As of December 6, 2014, these tools aren't entirely
1494 // reliable. See BUILDING.txt for information on building them.
1495 static VOID ScanNetboot() {
1496 CHAR16 *iPXEFileName = IPXE_NAME;
1497 CHAR16 *Location;
1498 REFIT_VOLUME *NetVolume;
1499
1500 if (FileExists(SelfVolume->RootDir, IPXE_DISCOVER_NAME) &&
1501 FileExists(SelfVolume->RootDir, IPXE_NAME) &&
1502 IsValidLoader(SelfVolume->RootDir, IPXE_DISCOVER_NAME) &&
1503 IsValidLoader(SelfVolume->RootDir, IPXE_NAME)) {
1504 Location = RuniPXEDiscover(SelfVolume->DeviceHandle);
1505 if (Location != NULL && FileExists(SelfVolume->RootDir, iPXEFileName)) {
1506 NetVolume = AllocatePool(sizeof(REFIT_VOLUME));
1507 CopyMem(NetVolume, SelfVolume, sizeof(REFIT_VOLUME));
1508 NetVolume->DiskKind = DISK_KIND_NET;
1509 NetVolume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_NET);
1510 NetVolume->PartName = NetVolume->VolName = NULL;
1511 AddLoaderEntry(iPXEFileName, Location, NetVolume, TRUE);
1512 MyFreePool(NetVolume);
1513 } // if support files exist and are valid
1514 }
1515 } // VOID ScanNetBoot()
1516
1517 static VOID ScanEfiFiles(REFIT_VOLUME *Volume) {
1518 EFI_STATUS Status;
1519 REFIT_DIR_ITER EfiDirIter;
1520 EFI_FILE_INFO *EfiDirEntry;
1521 CHAR16 FileName[256], *Directory = NULL, *MatchPatterns, *VolName = NULL, *SelfPath;
1522 UINTN i, Length;
1523 BOOLEAN ScanFallbackLoader = TRUE;
1524 BOOLEAN FoundBRBackup = FALSE;
1525
1526 if (Volume && (Volume->RootDir != NULL) && (Volume->VolName != NULL) && (Volume->IsReadable)) {
1527 MatchPatterns = StrDuplicate(LOADER_MATCH_PATTERNS);
1528 if (GlobalConfig.ScanAllLinux)
1529 MergeStrings(&MatchPatterns, LINUX_MATCH_PATTERNS, L',');
1530
1531 // check for Mac OS X boot loader
1532 if (ShouldScan(Volume, MACOSX_LOADER_DIR)) {
1533 StrCpy(FileName, MACOSX_LOADER_PATH);
1534 if (FileExists(Volume->RootDir, FileName) && !FilenameIn(Volume, MACOSX_LOADER_DIR, L"boot.efi", GlobalConfig.DontScanFiles)) {
1535 AddLoaderEntry(FileName, L"Mac OS X", Volume, TRUE);
1536 if (DuplicatesFallback(Volume, FileName))
1537 ScanFallbackLoader = FALSE;
1538 }
1539
1540 // check for XOM
1541 StrCpy(FileName, L"System\\Library\\CoreServices\\xom.efi");
1542 if (FileExists(Volume->RootDir, FileName) && !FilenameIn(Volume, MACOSX_LOADER_DIR, L"xom.efi", GlobalConfig.DontScanFiles)) {
1543 AddLoaderEntry(FileName, L"Windows XP (XoM)", Volume, TRUE);
1544 if (DuplicatesFallback(Volume, FileName))
1545 ScanFallbackLoader = FALSE;
1546 }
1547 } // if should scan Mac directory
1548
1549 // check for Microsoft boot loader/menu
1550 if (ShouldScan(Volume, L"EFI\\Microsoft\\Boot")) {
1551 StrCpy(FileName, L"EFI\\Microsoft\\Boot\\bkpbootmgfw.efi");
1552 if (FileExists(Volume->RootDir, FileName) && !FilenameIn(Volume, L"EFI\\Microsoft\\Boot", L"bkpbootmgfw.efi",
1553 GlobalConfig.DontScanFiles)) {
1554 AddLoaderEntry(FileName, L"Microsoft EFI boot (Boot Repair backup)", Volume, TRUE);
1555 FoundBRBackup = TRUE;
1556 if (DuplicatesFallback(Volume, FileName))
1557 ScanFallbackLoader = FALSE;
1558 }
1559 StrCpy(FileName, L"EFI\\Microsoft\\Boot\\bootmgfw.efi");
1560 if (FileExists(Volume->RootDir, FileName) &&
1561 !FilenameIn(Volume, L"EFI\\Microsoft\\Boot", L"bootmgfw.efi", GlobalConfig.DontScanFiles)) {
1562 if (FoundBRBackup)
1563 AddLoaderEntry(FileName, L"Supposed Microsoft EFI boot (probably GRUB)", Volume, TRUE);
1564 else
1565 AddLoaderEntry(FileName, L"Microsoft EFI boot", Volume, TRUE);
1566 if (DuplicatesFallback(Volume, FileName))
1567 ScanFallbackLoader = FALSE;
1568 }
1569 } // if
1570
1571 // scan the root directory for EFI executables
1572 if (ScanLoaderDir(Volume, L"\\", MatchPatterns))
1573 ScanFallbackLoader = FALSE;
1574
1575 // scan subdirectories of the EFI directory (as per the standard)
1576 DirIterOpen(Volume->RootDir, L"EFI", &EfiDirIter);
1577 while (DirIterNext(&EfiDirIter, 1, NULL, &EfiDirEntry)) {
1578 if (MyStriCmp(EfiDirEntry->FileName, L"tools") || EfiDirEntry->FileName[0] == '.')
1579 continue; // skip this, doesn't contain boot loaders or is scanned later
1580 SPrint(FileName, 255, L"EFI\\%s", EfiDirEntry->FileName);
1581 if (ScanLoaderDir(Volume, FileName, MatchPatterns))
1582 ScanFallbackLoader = FALSE;
1583 } // while()
1584 Status = DirIterClose(&EfiDirIter);
1585 if ((Status != EFI_NOT_FOUND) && (Status != EFI_INVALID_PARAMETER))
1586 CheckError(Status, L"while scanning the EFI directory");
1587
1588 // Scan user-specified (or additional default) directories....
1589 i = 0;
1590 while ((Directory = FindCommaDelimited(GlobalConfig.AlsoScan, i++)) != NULL) {
1591 if (ShouldScan(Volume, Directory)) {
1592 SplitVolumeAndFilename(&Directory, &VolName);
1593 CleanUpPathNameSlashes(Directory);
1594 Length = StrLen(Directory);
1595 if ((Length > 0) && ScanLoaderDir(Volume, Directory, MatchPatterns))
1596 ScanFallbackLoader = FALSE;
1597 MyFreePool(VolName);
1598 } // if should scan dir
1599 MyFreePool(Directory);
1600 } // while
1601
1602 // Don't scan the fallback loader if it's on the same volume and a duplicate of rEFInd itself....
1603 SelfPath = DevicePathToStr(SelfLoadedImage->FilePath);
1604 CleanUpPathNameSlashes(SelfPath);
1605 if ((Volume->DeviceHandle == SelfLoadedImage->DeviceHandle) && DuplicatesFallback(Volume, SelfPath))
1606 ScanFallbackLoader = FALSE;
1607
1608 // If not a duplicate & if it exists & if it's not us, create an entry
1609 // for the fallback boot loader
1610 if (ScanFallbackLoader && FileExists(Volume->RootDir, FALLBACK_FULLNAME) && ShouldScan(Volume, L"EFI\\BOOT")) {
1611 AddLoaderEntry(FALLBACK_FULLNAME, L"Fallback boot loader", Volume, TRUE);
1612 }
1613 } // if
1614 } // static VOID ScanEfiFiles()
1615
1616 // Scan internal disks for valid EFI boot loaders....
1617 static VOID ScanInternal(VOID) {
1618 UINTN VolumeIndex;
1619
1620 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1621 if (Volumes[VolumeIndex]->DiskKind == DISK_KIND_INTERNAL) {
1622 ScanEfiFiles(Volumes[VolumeIndex]);
1623 }
1624 } // for
1625 } // static VOID ScanInternal()
1626
1627 // Scan external disks for valid EFI boot loaders....
1628 static VOID ScanExternal(VOID) {
1629 UINTN VolumeIndex;
1630
1631 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1632 if (Volumes[VolumeIndex]->DiskKind == DISK_KIND_EXTERNAL) {
1633 ScanEfiFiles(Volumes[VolumeIndex]);
1634 }
1635 } // for
1636 } // static VOID ScanExternal()
1637
1638 // Scan internal disks for valid EFI boot loaders....
1639 static VOID ScanOptical(VOID) {
1640 UINTN VolumeIndex;
1641
1642 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1643 if (Volumes[VolumeIndex]->DiskKind == DISK_KIND_OPTICAL) {
1644 ScanEfiFiles(Volumes[VolumeIndex]);
1645 }
1646 } // for
1647 } // static VOID ScanOptical()
1648
1649 // default volume badge icon based on disk kind
1650 EG_IMAGE * GetDiskBadge(IN UINTN DiskType) {
1651 EG_IMAGE * Badge = NULL;
1652
1653 switch (DiskType) {
1654 case BBS_HARDDISK:
1655 Badge = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
1656 break;
1657 case BBS_USB:
1658 Badge = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
1659 break;
1660 case BBS_CDROM:
1661 Badge = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
1662 break;
1663 } // switch()
1664 return Badge;
1665 } // EG_IMAGE * GetDiskBadge()
1666
1667 //
1668 // pre-boot tool functions
1669 //
1670
1671 static VOID StartTool(IN LOADER_ENTRY *Entry)
1672 {
1673 BeginExternalScreen(Entry->UseGraphicsMode, Entry->me.Title + 6); // assumes "Start <title>" as assigned below
1674 StoreLoaderName(Entry->me.Title);
1675 StartEFIImage(Entry->DevicePath, Entry->LoadOptions, TYPE_EFI,
1676 Basename(Entry->LoaderPath), Entry->OSType, NULL, TRUE, FALSE);
1677 FinishExternalScreen();
1678 } /* static VOID StartTool() */
1679
1680 static LOADER_ENTRY * AddToolEntry(EFI_HANDLE DeviceHandle, IN CHAR16 *LoaderPath, IN CHAR16 *LoaderTitle, IN EG_IMAGE *Image,
1681 IN CHAR16 ShortcutLetter, IN BOOLEAN UseGraphicsMode)
1682 {
1683 LOADER_ENTRY *Entry;
1684 CHAR16 *TitleStr = NULL;
1685
1686 Entry = AllocateZeroPool(sizeof(LOADER_ENTRY));
1687
1688 TitleStr = PoolPrint(L"Start %s", LoaderTitle);
1689 Entry->me.Title = TitleStr;
1690 Entry->me.Tag = TAG_TOOL;
1691 Entry->me.Row = 1;
1692 Entry->me.ShortcutLetter = ShortcutLetter;
1693 Entry->me.Image = Image;
1694 Entry->LoaderPath = (LoaderPath) ? StrDuplicate(LoaderPath) : NULL;
1695 Entry->DevicePath = FileDevicePath(DeviceHandle, Entry->LoaderPath);
1696 Entry->UseGraphicsMode = UseGraphicsMode;
1697
1698 AddMenuEntry(&MainMenu, (REFIT_MENU_ENTRY *)Entry);
1699 return Entry;
1700 } /* static LOADER_ENTRY * AddToolEntry() */
1701
1702 // Locates boot loaders. NOTE: This assumes that GlobalConfig.LegacyType is set correctly.
1703 static VOID ScanForBootloaders(VOID) {
1704 UINTN i;
1705 CHAR8 s;
1706 BOOLEAN ScanForLegacy = FALSE;
1707
1708 // Determine up-front if we'll be scanning for legacy loaders....
1709 for (i = 0; i < NUM_SCAN_OPTIONS; i++) {
1710 s = GlobalConfig.ScanFor[i];
1711 if ((s == 'c') || (s == 'C') || (s == 'h') || (s == 'H') || (s == 'b') || (s == 'B'))
1712 ScanForLegacy = TRUE;
1713 } // for
1714
1715 // If UEFI & scanning for legacy loaders & deep legacy scan, update NVRAM boot manager list
1716 if ((GlobalConfig.LegacyType == LEGACY_TYPE_UEFI) && ScanForLegacy && GlobalConfig.DeepLegacyScan) {
1717 BdsDeleteAllInvalidLegacyBootOptions();
1718 BdsAddNonExistingLegacyBootOptions();
1719 } // if
1720
1721 // scan for loaders and tools, add them to the menu
1722 for (i = 0; i < NUM_SCAN_OPTIONS; i++) {
1723 switch(GlobalConfig.ScanFor[i]) {
1724 case 'c': case 'C':
1725 ScanLegacyDisc();
1726 break;
1727 case 'h': case 'H':
1728 ScanLegacyInternal();
1729 break;
1730 case 'b': case 'B':
1731 ScanLegacyExternal();
1732 break;
1733 case 'm': case 'M':
1734 ScanUserConfigured(GlobalConfig.ConfigFilename);
1735 break;
1736 case 'e': case 'E':
1737 ScanExternal();
1738 break;
1739 case 'i': case 'I':
1740 ScanInternal();
1741 break;
1742 case 'o': case 'O':
1743 ScanOptical();
1744 break;
1745 case 'n': case 'N':
1746 ScanNetboot();
1747 break;
1748 } // switch()
1749 } // for
1750
1751 // assign shortcut keys
1752 for (i = 0; i < MainMenu.EntryCount && MainMenu.Entries[i]->Row == 0 && i < 9; i++)
1753 MainMenu.Entries[i]->ShortcutDigit = (CHAR16)('1' + i);
1754
1755 // wait for user ACK when there were errors
1756 FinishTextScreen(FALSE);
1757 } // static VOID ScanForBootloaders()
1758
1759 // Locate a single tool from the specified Locations using one of the
1760 // specified Names and add it to the menu.
1761 static VOID FindTool(CHAR16 *Locations, CHAR16 *Names, CHAR16 *Description, UINTN Icon) {
1762 UINTN j = 0, k, VolumeIndex;
1763 CHAR16 *DirName, *FileName, *PathName, FullDescription[256];
1764
1765 while ((DirName = FindCommaDelimited(Locations, j++)) != NULL) {
1766 k = 0;
1767 while ((FileName = FindCommaDelimited(Names, k++)) != NULL) {
1768 PathName = StrDuplicate(DirName);
1769 MergeStrings(&PathName, FileName, MyStriCmp(PathName, L"\\") ? 0 : L'\\');
1770 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1771 if ((Volumes[VolumeIndex]->RootDir != NULL) &&
1772 (FileExists(Volumes[VolumeIndex]->RootDir, PathName)) &&
1773 IsValidLoader(Volumes[VolumeIndex]->RootDir, PathName)) {
1774 SPrint(FullDescription, 255, L"%s at %s on %s", Description, PathName, Volumes[VolumeIndex]->VolName);
1775 AddToolEntry(Volumes[VolumeIndex]->DeviceHandle, PathName, FullDescription, BuiltinIcon(Icon), 'S', FALSE);
1776 } // if
1777 } // for
1778 MyFreePool(PathName);
1779 MyFreePool(FileName);
1780 } // while Names
1781 MyFreePool(DirName);
1782 } // while Locations
1783 } // VOID FindTool()
1784
1785 // Add the second-row tags containing built-in and external tools (EFI shell,
1786 // reboot, etc.)
1787 static VOID ScanForTools(VOID) {
1788 CHAR16 *FileName = NULL, *VolName = NULL, *MokLocations, Description[256];
1789 REFIT_MENU_ENTRY *TempMenuEntry;
1790 UINTN i, j, VolumeIndex;
1791 UINT64 osind;
1792 CHAR8 *b = 0;
1793 UINT32 CsrValue;
1794
1795 MokLocations = StrDuplicate(MOK_LOCATIONS);
1796 if (MokLocations != NULL)
1797 MergeStrings(&MokLocations, SelfDirPath, L',');
1798
1799 for (i = 0; i < NUM_TOOLS; i++) {
1800 switch(GlobalConfig.ShowTools[i]) {
1801 // NOTE: Be sure that FileName is NULL at the end of each case.
1802 case TAG_SHUTDOWN:
1803 TempMenuEntry = CopyMenuEntry(&MenuEntryShutdown);
1804 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_SHUTDOWN);
1805 AddMenuEntry(&MainMenu, TempMenuEntry);
1806 break;
1807
1808 case TAG_REBOOT:
1809 TempMenuEntry = CopyMenuEntry(&MenuEntryReset);
1810 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_RESET);
1811 AddMenuEntry(&MainMenu, TempMenuEntry);
1812 break;
1813
1814 case TAG_ABOUT:
1815 TempMenuEntry = CopyMenuEntry(&MenuEntryAbout);
1816 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_ABOUT);
1817 AddMenuEntry(&MainMenu, TempMenuEntry);
1818 break;
1819
1820 case TAG_EXIT:
1821 TempMenuEntry = CopyMenuEntry(&MenuEntryExit);
1822 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_EXIT);
1823 AddMenuEntry(&MainMenu, TempMenuEntry);
1824 break;
1825
1826 case TAG_FIRMWARE:
1827 if (EfivarGetRaw(&GlobalGuid, L"OsIndicationsSupported", &b, &j) == EFI_SUCCESS) {
1828 osind = (UINT64)*b;
1829 if (osind & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) {
1830 TempMenuEntry = CopyMenuEntry(&MenuEntryFirmware);
1831 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_FIRMWARE);
1832 AddMenuEntry(&MainMenu, TempMenuEntry);
1833 } // if
1834 } // if
1835 break;
1836
1837 case TAG_SHELL:
1838 j = 0;
1839 while ((FileName = FindCommaDelimited(SHELL_NAMES, j++)) != NULL) {
1840 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1841 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"EFI Shell", BuiltinIcon(BUILTIN_ICON_TOOL_SHELL),
1842 'S', FALSE);
1843 }
1844 MyFreePool(FileName);
1845 } // while
1846 break;
1847
1848 case TAG_GPTSYNC:
1849 j = 0;
1850 while ((FileName = FindCommaDelimited(GPTSYNC_NAMES, j++)) != NULL) {
1851 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1852 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"Hybrid MBR tool", BuiltinIcon(BUILTIN_ICON_TOOL_PART),
1853 'P', FALSE);
1854 } // if
1855 MyFreePool(FileName);
1856 } // while
1857 FileName = NULL;
1858 break;
1859
1860 case TAG_GDISK:
1861 j = 0;
1862 while ((FileName = FindCommaDelimited(GDISK_NAMES, j++)) != NULL) {
1863 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1864 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"disk partitioning tool",
1865 BuiltinIcon(BUILTIN_ICON_TOOL_PART), 'G', FALSE);
1866 } // if
1867 MyFreePool(FileName);
1868 } // while
1869 FileName = NULL;
1870 break;
1871
1872 case TAG_NETBOOT:
1873 j = 0;
1874 while ((FileName = FindCommaDelimited(NETBOOT_NAMES, j++)) != NULL) {
1875 if (FileExists(SelfRootDir, FileName) && IsValidLoader(SelfRootDir, FileName)) {
1876 AddToolEntry(SelfLoadedImage->DeviceHandle, FileName, L"Netboot",
1877 BuiltinIcon(BUILTIN_ICON_TOOL_NETBOOT), 'N', FALSE);
1878 } // if
1879 MyFreePool(FileName);
1880 } // while
1881 FileName = NULL;
1882 break;
1883
1884 case TAG_APPLE_RECOVERY:
1885 FileName = StrDuplicate(L"\\com.apple.recovery.boot\\boot.efi");
1886 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1887 if ((Volumes[VolumeIndex]->RootDir != NULL) &&
1888 (FileExists(Volumes[VolumeIndex]->RootDir, FileName)) &&
1889 IsValidLoader(Volumes[VolumeIndex]->RootDir, FileName)) {
1890 SPrint(Description, 255, L"Apple Recovery on %s", Volumes[VolumeIndex]->VolName);
1891 AddToolEntry(Volumes[VolumeIndex]->DeviceHandle, FileName, Description,
1892 BuiltinIcon(BUILTIN_ICON_TOOL_APPLE_RESCUE), 'R', TRUE);
1893 } // if
1894 } // for
1895 MyFreePool(FileName);
1896 FileName = NULL;
1897 break;
1898
1899 case TAG_WINDOWS_RECOVERY:
1900 j = 0;
1901 while ((FileName = FindCommaDelimited(GlobalConfig.WindowsRecoveryFiles, j++)) != NULL) {
1902 SplitVolumeAndFilename(&FileName, &VolName);
1903 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1904 if ((Volumes[VolumeIndex]->RootDir != NULL) &&
1905 (FileExists(Volumes[VolumeIndex]->RootDir, FileName)) &&
1906 IsValidLoader(Volumes[VolumeIndex]->RootDir, FileName) &&
1907 ((VolName == NULL) || MyStriCmp(VolName, Volumes[VolumeIndex]->VolName))) {
1908 SPrint(Description, 255, L"Microsoft Recovery on %s", Volumes[VolumeIndex]->VolName);
1909 AddToolEntry(Volumes[VolumeIndex]->DeviceHandle, FileName, Description,
1910 BuiltinIcon(BUILTIN_ICON_TOOL_WINDOWS_RESCUE), 'R', TRUE);
1911 } // if
1912 } // for
1913 } // while
1914 MyFreePool(FileName);
1915 FileName = NULL;
1916 MyFreePool(VolName);
1917 VolName = NULL;
1918 break;
1919
1920 case TAG_MOK_TOOL:
1921 FindTool(MokLocations, MOK_NAMES, L"MOK utility", BUILTIN_ICON_TOOL_MOK_TOOL);
1922 break;
1923
1924 case TAG_FWUPDATE_TOOL:
1925 FindTool(MokLocations, FWUPDATE_NAMES, L"firmware update utility", BUILTIN_ICON_TOOL_FWUPDATE);
1926 break;
1927
1928 case TAG_CSR_ROTATE:
1929 if ((GetCsrStatus(&CsrValue) == EFI_SUCCESS) && (GlobalConfig.CsrValues)) {
1930 TempMenuEntry = CopyMenuEntry(&MenuEntryRotateCsr);
1931 TempMenuEntry->Image = BuiltinIcon(BUILTIN_ICON_FUNC_CSR_ROTATE);
1932 AddMenuEntry(&MainMenu, TempMenuEntry);
1933 } // if
1934 break;
1935
1936 case TAG_MEMTEST:
1937 FindTool(MEMTEST_LOCATIONS, MEMTEST_NAMES, L"Memory test utility", BUILTIN_ICON_TOOL_MEMTEST);
1938 break;
1939
1940 } // switch()
1941 } // for
1942 } // static VOID ScanForTools
1943
1944 // Rescan for boot loaders
1945 static VOID RescanAll(BOOLEAN DisplayMessage) {
1946 EG_PIXEL BGColor;
1947
1948 BGColor.b = 255;
1949 BGColor.g = 175;
1950 BGColor.r = 100;
1951 BGColor.a = 0;
1952 if (DisplayMessage)
1953 egDisplayMessage(L"Scanning for new boot loaders; please wait....", &BGColor);
1954 FreeList((VOID ***) &(MainMenu.Entries), &MainMenu.EntryCount);
1955 MainMenu.Entries = NULL;
1956 MainMenu.EntryCount = 0;
1957 ConnectAllDriversToAllControllers();
1958 ScanVolumes();
1959 ReadConfig(GlobalConfig.ConfigFilename);
1960 SetVolumeIcons();
1961 ScanForBootloaders();
1962 ScanForTools();
1963 SetupScreen();
1964 } // VOID RescanAll()
1965
1966 #ifdef __MAKEWITH_TIANO
1967
1968 // Minimal initialization function
1969 static VOID InitializeLib(IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable) {
1970 gST = SystemTable;
1971 // gImageHandle = ImageHandle;
1972 gBS = SystemTable->BootServices;
1973 // gRS = SystemTable->RuntimeServices;
1974 gRT = SystemTable->RuntimeServices; // Some BDS functions need gRT to be set
1975 EfiGetSystemConfigurationTable (&gEfiDxeServicesTableGuid, (VOID **) &gDS);
1976 }
1977
1978 #endif
1979
1980 // Set up our own Secure Boot extensions....
1981 // Returns TRUE on success, FALSE otherwise
1982 static BOOLEAN SecureBootSetup(VOID) {
1983 EFI_STATUS Status;
1984 BOOLEAN Success = FALSE;
1985
1986 if (secure_mode() && ShimLoaded()) {
1987 Status = security_policy_install();
1988 if (Status == EFI_SUCCESS) {
1989 Success = TRUE;
1990 } else {
1991 Print(L"Failed to install MOK Secure Boot extensions");
1992 PauseForKey();
1993 }
1994 }
1995 return Success;
1996 } // VOID SecureBootSetup()
1997
1998 // Remove our own Secure Boot extensions....
1999 // Returns TRUE on success, FALSE otherwise
2000 static BOOLEAN SecureBootUninstall(VOID) {
2001 EFI_STATUS Status;
2002 BOOLEAN Success = TRUE;
2003
2004 if (secure_mode()) {
2005 Status = security_policy_uninstall();
2006 if (Status != EFI_SUCCESS) {
2007 Success = FALSE;
2008 BeginTextScreen(L"Secure Boot Policy Failure");
2009 Print(L"Failed to uninstall MOK Secure Boot extensions; forcing a reboot.");
2010 PauseForKey();
2011 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
2012 }
2013 }
2014 return Success;
2015 } // VOID SecureBootUninstall
2016
2017 // Sets the global configuration filename; will be CONFIG_FILE_NAME unless the
2018 // "-c" command-line option is set, in which case that takes precedence.
2019 // If an error is encountered, leaves the value alone (it should be set to
2020 // CONFIG_FILE_NAME when GlobalConfig is initialized).
2021 static VOID SetConfigFilename(EFI_HANDLE ImageHandle) {
2022 EFI_LOADED_IMAGE *Info;
2023 CHAR16 *Options, *FileName, *SubString;
2024 EFI_STATUS Status;
2025
2026 Status = refit_call3_wrapper(BS->HandleProtocol, ImageHandle, &LoadedImageProtocol, (VOID **) &Info);
2027 if ((Status == EFI_SUCCESS) && (Info->LoadOptionsSize > 0)) {
2028 Options = (CHAR16 *) Info->LoadOptions;
2029 SubString = MyStrStr(Options, L" -c ");
2030 if (SubString) {
2031 FileName = StrDuplicate(&SubString[4]);
2032 if (FileName) {
2033 LimitStringLength(FileName, 256);
2034 }
2035
2036 if (FileExists(SelfDir, FileName)) {
2037 GlobalConfig.ConfigFilename = FileName;
2038 } else {
2039 Print(L"Specified configuration file (%s) doesn't exist; using\n'refind.conf' default\n", FileName);
2040 MyFreePool(FileName);
2041 } // if/else
2042 } // if
2043 } // if
2044 } // VOID SetConfigFilename()
2045
2046 //
2047 // main entry point
2048 //
2049 EFI_STATUS
2050 EFIAPI
2051 efi_main (EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable)
2052 {
2053 EFI_STATUS Status;
2054 BOOLEAN MainLoopRunning = TRUE;
2055 BOOLEAN MokProtocol;
2056 REFIT_MENU_ENTRY *ChosenEntry;
2057 UINTN MenuExit, i;
2058 CHAR16 *SelectionName = NULL;
2059 EG_PIXEL BGColor;
2060
2061 // bootstrap
2062 InitializeLib(ImageHandle, SystemTable);
2063 Status = InitRefitLib(ImageHandle);
2064 if (EFI_ERROR(Status))
2065 return Status;
2066
2067 // read configuration
2068 CopyMem(GlobalConfig.ScanFor, "ieom ", NUM_SCAN_OPTIONS);
2069 FindLegacyBootType();
2070 if (GlobalConfig.LegacyType == LEGACY_TYPE_MAC)
2071 CopyMem(GlobalConfig.ScanFor, "ihebocm ", NUM_SCAN_OPTIONS);
2072 SetConfigFilename(ImageHandle);
2073 MokProtocol = SecureBootSetup();
2074 LoadDrivers();
2075 ScanVolumes(); // Do before ReadConfig() because it needs SelfVolume->VolName
2076 ReadConfig(GlobalConfig.ConfigFilename);
2077 SetVolumeIcons();
2078
2079 if (GlobalConfig.SpoofOSXVersion && GlobalConfig.SpoofOSXVersion[0] != L'\0')
2080 SetAppleOSInfo();
2081
2082 InitScreen();
2083 WarnIfLegacyProblems();
2084 MainMenu.TimeoutSeconds = GlobalConfig.Timeout;
2085
2086 // disable EFI watchdog timer
2087 refit_call4_wrapper(BS->SetWatchdogTimer, 0x0000, 0x0000, 0x0000, NULL);
2088
2089 // further bootstrap (now with config available)
2090 ScanForBootloaders();
2091 ScanForTools();
2092 SetupScreen();
2093
2094 if (GlobalConfig.ScanDelay > 0) {
2095 BGColor.b = 255;
2096 BGColor.g = 175;
2097 BGColor.r = 100;
2098 BGColor.a = 0;
2099 if (GlobalConfig.ScanDelay > 1)
2100 egDisplayMessage(L"Pausing before disk scan; please wait....", &BGColor);
2101 for (i = 0; i < GlobalConfig.ScanDelay; i++)
2102 refit_call1_wrapper(BS->Stall, 1000000);
2103 RescanAll(GlobalConfig.ScanDelay > 1);
2104 } // if
2105
2106 if (GlobalConfig.DefaultSelection)
2107 SelectionName = StrDuplicate(GlobalConfig.DefaultSelection);
2108
2109 while (MainLoopRunning) {
2110 MenuExit = RunMainMenu(&MainMenu, &SelectionName, &ChosenEntry);
2111
2112 // The Escape key triggers a re-scan operation....
2113 if (MenuExit == MENU_EXIT_ESCAPE) {
2114 MenuExit = 0;
2115 RescanAll(TRUE);
2116 continue;
2117 }
2118
2119 switch (ChosenEntry->Tag) {
2120
2121 case TAG_REBOOT: // Reboot
2122 TerminateScreen();
2123 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
2124 MainLoopRunning = FALSE; // just in case we get this far
2125 break;
2126
2127 case TAG_SHUTDOWN: // Shut Down
2128 TerminateScreen();
2129 refit_call4_wrapper(RT->ResetSystem, EfiResetShutdown, EFI_SUCCESS, 0, NULL);
2130 MainLoopRunning = FALSE; // just in case we get this far
2131 break;
2132
2133 case TAG_ABOUT: // About rEFInd
2134 AboutrEFInd();
2135 break;
2136
2137 case TAG_LOADER: // Boot OS via .EFI loader
2138 StartLoader((LOADER_ENTRY *)ChosenEntry, SelectionName);
2139 break;
2140
2141 case TAG_LEGACY: // Boot legacy OS
2142 StartLegacy((LEGACY_ENTRY *)ChosenEntry, SelectionName);
2143 break;
2144
2145 case TAG_LEGACY_UEFI: // Boot a legacy OS on a non-Mac
2146 StartLegacyUEFI((LEGACY_ENTRY *)ChosenEntry, SelectionName);
2147 break;
2148
2149 case TAG_TOOL: // Start a EFI tool
2150 StartTool((LOADER_ENTRY *)ChosenEntry);
2151 break;
2152
2153 case TAG_EXIT: // Terminate rEFInd
2154 if ((MokProtocol) && !SecureBootUninstall()) {
2155 MainLoopRunning = FALSE; // just in case we get this far
2156 } else {
2157 BeginTextScreen(L" ");
2158 return EFI_SUCCESS;
2159 }
2160 break;
2161
2162 case TAG_FIRMWARE: // Reboot into firmware's user interface
2163 RebootIntoFirmware();
2164 break;
2165
2166 case TAG_CSR_ROTATE:
2167 RotateCsrValue();
2168 break;
2169
2170 } // switch()
2171 } // while()
2172
2173 // If we end up here, things have gone wrong. Try to reboot, and if that
2174 // fails, go into an endless loop.
2175 refit_call4_wrapper(RT->ResetSystem, EfiResetCold, EFI_SUCCESS, 0, NULL);
2176 EndlessIdleLoop();
2177
2178 return EFI_SUCCESS;
2179 } /* efi_main() */