3 * Main code for the boot menu
5 * Copyright (c) 2006-2010 Christoph Pfisterer
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
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
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.
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.
37 * Modifications copyright (c) 2012-2015 Roderick W. Smith
39 * Modifications distributed under the terms of the GNU General Public
40 * License (GPL) version 3 (GPLv3), or (at your option) any later version.
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.
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.
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/>.
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"
76 #ifdef __MAKEWITH_GNUEFI
77 #ifndef EFI_SECURITY_VIOLATION
78 #define EFI_SECURITY_VIOLATION EFIERR (26)
82 #ifndef EFI_OS_INDICATIONS_BOOT_TO_FW_UI
83 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001ULL
86 #ifdef __MAKEWITH_TIANO
87 #define LibLocateHandle gBS->LocateHandleBuffer
93 #define MACOSX_LOADER_DIR L"System\\Library\\CoreServices"
94 #define MACOSX_LOADER_PATH ( MACOSX_LOADER_DIR L"\\boot.efi" )
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 }};
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 }};
137 #define FAT_ARCH 0x0ef1fab9 /* ID for Apple "fat" binary */
139 #define IPXE_DISCOVER_NAME L"\\efi\\tools\\ipxe_discover.efi"
140 #define IPXE_NAME L"\\efi\\tools\\ipxe.efi"
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*"
147 // Maximum length of a text string in certain menus
148 #define MAX_LINE_LENGTH 65
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
};
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
"" };
163 REFIT_CONFIG GlobalConfig
= { FALSE
, TRUE
, FALSE
, FALSE
, TRUE
, 0, 0, 0, DONT_CHANGE_TEXT_MODE
,
164 20, 0, 0, GRAPHICS_FOR_OSX
, LEGACY_TYPE_MAC
,
165 0, 0, { DEFAULT_BIG_ICON_SIZE
/ 4, DEFAULT_SMALL_ICON_SIZE
, DEFAULT_BIG_ICON_SIZE
},
166 BANNER_NOSCALE
, NULL
, NULL
, NULL
, NULL
, CONFIG_FILE_NAME
, NULL
, NULL
, NULL
, NULL
,
167 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
168 { TAG_SHELL
, TAG_MEMTEST
, TAG_GDISK
, TAG_APPLE_RECOVERY
, TAG_WINDOWS_RECOVERY
,
169 TAG_MOK_TOOL
, TAG_ABOUT
, TAG_SHUTDOWN
, TAG_REBOOT
, TAG_FIRMWARE
,
170 0, 0, 0, 0, 0, 0, 0, 0 }
173 EFI_GUID GlobalGuid
= EFI_GLOBAL_VARIABLE
;
174 EFI_GUID RefindGuid
= REFIND_GUID_VALUE
;
176 GPT_DATA
*gPartitions
= NULL
;
178 // Structure used to hold boot loader filenames and time stamps in
179 // a linked list; used to sort entries within a directory.
183 struct LOADER_LIST
*NextEntry
;
190 static VOID
AboutrEFInd(VOID
)
192 CHAR16
*FirmwareVendor
;
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-2015 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)));
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"));
216 AddMenuInfoLine(&AboutMenu
, L
" Platform: unknown");
218 if (GetCsrStatus(&CsrStatus
) == EFI_SUCCESS
) {
219 RecordgCsrStatus(CsrStatus
, FALSE
);
220 AddMenuInfoLine(&AboutMenu
, gCsrStatus
);
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");
231 AddMenuInfoLine(&AboutMenu
, L
"Built with TianoCore EDK2");
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
);
239 RunMenu(&AboutMenu
, NULL
);
240 } /* VOID AboutrEFInd() */
242 static VOID
WarnSecureBootError(CHAR16
*Name
, BOOLEAN Verbose
) {
244 Name
= L
"the loader";
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");
261 } // VOID WarnSecureBootError()
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)
268 EFI_FILE_HANDLE FileHandle
;
270 UINTN Size
= sizeof(Header
);
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().
279 Status
= refit_call5_wrapper(RootDir
->Open
, RootDir
, &FileHandle
, FileName
, EFI_FILE_MODE_READ
, 0);
280 if (EFI_ERROR(Status
))
283 Status
= refit_call3_wrapper(FileHandle
->Read
, FileHandle
, &Size
, Header
);
284 refit_call1_wrapper(FileHandle
->Close
, FileHandle
);
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
));
296 } // BOOLEAN IsValidLoader()
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
,
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
;
316 if (ErrorInStep
!= NULL
)
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...
327 } // if (LoadOptions != NULL)
329 Print(L
"Starting %s\nUsing load options '%s'\n", ImageTitle
, FullLoadOptions
? FullLoadOptions
: L
"");
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
"");
342 MyFreePool(FullLoadOptions
);
343 FullLoadOptions
= Temp
;
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
);
373 Print(L
"Invalid loader file!\n");
374 ReturnStatus
= EFI_LOAD_ERROR
;
376 if (ReturnStatus
!= EFI_NOT_FOUND
) {
380 if ((Status
== EFI_ACCESS_DENIED
) || (Status
== EFI_SECURITY_VIOLATION
)) {
381 WarnSecureBootError(ImageTitle
, Verbose
);
384 SPrint(ErrorInfo
, 255, L
"while loading %s", ImageTitle
);
385 if (CheckError(Status
, ErrorInfo
)) {
386 if (ErrorInStep
!= NULL
)
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
)
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!
403 // close open file handles
405 ReturnStatus
= Status
= refit_call3_wrapper(BS
->StartImage
, ChildImageHandle
, NULL
, NULL
);
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
)
414 ConnectFilesystemDriver(ChildImageHandle
);
416 // re-open file handles
420 // unload the image, we don't care if it works or not...
422 Status
= refit_call1_wrapper(BS
->UnloadImage
, ChildImageHandle
);
425 MyFreePool(FullLoadOptions
);
427 } /* EFI_STATUS StartEFIImageList() */
429 EFI_STATUS
StartEFIImage(IN EFI_DEVICE_PATH
*DevicePath
,
430 IN CHAR16
*LoadOptions
, IN UINTN LoaderType
,
431 IN CHAR16
*ImageTitle
, IN CHAR8 OSType
,
432 OUT UINTN
*ErrorInStep
,
436 EFI_DEVICE_PATH
*DevicePaths
[2];
438 DevicePaths
[0] = DevicePath
;
439 DevicePaths
[1] = NULL
;
440 return StartEFIImageList(DevicePaths
, LoadOptions
, LoaderType
, ImageTitle
, OSType
, ErrorInStep
, Verbose
, IsDriver
);
441 } /* static EFI_STATUS StartEFIImage() */
443 // From gummiboot: Reboot the computer into its built-in user interface
444 static EFI_STATUS
RebootIntoFirmware(VOID
) {
450 osind
= EFI_OS_INDICATIONS_BOOT_TO_FW_UI
;
452 err
= EfivarGetRaw(&GlobalGuid
, L
"OsIndications", &b
, &size
);
453 if (err
== EFI_SUCCESS
)
457 err
= EfivarSetRaw(&GlobalGuid
, L
"OsIndications", (CHAR8
*)&osind
, sizeof(UINT64
), TRUE
);
458 if (err
!= EFI_SUCCESS
)
461 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);
462 Print(L
"Error calling ResetSystem: %r", err
);
467 // Record the value of the loader's name/description in rEFInd's "PreviousBoot" EFI variable,
468 // if it's different from what's already stored there.
469 VOID
StoreLoaderName(IN CHAR16
*Name
) {
471 CHAR16
*OldName
= NULL
;
475 Status
= EfivarGetRaw(&RefindGuid
, L
"PreviousBoot", (CHAR8
**) &OldName
, &Length
);
476 if ((Status
!= EFI_SUCCESS
) || (StrCmp(OldName
, Name
) != 0)) {
477 EfivarSetRaw(&RefindGuid
, L
"PreviousBoot", (CHAR8
*) Name
, StrLen(Name
) * 2 + 2, TRUE
);
481 } // VOID StoreLoaderName()
484 // EFI OS loader functions
487 // See http://www.thomas-krenn.com/en/wiki/Activating_the_Intel_VT_Virtualization_Feature
488 // for information on Intel VMX features
489 static VOID
DoEnableAndLockVMX(VOID
)
491 #if defined (EFIX64) | defined (EFI32)
493 UINT32 low_bits
= 0, high_bits
= 0;
496 __asm__
volatile ("rdmsr" : "=a" (low_bits
), "=d" (high_bits
) : "c" (msr
));
498 // enable and lock vmx if not locked
499 if ((low_bits
& 1) == 0) {
503 __asm__
volatile ("wrmsr" : : "c" (msr
), "a" (low_bits
), "d" (high_bits
));
506 } // VOID DoEnableAndLockVMX()
508 static VOID
StartLoader(LOADER_ENTRY
*Entry
, CHAR16
*SelectionName
)
510 UINTN ErrorInStep
= 0;
512 if (GlobalConfig
.EnableAndLockVMX
) {
513 DoEnableAndLockVMX();
516 BeginExternalScreen(Entry
->UseGraphicsMode
, L
"Booting OS");
517 StoreLoaderName(SelectionName
);
518 StartEFIImage(Entry
->DevicePath
, Entry
->LoadOptions
, TYPE_EFI
,
519 Basename(Entry
->LoaderPath
), Entry
->OSType
, &ErrorInStep
, !Entry
->UseGraphicsMode
, FALSE
);
520 FinishExternalScreen();
523 // Locate an initrd or initramfs file that matches the kernel specified by LoaderPath.
524 // The matching file has a name that begins with "init" and includes the same version
525 // number string as is found in LoaderPath -- but not a longer version number string.
526 // For instance, if LoaderPath is \EFI\kernels\bzImage-3.3.0.efi, and if \EFI\kernels
527 // has a file called initramfs-3.3.0.img, this function will return the string
528 // '\EFI\kernels\initramfs-3.3.0.img'. If the directory ALSO contains the file
529 // initramfs-3.3.0-rc7.img or initramfs-13.3.0.img, those files will NOT match;
530 // however, initmine-3.3.0.img might match. (FindInitrd() returns the first match it
531 // finds.) Thus, care should be taken to avoid placing duplicate matching files in
532 // the kernel's directory.
533 // If no matching init file can be found, returns NULL.
534 static CHAR16
* FindInitrd(IN CHAR16
*LoaderPath
, IN REFIT_VOLUME
*Volume
) {
535 CHAR16
*InitrdName
= NULL
, *FileName
, *KernelVersion
, *InitrdVersion
, *Path
;
536 REFIT_DIR_ITER DirIter
;
537 EFI_FILE_INFO
*DirEntry
;
539 FileName
= Basename(LoaderPath
);
540 KernelVersion
= FindNumbers(FileName
);
541 Path
= FindPath(LoaderPath
);
543 // Add trailing backslash for root directory; necessary on some systems, but must
544 // NOT be added to all directories, since on other systems, a trailing backslash on
545 // anything but the root directory causes them to flake out!
546 if (StrLen(Path
) == 0) {
547 MergeStrings(&Path
, L
"\\", 0);
549 DirIterOpen(Volume
->RootDir
, Path
, &DirIter
);
550 // Now add a trailing backslash if it was NOT added earlier, for consistency in
551 // building the InitrdName later....
552 if ((StrLen(Path
) > 0) && (Path
[StrLen(Path
) - 1] != L
'\\'))
553 MergeStrings(&Path
, L
"\\", 0);
554 while ((DirIterNext(&DirIter
, 2, L
"init*", &DirEntry
)) && (InitrdName
== NULL
)) {
555 InitrdVersion
= FindNumbers(DirEntry
->FileName
);
556 if (KernelVersion
!= NULL
) {
557 if (MyStriCmp(InitrdVersion
, KernelVersion
)) {
558 InitrdName
= PoolPrint(L
"%s%s", Path
, DirEntry
->FileName
);
561 if (InitrdVersion
== NULL
) {
562 InitrdName
= PoolPrint(L
"%s%s", Path
, DirEntry
->FileName
);
565 MyFreePool(InitrdVersion
);
567 DirIterClose(&DirIter
);
569 // Note: Don't FreePool(FileName), since Basename returns a pointer WITHIN the string it's passed.
570 MyFreePool(KernelVersion
);
573 } // static CHAR16 * FindInitrd()
575 LOADER_ENTRY
* AddPreparedLoaderEntry(LOADER_ENTRY
*Entry
) {
576 AddMenuEntry(&MainMenu
, (REFIT_MENU_ENTRY
*)Entry
);
579 } // LOADER_ENTRY * AddPreparedLoaderEntry()
581 // Creates a copy of a menu screen.
582 // Returns a pointer to the copy of the menu screen.
583 static REFIT_MENU_SCREEN
* CopyMenuScreen(REFIT_MENU_SCREEN
*Entry
) {
584 REFIT_MENU_SCREEN
*NewEntry
;
587 NewEntry
= AllocateZeroPool(sizeof(REFIT_MENU_SCREEN
));
588 if ((Entry
!= NULL
) && (NewEntry
!= NULL
)) {
589 CopyMem(NewEntry
, Entry
, sizeof(REFIT_MENU_SCREEN
));
590 NewEntry
->Title
= (Entry
->Title
) ? StrDuplicate(Entry
->Title
) : NULL
;
591 NewEntry
->TimeoutText
= (Entry
->TimeoutText
) ? StrDuplicate(Entry
->TimeoutText
) : NULL
;
592 if (Entry
->TitleImage
!= NULL
) {
593 NewEntry
->TitleImage
= AllocatePool(sizeof(EG_IMAGE
));
594 if (NewEntry
->TitleImage
!= NULL
)
595 CopyMem(NewEntry
->TitleImage
, Entry
->TitleImage
, sizeof(EG_IMAGE
));
597 NewEntry
->InfoLines
= (CHAR16
**) AllocateZeroPool(Entry
->InfoLineCount
* (sizeof(CHAR16
*)));
598 for (i
= 0; i
< Entry
->InfoLineCount
&& NewEntry
->InfoLines
; i
++) {
599 NewEntry
->InfoLines
[i
] = (Entry
->InfoLines
[i
]) ? StrDuplicate(Entry
->InfoLines
[i
]) : NULL
;
601 NewEntry
->Entries
= (REFIT_MENU_ENTRY
**) AllocateZeroPool(Entry
->EntryCount
* (sizeof (REFIT_MENU_ENTRY
*)));
602 for (i
= 0; i
< Entry
->EntryCount
&& NewEntry
->Entries
; i
++) {
603 AddMenuEntry(NewEntry
, Entry
->Entries
[i
]);
605 NewEntry
->Hint1
= (Entry
->Hint1
) ? StrDuplicate(Entry
->Hint1
) : NULL
;
606 NewEntry
->Hint2
= (Entry
->Hint2
) ? StrDuplicate(Entry
->Hint2
) : NULL
;
609 } // static REFIT_MENU_SCREEN* CopyMenuScreen()
611 // Creates a copy of a menu entry. Intended to enable moving a stack-based
612 // menu entry (such as the ones for the "reboot" and "exit" functions) to
613 // to the heap. This enables easier deletion of the whole set of menu
614 // entries when re-scanning.
615 // Returns a pointer to the copy of the menu entry.
616 static REFIT_MENU_ENTRY
* CopyMenuEntry(REFIT_MENU_ENTRY
*Entry
) {
617 REFIT_MENU_ENTRY
*NewEntry
;
619 NewEntry
= AllocateZeroPool(sizeof(REFIT_MENU_ENTRY
));
620 if ((Entry
!= NULL
) && (NewEntry
!= NULL
)) {
621 CopyMem(NewEntry
, Entry
, sizeof(REFIT_MENU_ENTRY
));
622 NewEntry
->Title
= (Entry
->Title
) ? StrDuplicate(Entry
->Title
) : NULL
;
623 if (Entry
->BadgeImage
!= NULL
) {
624 NewEntry
->BadgeImage
= AllocatePool(sizeof(EG_IMAGE
));
625 if (NewEntry
->BadgeImage
!= NULL
)
626 CopyMem(NewEntry
->BadgeImage
, Entry
->BadgeImage
, sizeof(EG_IMAGE
));
628 if (Entry
->Image
!= NULL
) {
629 NewEntry
->Image
= AllocatePool(sizeof(EG_IMAGE
));
630 if (NewEntry
->Image
!= NULL
)
631 CopyMem(NewEntry
->Image
, Entry
->Image
, sizeof(EG_IMAGE
));
633 if (Entry
->SubScreen
!= NULL
) {
634 NewEntry
->SubScreen
= CopyMenuScreen(Entry
->SubScreen
);
638 } // REFIT_MENU_ENTRY* CopyMenuEntry()
640 // Creates a new LOADER_ENTRY data structure and populates it with
641 // default values from the specified Entry, or NULL values if Entry
642 // is unspecified (NULL).
643 // Returns a pointer to the new data structure, or NULL if it
644 // couldn't be allocated
645 LOADER_ENTRY
*InitializeLoaderEntry(IN LOADER_ENTRY
*Entry
) {
646 LOADER_ENTRY
*NewEntry
= NULL
;
648 NewEntry
= AllocateZeroPool(sizeof(LOADER_ENTRY
));
649 if (NewEntry
!= NULL
) {
650 NewEntry
->me
.Title
= NULL
;
651 NewEntry
->me
.Tag
= TAG_LOADER
;
652 NewEntry
->Enabled
= TRUE
;
653 NewEntry
->UseGraphicsMode
= FALSE
;
654 NewEntry
->OSType
= 0;
656 NewEntry
->LoaderPath
= (Entry
->LoaderPath
) ? StrDuplicate(Entry
->LoaderPath
) : NULL
;
657 NewEntry
->VolName
= (Entry
->VolName
) ? StrDuplicate(Entry
->VolName
) : NULL
;
658 NewEntry
->DevicePath
= Entry
->DevicePath
;
659 NewEntry
->UseGraphicsMode
= Entry
->UseGraphicsMode
;
660 NewEntry
->LoadOptions
= (Entry
->LoadOptions
) ? StrDuplicate(Entry
->LoadOptions
) : NULL
;
661 NewEntry
->InitrdPath
= (Entry
->InitrdPath
) ? StrDuplicate(Entry
->InitrdPath
) : NULL
;
665 } // LOADER_ENTRY *InitializeLoaderEntry()
667 // Adds InitrdPath to Options, but only if Options doesn't already include an
668 // initrd= line. Done to enable overriding the default initrd selection in a
669 // refind_linux.conf file's options list.
670 // Returns a pointer to a new string. The calling function is responsible for
671 // freeing its memory.
672 static CHAR16
*AddInitrdToOptions(CHAR16
*Options
, CHAR16
*InitrdPath
) {
673 CHAR16
*NewOptions
= NULL
;
676 NewOptions
= StrDuplicate(Options
);
677 if ((InitrdPath
!= NULL
) && !StriSubCmp(L
"initrd=", Options
)) {
678 MergeStrings(&NewOptions
, L
"initrd=", L
' ');
679 MergeStrings(&NewOptions
, InitrdPath
, 0);
682 } // CHAR16 *AddInitrdToOptions()
684 // Prepare a REFIT_MENU_SCREEN data structure for a subscreen entry. This sets up
685 // the default entry that launches the boot loader using the same options as the
686 // main Entry does. Subsequent options can be added by the calling function.
687 // If a subscreen already exists in the Entry that's passed to this function,
688 // it's left unchanged and a pointer to it is returned.
689 // Returns a pointer to the new subscreen data structure, or NULL if there
690 // were problems allocating memory.
691 REFIT_MENU_SCREEN
*InitializeSubScreen(IN LOADER_ENTRY
*Entry
) {
692 CHAR16
*FileName
, *MainOptions
= NULL
;
693 REFIT_MENU_SCREEN
*SubScreen
= NULL
;
694 LOADER_ENTRY
*SubEntry
;
696 FileName
= Basename(Entry
->LoaderPath
);
697 if (Entry
->me
.SubScreen
== NULL
) { // No subscreen yet; initialize default entry....
698 SubScreen
= AllocateZeroPool(sizeof(REFIT_MENU_SCREEN
));
699 if (SubScreen
!= NULL
) {
700 SubScreen
->Title
= AllocateZeroPool(sizeof(CHAR16
) * 256);
701 SPrint(SubScreen
->Title
, 255, L
"Boot Options for %s on %s",
702 (Entry
->Title
!= NULL
) ? Entry
->Title
: FileName
, Entry
->VolName
);
703 SubScreen
->TitleImage
= Entry
->me
.Image
;
705 SubEntry
= InitializeLoaderEntry(Entry
);
706 if (SubEntry
!= NULL
) {
707 SubEntry
->me
.Title
= StrDuplicate(L
"Boot using default options");
708 MainOptions
= SubEntry
->LoadOptions
;
709 SubEntry
->LoadOptions
= AddInitrdToOptions(MainOptions
, SubEntry
->InitrdPath
);
710 MyFreePool(MainOptions
);
711 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
712 } // if (SubEntry != NULL)
713 SubScreen
->Hint1
= StrDuplicate(SUBSCREEN_HINT1
);
714 if (GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_EDITOR
) {
715 SubScreen
->Hint2
= StrDuplicate(SUBSCREEN_HINT2_NO_EDITOR
);
717 SubScreen
->Hint2
= StrDuplicate(SUBSCREEN_HINT2
);
719 } // if (SubScreen != NULL)
720 } else { // existing subscreen; less initialization, and just add new entry later....
721 SubScreen
= Entry
->me
.SubScreen
;
724 } // REFIT_MENU_SCREEN *InitializeSubScreen()
726 VOID
GenerateSubScreen(LOADER_ENTRY
*Entry
, IN REFIT_VOLUME
*Volume
, IN BOOLEAN GenerateReturn
) {
727 REFIT_MENU_SCREEN
*SubScreen
;
728 LOADER_ENTRY
*SubEntry
;
730 CHAR16 DiagsFileName
[256];
735 // create the submenu
736 if (StrLen(Entry
->Title
) == 0) {
737 MyFreePool(Entry
->Title
);
740 SubScreen
= InitializeSubScreen(Entry
);
742 // loader-specific submenu entries
743 if (Entry
->OSType
== 'M') { // entries for Mac OS X
745 SubEntry
= InitializeLoaderEntry(Entry
);
746 if (SubEntry
!= NULL
) {
747 SubEntry
->me
.Title
= L
"Boot Mac OS X with a 64-bit kernel";
748 SubEntry
->LoadOptions
= L
"arch=x86_64";
749 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
750 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
753 SubEntry
= InitializeLoaderEntry(Entry
);
754 if (SubEntry
!= NULL
) {
755 SubEntry
->me
.Title
= L
"Boot Mac OS X with a 32-bit kernel";
756 SubEntry
->LoadOptions
= L
"arch=i386";
757 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
758 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
762 if (!(GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_SINGLEUSER
)) {
763 SubEntry
= InitializeLoaderEntry(Entry
);
764 if (SubEntry
!= NULL
) {
765 SubEntry
->me
.Title
= L
"Boot Mac OS X in verbose mode";
766 SubEntry
->UseGraphicsMode
= FALSE
;
767 SubEntry
->LoadOptions
= L
"-v";
768 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
772 SubEntry
= InitializeLoaderEntry(Entry
);
773 if (SubEntry
!= NULL
) {
774 SubEntry
->me
.Title
= L
"Boot Mac OS X in verbose mode (64-bit)";
775 SubEntry
->UseGraphicsMode
= FALSE
;
776 SubEntry
->LoadOptions
= L
"-v arch=x86_64";
777 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
780 SubEntry
= InitializeLoaderEntry(Entry
);
781 if (SubEntry
!= NULL
) {
782 SubEntry
->me
.Title
= L
"Boot Mac OS X in verbose mode (32-bit)";
783 SubEntry
->UseGraphicsMode
= FALSE
;
784 SubEntry
->LoadOptions
= L
"-v arch=i386";
785 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
789 SubEntry
= InitializeLoaderEntry(Entry
);
790 if (SubEntry
!= NULL
) {
791 SubEntry
->me
.Title
= L
"Boot Mac OS X in single user mode";
792 SubEntry
->UseGraphicsMode
= FALSE
;
793 SubEntry
->LoadOptions
= L
"-v -s";
794 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
796 } // single-user mode allowed
798 if (!(GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_SAFEMODE
)) {
799 SubEntry
= InitializeLoaderEntry(Entry
);
800 if (SubEntry
!= NULL
) {
801 SubEntry
->me
.Title
= L
"Boot Mac OS X in safe mode";
802 SubEntry
->UseGraphicsMode
= FALSE
;
803 SubEntry
->LoadOptions
= L
"-v -x";
804 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
806 } // safe mode allowed
808 // check for Apple hardware diagnostics
809 StrCpy(DiagsFileName
, L
"System\\Library\\CoreServices\\.diagnostics\\diags.efi");
810 if (FileExists(Volume
->RootDir
, DiagsFileName
) && !(GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_HWTEST
)) {
811 SubEntry
= InitializeLoaderEntry(Entry
);
812 if (SubEntry
!= NULL
) {
813 SubEntry
->me
.Title
= L
"Run Apple Hardware Test";
814 MyFreePool(SubEntry
->LoaderPath
);
815 SubEntry
->LoaderPath
= StrDuplicate(DiagsFileName
);
816 SubEntry
->DevicePath
= FileDevicePath(Volume
->DeviceHandle
, SubEntry
->LoaderPath
);
817 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
818 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
820 } // if diagnostics entry found
822 } else if (Entry
->OSType
== 'L') { // entries for Linux kernels with EFI stub loaders
823 File
= ReadLinuxOptionsFile(Entry
->LoaderPath
, Volume
);
825 InitrdName
= FindInitrd(Entry
->LoaderPath
, Volume
);
826 TokenCount
= ReadTokenLine(File
, &TokenList
);
827 // first entry requires special processing, since it was initially set
828 // up with a default title but correct options by InitializeSubScreen(),
830 if ((TokenCount
> 1) && (SubScreen
->Entries
!= NULL
) && (SubScreen
->Entries
[0] != NULL
)) {
831 MyFreePool(SubScreen
->Entries
[0]->Title
);
832 SubScreen
->Entries
[0]->Title
= TokenList
[0] ? StrDuplicate(TokenList
[0]) : StrDuplicate(L
"Boot Linux");
834 FreeTokenLine(&TokenList
, &TokenCount
);
835 while ((TokenCount
= ReadTokenLine(File
, &TokenList
)) > 1) {
836 SubEntry
= InitializeLoaderEntry(Entry
);
837 SubEntry
->me
.Title
= TokenList
[0] ? StrDuplicate(TokenList
[0]) : StrDuplicate(L
"Boot Linux");
838 MyFreePool(SubEntry
->LoadOptions
);
839 SubEntry
->LoadOptions
= AddInitrdToOptions(TokenList
[1], InitrdName
);
840 FreeTokenLine(&TokenList
, &TokenCount
);
841 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_LINUX
;
842 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
844 MyFreePool(InitrdName
);
848 } else if (Entry
->OSType
== 'E') { // entries for ELILO
849 SubEntry
= InitializeLoaderEntry(Entry
);
850 if (SubEntry
!= NULL
) {
851 SubEntry
->me
.Title
= L
"Run ELILO in interactive mode";
852 SubEntry
->LoadOptions
= L
"-p";
853 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
854 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
857 SubEntry
= InitializeLoaderEntry(Entry
);
858 if (SubEntry
!= NULL
) {
859 SubEntry
->me
.Title
= L
"Boot Linux for a 17\" iMac or a 15\" MacBook Pro (*)";
860 SubEntry
->LoadOptions
= L
"-d 0 i17";
861 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
862 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
865 SubEntry
= InitializeLoaderEntry(Entry
);
866 if (SubEntry
!= NULL
) {
867 SubEntry
->me
.Title
= L
"Boot Linux for a 20\" iMac (*)";
868 SubEntry
->LoadOptions
= L
"-d 0 i20";
869 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
870 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
873 SubEntry
= InitializeLoaderEntry(Entry
);
874 if (SubEntry
!= NULL
) {
875 SubEntry
->me
.Title
= L
"Boot Linux for a Mac Mini (*)";
876 SubEntry
->LoadOptions
= L
"-d 0 mini";
877 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
878 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
881 AddMenuInfoLine(SubScreen
, L
"NOTE: This is an example. Entries");
882 AddMenuInfoLine(SubScreen
, L
"marked with (*) may not work.");
884 } else if (Entry
->OSType
== 'X') { // entries for xom.efi
885 // by default, skip the built-in selection and boot from hard disk only
886 Entry
->LoadOptions
= L
"-s -h";
888 SubEntry
= InitializeLoaderEntry(Entry
);
889 if (SubEntry
!= NULL
) {
890 SubEntry
->me
.Title
= L
"Boot Windows from Hard Disk";
891 SubEntry
->LoadOptions
= L
"-s -h";
892 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
893 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
896 SubEntry
= InitializeLoaderEntry(Entry
);
897 if (SubEntry
!= NULL
) {
898 SubEntry
->me
.Title
= L
"Boot Windows from CD-ROM";
899 SubEntry
->LoadOptions
= L
"-s -c";
900 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
901 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
904 SubEntry
= InitializeLoaderEntry(Entry
);
905 if (SubEntry
!= NULL
) {
906 SubEntry
->me
.Title
= L
"Run XOM in text mode";
907 SubEntry
->LoadOptions
= L
"-v";
908 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
909 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
911 } // entries for xom.efi
913 AddMenuEntry(SubScreen
, &MenuEntryReturn
);
914 Entry
->me
.SubScreen
= SubScreen
;
915 } // VOID GenerateSubScreen()
917 // Returns options for a Linux kernel. Reads them from an options file in the
918 // kernel's directory; and if present, adds an initrd= option for an initial
919 // RAM disk file with the same version number as the kernel file.
920 static CHAR16
* GetMainLinuxOptions(IN CHAR16
* LoaderPath
, IN REFIT_VOLUME
*Volume
) {
921 CHAR16
*Options
= NULL
, *InitrdName
, *FullOptions
= NULL
;
923 Options
= GetFirstOptionsFromFile(LoaderPath
, Volume
);
924 InitrdName
= FindInitrd(LoaderPath
, Volume
);
925 FullOptions
= AddInitrdToOptions(Options
, InitrdName
);
928 MyFreePool(InitrdName
);
929 return (FullOptions
);
930 } // static CHAR16 * GetMainLinuxOptions()
932 // Read the specified file and add values of "ID", "NAME", or "DISTRIB_ID" tokens to
933 // OSIconName list. Intended for adding Linux distribution clues gleaned from
934 // /etc/lsb-release and /etc/os-release files.
935 static VOID
ParseReleaseFile(CHAR16
**OSIconName
, REFIT_VOLUME
*Volume
, CHAR16
*FileName
) {
939 UINTN TokenCount
= 0;
941 if ((Volume
== NULL
) || (FileName
== NULL
) || (OSIconName
== NULL
) || (*OSIconName
== NULL
))
944 if (FileExists(Volume
->RootDir
, FileName
) &&
945 (ReadFile(Volume
->RootDir
, FileName
, &File
, &FileSize
) == EFI_SUCCESS
)) {
947 TokenCount
= ReadTokenLine(&File
, &TokenList
);
948 if ((TokenCount
> 1) && (MyStriCmp(TokenList
[0], L
"ID") ||
949 MyStriCmp(TokenList
[0], L
"NAME") ||
950 MyStriCmp(TokenList
[0], L
"DISTRIB_ID"))) {
951 MergeWords(OSIconName
, TokenList
[1], L
',');
953 FreeTokenLine(&TokenList
, &TokenCount
);
954 } while (TokenCount
> 0);
955 MyFreePool(File
.Buffer
);
957 } // VOID ParseReleaseFile()
959 // Try to guess the name of the Linux distribution & add that name to
961 static VOID
GuessLinuxDistribution(CHAR16
**OSIconName
, REFIT_VOLUME
*Volume
, CHAR16
*LoaderPath
) {
962 // If on Linux root fs, /etc/os-release or /etc/lsb-release file probably has clues....
963 ParseReleaseFile(OSIconName
, Volume
, L
"etc\\lsb-release");
964 ParseReleaseFile(OSIconName
, Volume
, L
"etc\\os-release");
966 // Search for clues in the kernel's filename....
967 if (StriSubCmp(L
".fc", LoaderPath
))
968 MergeStrings(OSIconName
, L
"fedora", L
',');
969 if (StriSubCmp(L
".el", LoaderPath
))
970 MergeStrings(OSIconName
, L
"redhat", L
',');
971 } // VOID GuessLinuxDistribution()
973 // Sets a few defaults for a loader entry -- mainly the icon, but also the OS type
974 // code and shortcut letter. For Linux EFI stub loaders, also sets kernel options
975 // that will (with luck) work fairly automatically.
976 VOID
SetLoaderDefaults(LOADER_ENTRY
*Entry
, CHAR16
*LoaderPath
, REFIT_VOLUME
*Volume
) {
977 CHAR16
*NameClues
, *PathOnly
, *NoExtension
, *OSIconName
= NULL
, *Temp
;
978 CHAR16 ShortcutLetter
= 0;
980 NameClues
= Basename(LoaderPath
);
981 PathOnly
= FindPath(LoaderPath
);
982 NoExtension
= StripEfiExtension(NameClues
);
984 if (Volume
->DiskKind
== DISK_KIND_NET
) {
985 MergeStrings(&NameClues
, Entry
->me
.Title
, L
' ');
987 // locate a custom icon for the loader
988 // Anything found here takes precedence over the "hints" in the OSIconName variable
989 if (!Entry
->me
.Image
) {
990 Entry
->me
.Image
= egLoadIconAnyType(Volume
->RootDir
, PathOnly
, NoExtension
, GlobalConfig
.IconSizes
[ICON_SIZE_BIG
]);
992 if (!Entry
->me
.Image
) {
993 Entry
->me
.Image
= egCopyImage(Volume
->VolIconImage
);
996 // Begin creating icon "hints" by using last part of directory path leading
998 Temp
= FindLastDirName(LoaderPath
);
999 MergeStrings(&OSIconName
, Temp
, L
',');
1002 if (OSIconName
!= NULL
) {
1003 ShortcutLetter
= OSIconName
[0];
1006 // Add every "word" in the volume label, delimited by spaces, dashes (-), or
1007 // underscores (_), to the list of hints to be used in searching for OS
1009 MergeWords(&OSIconName
, Volume
->VolName
, L
',');
1010 } // if/else network boot
1012 // detect specific loaders
1013 if (StriSubCmp(L
"bzImage", NameClues
) || StriSubCmp(L
"vmlinuz", NameClues
) || StriSubCmp(L
"kernel", NameClues
)) {
1014 if (Volume
->DiskKind
!= DISK_KIND_NET
) {
1015 GuessLinuxDistribution(&OSIconName
, Volume
, LoaderPath
);
1016 Entry
->LoadOptions
= GetMainLinuxOptions(LoaderPath
, Volume
);
1018 MergeStrings(&OSIconName
, L
"linux", L
',');
1019 Entry
->OSType
= 'L';
1020 if (ShortcutLetter
== 0)
1021 ShortcutLetter
= 'L';
1022 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_LINUX
;
1023 } else if (StriSubCmp(L
"refit", LoaderPath
)) {
1024 MergeStrings(&OSIconName
, L
"refit", L
',');
1025 Entry
->OSType
= 'R';
1026 ShortcutLetter
= 'R';
1027 } else if (StriSubCmp(L
"refind", LoaderPath
)) {
1028 MergeStrings(&OSIconName
, L
"refind", L
',');
1029 Entry
->OSType
= 'R';
1030 ShortcutLetter
= 'R';
1031 } else if (MyStriCmp(LoaderPath
, MACOSX_LOADER_PATH
)) {
1032 MergeStrings(&OSIconName
, L
"mac", L
',');
1033 Entry
->OSType
= 'M';
1034 ShortcutLetter
= 'M';
1035 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
1036 } else if (MyStriCmp(NameClues
, L
"diags.efi")) {
1037 MergeStrings(&OSIconName
, L
"hwtest", L
',');
1038 } else if (MyStriCmp(NameClues
, L
"e.efi") || MyStriCmp(NameClues
, L
"elilo.efi") || StriSubCmp(L
"elilo", NameClues
)) {
1039 MergeStrings(&OSIconName
, L
"elilo,linux", L
',');
1040 Entry
->OSType
= 'E';
1041 if (ShortcutLetter
== 0)
1042 ShortcutLetter
= 'L';
1043 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
1044 } else if (StriSubCmp(L
"grub", NameClues
)) {
1045 MergeStrings(&OSIconName
, L
"grub,linux", L
',');
1046 Entry
->OSType
= 'G';
1047 ShortcutLetter
= 'G';
1048 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_GRUB
;
1049 } else if (MyStriCmp(NameClues
, L
"cdboot.efi") ||
1050 MyStriCmp(NameClues
, L
"bootmgr.efi") ||
1051 MyStriCmp(NameClues
, L
"bootmgfw.efi") ||
1052 MyStriCmp(NameClues
, L
"bkpbootmgfw.efi")) {
1053 MergeStrings(&OSIconName
, L
"win8", L
',');
1054 Entry
->OSType
= 'W';
1055 ShortcutLetter
= 'W';
1056 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
1057 } else if (MyStriCmp(NameClues
, L
"xom.efi")) {
1058 MergeStrings(&OSIconName
, L
"xom,win,win8", L
',');
1059 Entry
->OSType
= 'X';
1060 ShortcutLetter
= 'W';
1061 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
1063 else if (StriSubCmp(L
"ipxe", NameClues
)) {
1064 Entry
->OSType
= 'N';
1065 ShortcutLetter
= 'N';
1066 MergeStrings(&OSIconName
, L
"network", L
',');
1069 if ((ShortcutLetter
>= 'a') && (ShortcutLetter
<= 'z'))
1070 ShortcutLetter
= ShortcutLetter
- 'a' + 'A'; // convert lowercase to uppercase
1071 Entry
->me
.ShortcutLetter
= ShortcutLetter
;
1072 if (Entry
->me
.Image
== NULL
)
1073 Entry
->me
.Image
= LoadOSIcon(OSIconName
, L
"unknown", FALSE
);
1074 MyFreePool(PathOnly
);
1075 } // VOID SetLoaderDefaults()
1077 // Add a specified EFI boot loader to the list, using automatic settings
1078 // for icons, options, etc.
1079 static LOADER_ENTRY
* AddLoaderEntry(IN CHAR16
*LoaderPath
, IN CHAR16
*LoaderTitle
, IN REFIT_VOLUME
*Volume
, IN BOOLEAN SubScreenReturn
) {
1080 LOADER_ENTRY
*Entry
;
1082 CleanUpPathNameSlashes(LoaderPath
);
1083 Entry
= InitializeLoaderEntry(NULL
);
1084 if (Entry
!= NULL
) {
1085 Entry
->Title
= StrDuplicate((LoaderTitle
!= NULL
) ? LoaderTitle
: LoaderPath
);
1086 Entry
->me
.Title
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1087 // Extra space at end of Entry->me.Title enables searching on Volume->VolName even if another volume
1088 // name is identical except for something added to the end (e.g., VolB1 vs. VolB12).
1089 // Note: Volume->VolName will be NULL for network boot programs.
1090 if (Volume
->VolName
)
1091 SPrint(Entry
->me
.Title
, 255, L
"Boot %s from %s ", (LoaderTitle
!= NULL
) ? LoaderTitle
: LoaderPath
, Volume
->VolName
);
1093 SPrint(Entry
->me
.Title
, 255, L
"Boot %s ", (LoaderTitle
!= NULL
) ? LoaderTitle
: LoaderPath
);
1095 Entry
->me
.BadgeImage
= Volume
->VolBadgeImage
;
1096 if ((LoaderPath
!= NULL
) && (LoaderPath
[0] != L
'\\')) {
1097 Entry
->LoaderPath
= StrDuplicate(L
"\\");
1099 Entry
->LoaderPath
= NULL
;
1101 MergeStrings(&(Entry
->LoaderPath
), LoaderPath
, 0);
1102 Entry
->VolName
= Volume
->VolName
;
1103 Entry
->DevicePath
= FileDevicePath(Volume
->DeviceHandle
, Entry
->LoaderPath
);
1104 SetLoaderDefaults(Entry
, LoaderPath
, Volume
);
1105 GenerateSubScreen(Entry
, Volume
, SubScreenReturn
);
1106 AddMenuEntry(&MainMenu
, (REFIT_MENU_ENTRY
*)Entry
);
1110 } // LOADER_ENTRY * AddLoaderEntry()
1112 // Add a Linux kernel as a submenu entry for another (pre-existing) Linux kernel entry.
1113 static VOID
AddKernelToSubmenu(LOADER_ENTRY
* TargetLoader
, CHAR16
*FileName
, REFIT_VOLUME
*Volume
) {
1115 CHAR16
**TokenList
= NULL
, *InitrdName
, *SubmenuName
= NULL
, *VolName
= NULL
, *Path
= NULL
, *Title
;
1116 REFIT_MENU_SCREEN
*SubScreen
;
1117 LOADER_ENTRY
*SubEntry
;
1120 File
= ReadLinuxOptionsFile(TargetLoader
->LoaderPath
, Volume
);
1122 SubScreen
= TargetLoader
->me
.SubScreen
;
1123 InitrdName
= FindInitrd(FileName
, Volume
);
1124 while ((TokenCount
= ReadTokenLine(File
, &TokenList
)) > 1) {
1125 SubEntry
= InitializeLoaderEntry(TargetLoader
);
1126 SplitPathName(FileName
, &VolName
, &Path
, &SubmenuName
);
1127 MergeStrings(&SubmenuName
, L
": ", '\0');
1128 MergeStrings(&SubmenuName
, TokenList
[0] ? StrDuplicate(TokenList
[0]) : StrDuplicate(L
"Boot Linux"), '\0');
1129 Title
= StrDuplicate(SubmenuName
);
1130 LimitStringLength(Title
, MAX_LINE_LENGTH
);
1131 SubEntry
->me
.Title
= Title
;
1132 MyFreePool(SubEntry
->LoadOptions
);
1133 SubEntry
->LoadOptions
= AddInitrdToOptions(TokenList
[1], InitrdName
);
1134 MyFreePool(SubEntry
->LoaderPath
);
1135 SubEntry
->LoaderPath
= StrDuplicate(FileName
);
1136 CleanUpPathNameSlashes(SubEntry
->LoaderPath
);
1137 SubEntry
->DevicePath
= FileDevicePath(Volume
->DeviceHandle
, SubEntry
->LoaderPath
);
1138 FreeTokenLine(&TokenList
, &TokenCount
);
1139 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_LINUX
;
1140 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
1142 MyFreePool(VolName
);
1144 MyFreePool(SubmenuName
);
1145 MyFreePool(InitrdName
);
1148 } // static VOID AddKernelToSubmenu()
1150 // Returns -1 if (Time1 < Time2), +1 if (Time1 > Time2), or 0 if
1151 // (Time1 == Time2). Precision is only to the nearest second; since
1152 // this is used for sorting boot loader entries, differences smaller
1153 // than this are likely to be meaningless (and unlikely!).
1154 INTN
TimeComp(IN EFI_TIME
*Time1
, IN EFI_TIME
*Time2
) {
1155 INT64 Time1InSeconds
, Time2InSeconds
;
1157 // Following values are overestimates; I'm assuming 31 days in every month.
1158 // This is fine for the purpose of this function, which is limited
1159 Time1InSeconds
= Time1
->Second
+ (Time1
->Minute
* 60) + (Time1
->Hour
* 3600) + (Time1
->Day
* 86400) +
1160 (Time1
->Month
* 2678400) + ((Time1
->Year
- 1998) * 32140800);
1161 Time2InSeconds
= Time2
->Second
+ (Time2
->Minute
* 60) + (Time2
->Hour
* 3600) + (Time2
->Day
* 86400) +
1162 (Time2
->Month
* 2678400) + ((Time2
->Year
- 1998) * 32140800);
1163 if (Time1InSeconds
< Time2InSeconds
)
1165 else if (Time1InSeconds
> Time2InSeconds
)
1169 } // INTN TimeComp()
1171 // Adds a loader list element, keeping it sorted by date. EXCEPTION: Fedora's rescue
1172 // kernel, which begins with "vmlinuz-0-rescue," should not be at the top of the list,
1173 // since that will make it the default if kernel folding is enabled, so float it to
1175 // Returns the new first element (the one with the most recent date).
1176 static struct LOADER_LIST
* AddLoaderListEntry(struct LOADER_LIST
*LoaderList
, struct LOADER_LIST
*NewEntry
) {
1177 struct LOADER_LIST
*LatestEntry
, *CurrentEntry
, *PrevEntry
= NULL
;
1178 BOOLEAN LinuxRescue
= FALSE
;
1180 LatestEntry
= CurrentEntry
= LoaderList
;
1181 if (LoaderList
== NULL
) {
1182 LatestEntry
= NewEntry
;
1184 if (StriSubCmp(L
"vmlinuz-0-rescue", NewEntry
->FileName
))
1186 while ((CurrentEntry
!= NULL
) && (LinuxRescue
|| (TimeComp(&(NewEntry
->TimeStamp
), &(CurrentEntry
->TimeStamp
)) < 0))) {
1187 PrevEntry
= CurrentEntry
;
1188 CurrentEntry
= CurrentEntry
->NextEntry
;
1190 NewEntry
->NextEntry
= CurrentEntry
;
1191 if (PrevEntry
== NULL
) {
1192 LatestEntry
= NewEntry
;
1194 PrevEntry
->NextEntry
= NewEntry
;
1197 return (LatestEntry
);
1198 } // static VOID AddLoaderListEntry()
1200 // Delete the LOADER_LIST linked list
1201 static VOID
CleanUpLoaderList(struct LOADER_LIST
*LoaderList
) {
1202 struct LOADER_LIST
*Temp
;
1204 while (LoaderList
!= NULL
) {
1206 LoaderList
= LoaderList
->NextEntry
;
1207 MyFreePool(Temp
->FileName
);
1210 } // static VOID CleanUpLoaderList()
1212 // Returns FALSE if the specified file/volume matches the GlobalConfig.DontScanDirs
1213 // or GlobalConfig.DontScanVolumes specification, or if Path points to a volume
1214 // other than the one specified by Volume, or if the specified path is SelfDir.
1215 // Returns TRUE if none of these conditions is met -- that is, if the path is
1216 // eligible for scanning.
1217 static BOOLEAN
ShouldScan(REFIT_VOLUME
*Volume
, CHAR16
*Path
) {
1218 CHAR16
*VolName
= NULL
, *DontScanDir
, *PathCopy
= NULL
;
1220 BOOLEAN ScanIt
= TRUE
;
1222 if ((IsIn(Volume
->VolName
, GlobalConfig
.DontScanVolumes
)) || (IsIn(Volume
->PartName
, GlobalConfig
.DontScanVolumes
)))
1225 if (MyStriCmp(Path
, SelfDirPath
) && (Volume
->DeviceHandle
== SelfVolume
->DeviceHandle
))
1228 // See if Path includes an explicit volume declaration that's NOT Volume....
1229 PathCopy
= StrDuplicate(Path
);
1230 if (SplitVolumeAndFilename(&PathCopy
, &VolName
)) {
1231 VolumeNumberToName(Volume
, &VolName
);
1232 if (VolName
&& !MyStriCmp(VolName
, Volume
->VolName
)) {
1235 } // if Path includes volume specification
1236 MyFreePool(PathCopy
);
1237 MyFreePool(VolName
);
1240 // See if Volume is in GlobalConfig.DontScanDirs....
1241 while (ScanIt
&& (DontScanDir
= FindCommaDelimited(GlobalConfig
.DontScanDirs
, i
++))) {
1242 SplitVolumeAndFilename(&DontScanDir
, &VolName
);
1243 CleanUpPathNameSlashes(DontScanDir
);
1244 VolumeNumberToName(Volume
, &VolName
);
1245 if (VolName
!= NULL
) {
1246 if (MyStriCmp(VolName
, Volume
->VolName
) && MyStriCmp(DontScanDir
, Path
))
1249 if (MyStriCmp(DontScanDir
, Path
))
1252 MyFreePool(DontScanDir
);
1253 MyFreePool(VolName
);
1259 } // BOOLEAN ShouldScan()
1261 // Returns TRUE if the file is byte-for-byte identical with the fallback file
1262 // on the volume AND if the file is not itself the fallback file; returns
1263 // FALSE if the file is not identical to the fallback file OR if the file
1264 // IS the fallback file. Intended for use in excluding the fallback boot
1265 // loader when it's a duplicate of another boot loader.
1266 static BOOLEAN
DuplicatesFallback(IN REFIT_VOLUME
*Volume
, IN CHAR16
*FileName
) {
1267 CHAR8
*FileContents
, *FallbackContents
;
1268 EFI_FILE_HANDLE FileHandle
, FallbackHandle
;
1269 EFI_FILE_INFO
*FileInfo
, *FallbackInfo
;
1270 UINTN FileSize
= 0, FallbackSize
= 0;
1272 BOOLEAN AreIdentical
= FALSE
;
1274 if (!FileExists(Volume
->RootDir
, FileName
) || !FileExists(Volume
->RootDir
, FALLBACK_FULLNAME
))
1277 CleanUpPathNameSlashes(FileName
);
1279 if (MyStriCmp(FileName
, FALLBACK_FULLNAME
))
1280 return FALSE
; // identical filenames, so not a duplicate....
1282 Status
= refit_call5_wrapper(Volume
->RootDir
->Open
, Volume
->RootDir
, &FileHandle
, FileName
, EFI_FILE_MODE_READ
, 0);
1283 if (Status
== EFI_SUCCESS
) {
1284 FileInfo
= LibFileInfo(FileHandle
);
1285 FileSize
= FileInfo
->FileSize
;
1290 Status
= refit_call5_wrapper(Volume
->RootDir
->Open
, Volume
->RootDir
, &FallbackHandle
, FALLBACK_FULLNAME
, EFI_FILE_MODE_READ
, 0);
1291 if (Status
== EFI_SUCCESS
) {
1292 FallbackInfo
= LibFileInfo(FallbackHandle
);
1293 FallbackSize
= FallbackInfo
->FileSize
;
1295 refit_call1_wrapper(FileHandle
->Close
, FileHandle
);
1299 if (FallbackSize
!= FileSize
) { // not same size, so can't be identical
1300 AreIdentical
= FALSE
;
1301 } else { // could be identical; do full check....
1302 FileContents
= AllocatePool(FileSize
);
1303 FallbackContents
= AllocatePool(FallbackSize
);
1304 if (FileContents
&& FallbackContents
) {
1305 Status
= refit_call3_wrapper(FileHandle
->Read
, FileHandle
, &FileSize
, FileContents
);
1306 if (Status
== EFI_SUCCESS
) {
1307 Status
= refit_call3_wrapper(FallbackHandle
->Read
, FallbackHandle
, &FallbackSize
, FallbackContents
);
1309 if (Status
== EFI_SUCCESS
) {
1310 AreIdentical
= (CompareMem(FileContents
, FallbackContents
, FileSize
) == 0);
1313 MyFreePool(FileContents
);
1314 MyFreePool(FallbackContents
);
1317 // BUG ALERT: Some systems (e.g., DUET, some Macs with large displays) crash if the
1318 // following two calls are reversed. Go figure....
1319 refit_call1_wrapper(FileHandle
->Close
, FallbackHandle
);
1320 refit_call1_wrapper(FileHandle
->Close
, FileHandle
);
1321 return AreIdentical
;
1322 } // BOOLEAN DuplicatesFallback()
1324 // Returns FALSE if two measures of file size are identical for a single file,
1325 // TRUE if not or if the file can't be opened and the other measure is non-0.
1326 // Despite the function's name, this isn't really a direct test of symbolic
1327 // link status, since EFI doesn't officially support symlinks. It does seem
1328 // to be a reliable indicator, though. (OTOH, some disk errors might cause a
1329 // file to fail to open, which would return a false positive -- but as I use
1330 // this function to exclude symbolic links from the list of boot loaders,
1331 // that would be fine, since such boot loaders wouldn't work.)
1332 static BOOLEAN
IsSymbolicLink(REFIT_VOLUME
*Volume
, CHAR16
*Path
, EFI_FILE_INFO
*DirEntry
) {
1333 EFI_FILE_HANDLE FileHandle
;
1334 EFI_FILE_INFO
*FileInfo
= NULL
;
1336 UINTN FileSize2
= 0;
1339 FileName
= StrDuplicate(Path
);
1340 MergeStrings(&FileName
, DirEntry
->FileName
, L
'\\');
1341 CleanUpPathNameSlashes(FileName
);
1343 Status
= refit_call5_wrapper(Volume
->RootDir
->Open
, Volume
->RootDir
, &FileHandle
, FileName
, EFI_FILE_MODE_READ
, 0);
1344 if (Status
== EFI_SUCCESS
) {
1345 FileInfo
= LibFileInfo(FileHandle
);
1346 if (FileInfo
!= NULL
)
1347 FileSize2
= FileInfo
->FileSize
;
1350 MyFreePool(FileName
);
1351 MyFreePool(FileInfo
);
1353 return (DirEntry
->FileSize
!= FileSize2
);
1354 } // BOOLEAN IsSymbolicLink()
1356 // Returns TRUE if a file with the same name as the original but with
1357 // ".efi.signed" is also present in the same directory. Ubuntu is using
1358 // this filename as a signed version of the original unsigned kernel, and
1359 // there's no point in cluttering the display with two kernels that will
1360 // behave identically on non-SB systems, or when one will fail when SB
1362 static BOOLEAN
HasSignedCounterpart(IN REFIT_VOLUME
*Volume
, IN CHAR16
*Path
, IN CHAR16
*Filename
) {
1363 CHAR16
*NewFile
= NULL
;
1364 BOOLEAN retval
= FALSE
;
1366 MergeStrings(&NewFile
, Path
, 0);
1367 MergeStrings(&NewFile
, Filename
, L
'\\');
1368 MergeStrings(&NewFile
, L
".efi.signed", 0);
1369 if (NewFile
!= NULL
) {
1370 CleanUpPathNameSlashes(NewFile
);
1371 if (FileExists(Volume
->RootDir
, NewFile
))
1373 MyFreePool(NewFile
);
1377 } // BOOLEAN HasSignedCounterpart()
1379 // Scan an individual directory for EFI boot loader files and, if found,
1380 // add them to the list. Exception: Ignores FALLBACK_FULLNAME, which is picked
1381 // up in ScanEfiFiles(). Sorts the entries within the loader directory so that
1382 // the most recent one appears first in the list.
1383 // Returns TRUE if a duplicate for FALLBACK_FILENAME was found, FALSE if not.
1384 static BOOLEAN
ScanLoaderDir(IN REFIT_VOLUME
*Volume
, IN CHAR16
*Path
, IN CHAR16
*Pattern
)
1387 REFIT_DIR_ITER DirIter
;
1388 EFI_FILE_INFO
*DirEntry
;
1389 CHAR16 FileName
[256], *Extension
;
1390 struct LOADER_LIST
*LoaderList
= NULL
, *NewLoader
;
1391 LOADER_ENTRY
*FirstKernel
= NULL
, *LatestEntry
= NULL
;
1392 BOOLEAN FoundFallbackDuplicate
= FALSE
, IsLinux
= FALSE
, InSelfPath
;
1394 InSelfPath
= MyStriCmp(Path
, SelfDirPath
);
1395 if ((!SelfDirPath
|| !Path
|| (InSelfPath
&& (Volume
->DeviceHandle
!= SelfVolume
->DeviceHandle
)) ||
1396 (!InSelfPath
)) && (ShouldScan(Volume
, Path
))) {
1397 // look through contents of the directory
1398 DirIterOpen(Volume
->RootDir
, Path
, &DirIter
);
1399 while (DirIterNext(&DirIter
, 2, Pattern
, &DirEntry
)) {
1400 Extension
= FindExtension(DirEntry
->FileName
);
1401 if (DirEntry
->FileName
[0] == '.' ||
1402 MyStriCmp(Extension
, L
".icns") ||
1403 MyStriCmp(Extension
, L
".png") ||
1404 (MyStriCmp(DirEntry
->FileName
, FALLBACK_BASENAME
) && (MyStriCmp(Path
, L
"EFI\\BOOT"))) ||
1405 StriSubCmp(L
"shell", DirEntry
->FileName
) ||
1406 IsSymbolicLink(Volume
, Path
, DirEntry
) || /* is symbolic link */
1407 HasSignedCounterpart(Volume
, Path
, DirEntry
->FileName
) || /* a file with same name plus ".efi.signed" is present */
1408 FilenameIn(Volume
, Path
, DirEntry
->FileName
, GlobalConfig
.DontScanFiles
))
1409 continue; // skip this
1412 SPrint(FileName
, 255, L
"\\%s\\%s", Path
, DirEntry
->FileName
);
1414 SPrint(FileName
, 255, L
"\\%s", DirEntry
->FileName
);
1415 CleanUpPathNameSlashes(FileName
);
1417 if(!IsValidLoader(Volume
->RootDir
, FileName
))
1420 NewLoader
= AllocateZeroPool(sizeof(struct LOADER_LIST
));
1421 if (NewLoader
!= NULL
) {
1422 NewLoader
->FileName
= StrDuplicate(FileName
);
1423 NewLoader
->TimeStamp
= DirEntry
->ModificationTime
;
1424 LoaderList
= AddLoaderListEntry(LoaderList
, NewLoader
);
1425 if (DuplicatesFallback(Volume
, FileName
))
1426 FoundFallbackDuplicate
= TRUE
;
1428 MyFreePool(Extension
);
1431 NewLoader
= LoaderList
;
1432 while (NewLoader
!= NULL
) {
1433 IsLinux
= (StriSubCmp(L
"bzImage", NewLoader
->FileName
) ||
1434 StriSubCmp(L
"vmlinuz", NewLoader
->FileName
) ||
1435 StriSubCmp(L
"kernel", NewLoader
->FileName
));
1436 if ((FirstKernel
!= NULL
) && IsLinux
&& GlobalConfig
.FoldLinuxKernels
) {
1437 AddKernelToSubmenu(FirstKernel
, NewLoader
->FileName
, Volume
);
1439 LatestEntry
= AddLoaderEntry(NewLoader
->FileName
, NULL
, Volume
, !(IsLinux
&& GlobalConfig
.FoldLinuxKernels
));
1440 if (IsLinux
&& (FirstKernel
== NULL
))
1441 FirstKernel
= LatestEntry
;
1443 NewLoader
= NewLoader
->NextEntry
;
1445 if ((NewLoader
!= NULL
) && (FirstKernel
!= NULL
) && IsLinux
&& GlobalConfig
.FoldLinuxKernels
)
1446 AddMenuEntry(FirstKernel
->me
.SubScreen
, &MenuEntryReturn
);
1448 CleanUpLoaderList(LoaderList
);
1449 Status
= DirIterClose(&DirIter
);
1450 // NOTE: EFI_INVALID_PARAMETER really is an error that should be reported;
1451 // but I've gotten reports from users who are getting this error occasionally
1452 // and I can't find anything wrong or reproduce the problem, so I'm putting
1453 // it down to buggy EFI implementations and ignoring that particular error....
1454 if ((Status
!= EFI_NOT_FOUND
) && (Status
!= EFI_INVALID_PARAMETER
)) {
1456 SPrint(FileName
, 255, L
"while scanning the %s directory", Path
);
1458 StrCpy(FileName
, L
"while scanning the root directory");
1459 CheckError(Status
, FileName
);
1460 } // if (Status != EFI_NOT_FOUND)
1461 } // if not scanning a blacklisted directory
1463 return FoundFallbackDuplicate
;
1464 } /* static VOID ScanLoaderDir() */
1466 // Run the IPXE_DISCOVER_NAME program, which obtains the IP address of the boot
1467 // server and the name of the boot file it delivers.
1468 CHAR16
* RuniPXEDiscover(EFI_HANDLE Volume
)
1471 EFI_DEVICE_PATH
*FilePath
;
1472 EFI_HANDLE iPXEHandle
;
1473 CHAR16
*boot_info
= NULL
;
1474 UINTN boot_info_size
= 0;
1476 FilePath
= FileDevicePath (Volume
, IPXE_DISCOVER_NAME
);
1477 Status
= refit_call6_wrapper(BS
->LoadImage
, FALSE
, SelfImageHandle
, FilePath
, NULL
, 0, &iPXEHandle
);
1481 Status
= refit_call3_wrapper(BS
->StartImage
, iPXEHandle
, &boot_info_size
, &boot_info
);
1484 } // RuniPXEDiscover()
1486 // Scan for network (PXE) boot servers. This function relies on the presence
1487 // of the IPXE_DISCOVER_NAME and IPXE_NAME program files on the volume from
1488 // which rEFInd launched. As of December 6, 2014, these tools aren't entirely
1489 // reliable. See BUILDING.txt for information on building them.
1490 static VOID
ScanNetboot() {
1491 CHAR16
*iPXEFileName
= IPXE_NAME
;
1493 REFIT_VOLUME
*NetVolume
;
1495 if (FileExists(SelfVolume
->RootDir
, IPXE_DISCOVER_NAME
) &&
1496 FileExists(SelfVolume
->RootDir
, IPXE_NAME
) &&
1497 IsValidLoader(SelfVolume
->RootDir
, IPXE_DISCOVER_NAME
) &&
1498 IsValidLoader(SelfVolume
->RootDir
, IPXE_NAME
)) {
1499 Location
= RuniPXEDiscover(SelfVolume
->DeviceHandle
);
1500 if (Location
!= NULL
&& FileExists(SelfVolume
->RootDir
, iPXEFileName
)) {
1501 NetVolume
= AllocatePool(sizeof(REFIT_VOLUME
));
1502 CopyMem(NetVolume
, SelfVolume
, sizeof(REFIT_VOLUME
));
1503 NetVolume
->DiskKind
= DISK_KIND_NET
;
1504 NetVolume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_NET
);
1505 NetVolume
->PartName
= NetVolume
->VolName
= NULL
;
1506 AddLoaderEntry(iPXEFileName
, Location
, NetVolume
, TRUE
);
1507 MyFreePool(NetVolume
);
1508 } // if support files exist and are valid
1510 } // VOID ScanNetBoot()
1512 static VOID
ScanEfiFiles(REFIT_VOLUME
*Volume
) {
1514 REFIT_DIR_ITER EfiDirIter
;
1515 EFI_FILE_INFO
*EfiDirEntry
;
1516 CHAR16 FileName
[256], *Directory
= NULL
, *MatchPatterns
, *VolName
= NULL
, *SelfPath
;
1518 BOOLEAN ScanFallbackLoader
= TRUE
;
1519 BOOLEAN FoundBRBackup
= FALSE
;
1521 if (Volume
&& (Volume
->RootDir
!= NULL
) && (Volume
->VolName
!= NULL
) && (Volume
->IsReadable
)) {
1522 MatchPatterns
= StrDuplicate(LOADER_MATCH_PATTERNS
);
1523 if (GlobalConfig
.ScanAllLinux
)
1524 MergeStrings(&MatchPatterns
, LINUX_MATCH_PATTERNS
, L
',');
1526 // check for Mac OS X boot loader
1527 if (ShouldScan(Volume
, MACOSX_LOADER_DIR
)) {
1528 StrCpy(FileName
, MACOSX_LOADER_PATH
);
1529 if (FileExists(Volume
->RootDir
, FileName
) && !FilenameIn(Volume
, MACOSX_LOADER_DIR
, L
"boot.efi", GlobalConfig
.DontScanFiles
)) {
1530 AddLoaderEntry(FileName
, L
"Mac OS X", Volume
, TRUE
);
1531 if (DuplicatesFallback(Volume
, FileName
))
1532 ScanFallbackLoader
= FALSE
;
1536 StrCpy(FileName
, L
"System\\Library\\CoreServices\\xom.efi");
1537 if (FileExists(Volume
->RootDir
, FileName
) && !FilenameIn(Volume
, MACOSX_LOADER_DIR
, L
"xom.efi", GlobalConfig
.DontScanFiles
)) {
1538 AddLoaderEntry(FileName
, L
"Windows XP (XoM)", Volume
, TRUE
);
1539 if (DuplicatesFallback(Volume
, FileName
))
1540 ScanFallbackLoader
= FALSE
;
1542 } // if should scan Mac directory
1544 // check for Microsoft boot loader/menu
1545 if (ShouldScan(Volume
, L
"EFI\\Microsoft\\Boot")) {
1546 StrCpy(FileName
, L
"EFI\\Microsoft\\Boot\\bkpbootmgfw.efi");
1547 if (FileExists(Volume
->RootDir
, FileName
) && !FilenameIn(Volume
, L
"EFI\\Microsoft\\Boot", L
"bkpbootmgfw.efi",
1548 GlobalConfig
.DontScanFiles
)) {
1549 AddLoaderEntry(FileName
, L
"Microsoft EFI boot (Boot Repair backup)", Volume
, TRUE
);
1550 FoundBRBackup
= TRUE
;
1551 if (DuplicatesFallback(Volume
, FileName
))
1552 ScanFallbackLoader
= FALSE
;
1554 StrCpy(FileName
, L
"EFI\\Microsoft\\Boot\\bootmgfw.efi");
1555 if (FileExists(Volume
->RootDir
, FileName
) &&
1556 !FilenameIn(Volume
, L
"EFI\\Microsoft\\Boot", L
"bootmgfw.efi", GlobalConfig
.DontScanFiles
)) {
1558 AddLoaderEntry(FileName
, L
"Supposed Microsoft EFI boot (probably GRUB)", Volume
, TRUE
);
1560 AddLoaderEntry(FileName
, L
"Microsoft EFI boot", Volume
, TRUE
);
1561 if (DuplicatesFallback(Volume
, FileName
))
1562 ScanFallbackLoader
= FALSE
;
1566 // scan the root directory for EFI executables
1567 if (ScanLoaderDir(Volume
, L
"\\", MatchPatterns
))
1568 ScanFallbackLoader
= FALSE
;
1570 // scan subdirectories of the EFI directory (as per the standard)
1571 DirIterOpen(Volume
->RootDir
, L
"EFI", &EfiDirIter
);
1572 while (DirIterNext(&EfiDirIter
, 1, NULL
, &EfiDirEntry
)) {
1573 if (MyStriCmp(EfiDirEntry
->FileName
, L
"tools") || EfiDirEntry
->FileName
[0] == '.')
1574 continue; // skip this, doesn't contain boot loaders or is scanned later
1575 SPrint(FileName
, 255, L
"EFI\\%s", EfiDirEntry
->FileName
);
1576 if (ScanLoaderDir(Volume
, FileName
, MatchPatterns
))
1577 ScanFallbackLoader
= FALSE
;
1579 Status
= DirIterClose(&EfiDirIter
);
1580 if ((Status
!= EFI_NOT_FOUND
) && (Status
!= EFI_INVALID_PARAMETER
))
1581 CheckError(Status
, L
"while scanning the EFI directory");
1583 // Scan user-specified (or additional default) directories....
1585 while ((Directory
= FindCommaDelimited(GlobalConfig
.AlsoScan
, i
++)) != NULL
) {
1586 if (ShouldScan(Volume
, Directory
)) {
1587 SplitVolumeAndFilename(&Directory
, &VolName
);
1588 CleanUpPathNameSlashes(Directory
);
1589 Length
= StrLen(Directory
);
1590 if ((Length
> 0) && ScanLoaderDir(Volume
, Directory
, MatchPatterns
))
1591 ScanFallbackLoader
= FALSE
;
1592 MyFreePool(VolName
);
1593 } // if should scan dir
1594 MyFreePool(Directory
);
1597 // Don't scan the fallback loader if it's on the same volume and a duplicate of rEFInd itself....
1598 SelfPath
= DevicePathToStr(SelfLoadedImage
->FilePath
);
1599 CleanUpPathNameSlashes(SelfPath
);
1600 if ((Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
) && DuplicatesFallback(Volume
, SelfPath
))
1601 ScanFallbackLoader
= FALSE
;
1603 // If not a duplicate & if it exists & if it's not us, create an entry
1604 // for the fallback boot loader
1605 if (ScanFallbackLoader
&& FileExists(Volume
->RootDir
, FALLBACK_FULLNAME
) && ShouldScan(Volume
, L
"EFI\\BOOT")) {
1606 AddLoaderEntry(FALLBACK_FULLNAME
, L
"Fallback boot loader", Volume
, TRUE
);
1609 } // static VOID ScanEfiFiles()
1611 // Scan internal disks for valid EFI boot loaders....
1612 static VOID
ScanInternal(VOID
) {
1615 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1616 if (Volumes
[VolumeIndex
]->DiskKind
== DISK_KIND_INTERNAL
) {
1617 ScanEfiFiles(Volumes
[VolumeIndex
]);
1620 } // static VOID ScanInternal()
1622 // Scan external disks for valid EFI boot loaders....
1623 static VOID
ScanExternal(VOID
) {
1626 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1627 if (Volumes
[VolumeIndex
]->DiskKind
== DISK_KIND_EXTERNAL
) {
1628 ScanEfiFiles(Volumes
[VolumeIndex
]);
1631 } // static VOID ScanExternal()
1633 // Scan internal disks for valid EFI boot loaders....
1634 static VOID
ScanOptical(VOID
) {
1637 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1638 if (Volumes
[VolumeIndex
]->DiskKind
== DISK_KIND_OPTICAL
) {
1639 ScanEfiFiles(Volumes
[VolumeIndex
]);
1642 } // static VOID ScanOptical()
1644 // default volume badge icon based on disk kind
1645 EG_IMAGE
* GetDiskBadge(IN UINTN DiskType
) {
1646 EG_IMAGE
* Badge
= NULL
;
1650 Badge
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
1653 Badge
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
1656 Badge
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
1660 } // EG_IMAGE * GetDiskBadge()
1663 // pre-boot tool functions
1666 static VOID
StartTool(IN LOADER_ENTRY
*Entry
)
1668 BeginExternalScreen(Entry
->UseGraphicsMode
, Entry
->me
.Title
+ 6); // assumes "Start <title>" as assigned below
1669 StoreLoaderName(Entry
->me
.Title
);
1670 StartEFIImage(Entry
->DevicePath
, Entry
->LoadOptions
, TYPE_EFI
,
1671 Basename(Entry
->LoaderPath
), Entry
->OSType
, NULL
, TRUE
, FALSE
);
1672 FinishExternalScreen();
1673 } /* static VOID StartTool() */
1675 static LOADER_ENTRY
* AddToolEntry(EFI_HANDLE DeviceHandle
, IN CHAR16
*LoaderPath
, IN CHAR16
*LoaderTitle
, IN EG_IMAGE
*Image
,
1676 IN CHAR16 ShortcutLetter
, IN BOOLEAN UseGraphicsMode
)
1678 LOADER_ENTRY
*Entry
;
1679 CHAR16
*TitleStr
= NULL
;
1681 Entry
= AllocateZeroPool(sizeof(LOADER_ENTRY
));
1683 TitleStr
= PoolPrint(L
"Start %s", LoaderTitle
);
1684 Entry
->me
.Title
= TitleStr
;
1685 Entry
->me
.Tag
= TAG_TOOL
;
1687 Entry
->me
.ShortcutLetter
= ShortcutLetter
;
1688 Entry
->me
.Image
= Image
;
1689 Entry
->LoaderPath
= (LoaderPath
) ? StrDuplicate(LoaderPath
) : NULL
;
1690 Entry
->DevicePath
= FileDevicePath(DeviceHandle
, Entry
->LoaderPath
);
1691 Entry
->UseGraphicsMode
= UseGraphicsMode
;
1693 AddMenuEntry(&MainMenu
, (REFIT_MENU_ENTRY
*)Entry
);
1695 } /* static LOADER_ENTRY * AddToolEntry() */
1697 // Locates boot loaders. NOTE: This assumes that GlobalConfig.LegacyType is set correctly.
1698 static VOID
ScanForBootloaders(VOID
) {
1701 BOOLEAN ScanForLegacy
= FALSE
;
1703 // Determine up-front if we'll be scanning for legacy loaders....
1704 for (i
= 0; i
< NUM_SCAN_OPTIONS
; i
++) {
1705 s
= GlobalConfig
.ScanFor
[i
];
1706 if ((s
== 'c') || (s
== 'C') || (s
== 'h') || (s
== 'H') || (s
== 'b') || (s
== 'B'))
1707 ScanForLegacy
= TRUE
;
1710 // If UEFI & scanning for legacy loaders & deep legacy scan, update NVRAM boot manager list
1711 if ((GlobalConfig
.LegacyType
== LEGACY_TYPE_UEFI
) && ScanForLegacy
&& GlobalConfig
.DeepLegacyScan
) {
1712 BdsDeleteAllInvalidLegacyBootOptions();
1713 BdsAddNonExistingLegacyBootOptions();
1716 // scan for loaders and tools, add them to the menu
1717 for (i
= 0; i
< NUM_SCAN_OPTIONS
; i
++) {
1718 switch(GlobalConfig
.ScanFor
[i
]) {
1723 ScanLegacyInternal();
1726 ScanLegacyExternal();
1729 ScanUserConfigured(GlobalConfig
.ConfigFilename
);
1746 // assign shortcut keys
1747 for (i
= 0; i
< MainMenu
.EntryCount
&& MainMenu
.Entries
[i
]->Row
== 0 && i
< 9; i
++)
1748 MainMenu
.Entries
[i
]->ShortcutDigit
= (CHAR16
)('1' + i
);
1750 // wait for user ACK when there were errors
1751 FinishTextScreen(FALSE
);
1752 } // static VOID ScanForBootloaders()
1754 // Locate a single tool from the specified Locations using one of the
1755 // specified Names and add it to the menu.
1756 static VOID
FindTool(CHAR16
*Locations
, CHAR16
*Names
, CHAR16
*Description
, UINTN Icon
) {
1757 UINTN j
= 0, k
, VolumeIndex
;
1758 CHAR16
*DirName
, *FileName
, *PathName
, FullDescription
[256];
1760 while ((DirName
= FindCommaDelimited(Locations
, j
++)) != NULL
) {
1762 while ((FileName
= FindCommaDelimited(Names
, k
++)) != NULL
) {
1763 PathName
= StrDuplicate(DirName
);
1764 MergeStrings(&PathName
, FileName
, MyStriCmp(PathName
, L
"\\") ? 0 : L
'\\');
1765 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1766 if ((Volumes
[VolumeIndex
]->RootDir
!= NULL
) &&
1767 (FileExists(Volumes
[VolumeIndex
]->RootDir
, PathName
)) &&
1768 IsValidLoader(Volumes
[VolumeIndex
]->RootDir
, PathName
)) {
1769 SPrint(FullDescription
, 255, L
"%s at %s on %s", Description
, PathName
, Volumes
[VolumeIndex
]->VolName
);
1770 AddToolEntry(Volumes
[VolumeIndex
]->DeviceHandle
, PathName
, FullDescription
, BuiltinIcon(Icon
), 'S', FALSE
);
1773 MyFreePool(PathName
);
1774 MyFreePool(FileName
);
1776 MyFreePool(DirName
);
1777 } // while Locations
1778 } // VOID FindTool()
1780 // Add the second-row tags containing built-in and external tools (EFI shell,
1782 static VOID
ScanForTools(VOID
) {
1783 CHAR16
*FileName
= NULL
, *VolName
= NULL
, *MokLocations
, Description
[256];
1784 REFIT_MENU_ENTRY
*TempMenuEntry
;
1785 UINTN i
, j
, VolumeIndex
;
1790 MokLocations
= StrDuplicate(MOK_LOCATIONS
);
1791 if (MokLocations
!= NULL
)
1792 MergeStrings(&MokLocations
, SelfDirPath
, L
',');
1794 for (i
= 0; i
< NUM_TOOLS
; i
++) {
1795 switch(GlobalConfig
.ShowTools
[i
]) {
1796 // NOTE: Be sure that FileName is NULL at the end of each case.
1798 TempMenuEntry
= CopyMenuEntry(&MenuEntryShutdown
);
1799 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_SHUTDOWN
);
1800 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1804 TempMenuEntry
= CopyMenuEntry(&MenuEntryReset
);
1805 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_RESET
);
1806 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1810 TempMenuEntry
= CopyMenuEntry(&MenuEntryAbout
);
1811 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_ABOUT
);
1812 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1816 TempMenuEntry
= CopyMenuEntry(&MenuEntryExit
);
1817 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_EXIT
);
1818 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1822 if (EfivarGetRaw(&GlobalGuid
, L
"OsIndicationsSupported", &b
, &j
) == EFI_SUCCESS
) {
1824 if (osind
& EFI_OS_INDICATIONS_BOOT_TO_FW_UI
) {
1825 TempMenuEntry
= CopyMenuEntry(&MenuEntryFirmware
);
1826 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_FIRMWARE
);
1827 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1834 while ((FileName
= FindCommaDelimited(SHELL_NAMES
, j
++)) != NULL
) {
1835 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1836 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"EFI Shell", BuiltinIcon(BUILTIN_ICON_TOOL_SHELL
),
1839 MyFreePool(FileName
);
1845 while ((FileName
= FindCommaDelimited(GPTSYNC_NAMES
, j
++)) != NULL
) {
1846 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1847 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"Hybrid MBR tool", BuiltinIcon(BUILTIN_ICON_TOOL_PART
),
1850 MyFreePool(FileName
);
1857 while ((FileName
= FindCommaDelimited(GDISK_NAMES
, j
++)) != NULL
) {
1858 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1859 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"disk partitioning tool",
1860 BuiltinIcon(BUILTIN_ICON_TOOL_PART
), 'G', FALSE
);
1862 MyFreePool(FileName
);
1869 while ((FileName
= FindCommaDelimited(NETBOOT_NAMES
, j
++)) != NULL
) {
1870 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1871 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"Netboot",
1872 BuiltinIcon(BUILTIN_ICON_TOOL_NETBOOT
), 'N', FALSE
);
1874 MyFreePool(FileName
);
1879 case TAG_APPLE_RECOVERY
:
1880 FileName
= StrDuplicate(L
"\\com.apple.recovery.boot\\boot.efi");
1881 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1882 if ((Volumes
[VolumeIndex
]->RootDir
!= NULL
) &&
1883 (FileExists(Volumes
[VolumeIndex
]->RootDir
, FileName
)) &&
1884 IsValidLoader(Volumes
[VolumeIndex
]->RootDir
, FileName
)) {
1885 SPrint(Description
, 255, L
"Apple Recovery on %s", Volumes
[VolumeIndex
]->VolName
);
1886 AddToolEntry(Volumes
[VolumeIndex
]->DeviceHandle
, FileName
, Description
,
1887 BuiltinIcon(BUILTIN_ICON_TOOL_APPLE_RESCUE
), 'R', TRUE
);
1890 MyFreePool(FileName
);
1894 case TAG_WINDOWS_RECOVERY
:
1896 while ((FileName
= FindCommaDelimited(GlobalConfig
.WindowsRecoveryFiles
, j
++)) != NULL
) {
1897 SplitVolumeAndFilename(&FileName
, &VolName
);
1898 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1899 if ((Volumes
[VolumeIndex
]->RootDir
!= NULL
) &&
1900 (FileExists(Volumes
[VolumeIndex
]->RootDir
, FileName
)) &&
1901 IsValidLoader(Volumes
[VolumeIndex
]->RootDir
, FileName
) &&
1902 ((VolName
== NULL
) || MyStriCmp(VolName
, Volumes
[VolumeIndex
]->VolName
))) {
1903 SPrint(Description
, 255, L
"Microsoft Recovery on %s", Volumes
[VolumeIndex
]->VolName
);
1904 AddToolEntry(Volumes
[VolumeIndex
]->DeviceHandle
, FileName
, Description
,
1905 BuiltinIcon(BUILTIN_ICON_TOOL_WINDOWS_RESCUE
), 'R', TRUE
);
1909 MyFreePool(FileName
);
1911 MyFreePool(VolName
);
1916 FindTool(MokLocations
, MOK_NAMES
, L
"MOK utility", BUILTIN_ICON_TOOL_MOK_TOOL
);
1919 case TAG_CSR_ROTATE
:
1920 if ((GetCsrStatus(&CsrValue
) == EFI_SUCCESS
) && (GlobalConfig
.CsrValues
)) {
1921 TempMenuEntry
= CopyMenuEntry(&MenuEntryRotateCsr
);
1922 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_CSR_ROTATE
);
1923 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1928 FindTool(MEMTEST_LOCATIONS
, MEMTEST_NAMES
, L
"Memory test utility", BUILTIN_ICON_TOOL_MEMTEST
);
1933 } // static VOID ScanForTools
1935 // Rescan for boot loaders
1936 static VOID
RescanAll(BOOLEAN DisplayMessage
) {
1944 egDisplayMessage(L
"Scanning for new boot loaders; please wait....", &BGColor
);
1945 FreeList((VOID
***) &(MainMenu
.Entries
), &MainMenu
.EntryCount
);
1946 MainMenu
.Entries
= NULL
;
1947 MainMenu
.EntryCount
= 0;
1948 ConnectAllDriversToAllControllers();
1950 ReadConfig(GlobalConfig
.ConfigFilename
);
1952 ScanForBootloaders();
1955 } // VOID RescanAll()
1957 #ifdef __MAKEWITH_TIANO
1959 // Minimal initialization function
1960 static VOID
InitializeLib(IN EFI_HANDLE ImageHandle
, IN EFI_SYSTEM_TABLE
*SystemTable
) {
1962 // gImageHandle = ImageHandle;
1963 gBS
= SystemTable
->BootServices
;
1964 // gRS = SystemTable->RuntimeServices;
1965 gRT
= SystemTable
->RuntimeServices
; // Some BDS functions need gRT to be set
1966 EfiGetSystemConfigurationTable (&gEfiDxeServicesTableGuid
, (VOID
**) &gDS
);
1971 // Set up our own Secure Boot extensions....
1972 // Returns TRUE on success, FALSE otherwise
1973 static BOOLEAN
SecureBootSetup(VOID
) {
1975 BOOLEAN Success
= FALSE
;
1977 if (secure_mode() && ShimLoaded()) {
1978 Status
= security_policy_install();
1979 if (Status
== EFI_SUCCESS
) {
1982 Print(L
"Failed to install MOK Secure Boot extensions");
1987 } // VOID SecureBootSetup()
1989 // Remove our own Secure Boot extensions....
1990 // Returns TRUE on success, FALSE otherwise
1991 static BOOLEAN
SecureBootUninstall(VOID
) {
1993 BOOLEAN Success
= TRUE
;
1995 if (secure_mode()) {
1996 Status
= security_policy_uninstall();
1997 if (Status
!= EFI_SUCCESS
) {
1999 BeginTextScreen(L
"Secure Boot Policy Failure");
2000 Print(L
"Failed to uninstall MOK Secure Boot extensions; forcing a reboot.");
2002 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);
2006 } // VOID SecureBootUninstall
2008 // Sets the global configuration filename; will be CONFIG_FILE_NAME unless the
2009 // "-c" command-line option is set, in which case that takes precedence.
2010 // If an error is encountered, leaves the value alone (it should be set to
2011 // CONFIG_FILE_NAME when GlobalConfig is initialized).
2012 static VOID
SetConfigFilename(EFI_HANDLE ImageHandle
) {
2013 EFI_LOADED_IMAGE
*Info
;
2014 CHAR16
*Options
, *FileName
, *SubString
;
2017 Status
= refit_call3_wrapper(BS
->HandleProtocol
, ImageHandle
, &LoadedImageProtocol
, (VOID
**) &Info
);
2018 if ((Status
== EFI_SUCCESS
) && (Info
->LoadOptionsSize
> 0)) {
2019 Options
= (CHAR16
*) Info
->LoadOptions
;
2020 SubString
= MyStrStr(Options
, L
" -c ");
2022 FileName
= StrDuplicate(&SubString
[4]);
2024 LimitStringLength(FileName
, 256);
2027 if (FileExists(SelfDir
, FileName
)) {
2028 GlobalConfig
.ConfigFilename
= FileName
;
2030 Print(L
"Specified configuration file (%s) doesn't exist; using\n'refind.conf' default\n", FileName
);
2031 MyFreePool(FileName
);
2035 } // VOID SetConfigFilename()
2042 efi_main (EFI_HANDLE ImageHandle
, EFI_SYSTEM_TABLE
*SystemTable
)
2045 BOOLEAN MainLoopRunning
= TRUE
;
2046 BOOLEAN MokProtocol
;
2047 REFIT_MENU_ENTRY
*ChosenEntry
;
2049 CHAR16
*SelectionName
= NULL
;
2053 InitializeLib(ImageHandle
, SystemTable
);
2054 Status
= InitRefitLib(ImageHandle
);
2055 if (EFI_ERROR(Status
))
2058 // read configuration
2059 CopyMem(GlobalConfig
.ScanFor
, "ieom ", NUM_SCAN_OPTIONS
);
2060 FindLegacyBootType();
2061 if (GlobalConfig
.LegacyType
== LEGACY_TYPE_MAC
)
2062 CopyMem(GlobalConfig
.ScanFor
, "ihebocm ", NUM_SCAN_OPTIONS
);
2063 SetConfigFilename(ImageHandle
);
2064 MokProtocol
= SecureBootSetup();
2066 ScanVolumes(); // Do before ReadConfig() because it needs SelfVolume->VolName
2067 ReadConfig(GlobalConfig
.ConfigFilename
);
2070 if (GlobalConfig
.SpoofOSXVersion
&& GlobalConfig
.SpoofOSXVersion
[0] != L
'\0')
2074 WarnIfLegacyProblems();
2075 MainMenu
.TimeoutSeconds
= GlobalConfig
.Timeout
;
2077 // disable EFI watchdog timer
2078 refit_call4_wrapper(BS
->SetWatchdogTimer
, 0x0000, 0x0000, 0x0000, NULL
);
2080 // further bootstrap (now with config available)
2081 ScanForBootloaders();
2085 if (GlobalConfig
.ScanDelay
> 0) {
2090 if (GlobalConfig
.ScanDelay
> 1)
2091 egDisplayMessage(L
"Pausing before disk scan; please wait....", &BGColor
);
2092 for (i
= 0; i
< GlobalConfig
.ScanDelay
; i
++)
2093 refit_call1_wrapper(BS
->Stall
, 1000000);
2094 RescanAll(GlobalConfig
.ScanDelay
> 1);
2097 if (GlobalConfig
.DefaultSelection
)
2098 SelectionName
= StrDuplicate(GlobalConfig
.DefaultSelection
);
2100 while (MainLoopRunning
) {
2101 MenuExit
= RunMainMenu(&MainMenu
, &SelectionName
, &ChosenEntry
);
2103 // The Escape key triggers a re-scan operation....
2104 if (MenuExit
== MENU_EXIT_ESCAPE
) {
2110 switch (ChosenEntry
->Tag
) {
2112 case TAG_REBOOT
: // Reboot
2114 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);
2115 MainLoopRunning
= FALSE
; // just in case we get this far
2118 case TAG_SHUTDOWN
: // Shut Down
2120 refit_call4_wrapper(RT
->ResetSystem
, EfiResetShutdown
, EFI_SUCCESS
, 0, NULL
);
2121 MainLoopRunning
= FALSE
; // just in case we get this far
2124 case TAG_ABOUT
: // About rEFInd
2128 case TAG_LOADER
: // Boot OS via .EFI loader
2129 StartLoader((LOADER_ENTRY
*)ChosenEntry
, SelectionName
);
2132 case TAG_LEGACY
: // Boot legacy OS
2133 StartLegacy((LEGACY_ENTRY
*)ChosenEntry
, SelectionName
);
2136 case TAG_LEGACY_UEFI
: // Boot a legacy OS on a non-Mac
2137 StartLegacyUEFI((LEGACY_ENTRY
*)ChosenEntry
, SelectionName
);
2140 case TAG_TOOL
: // Start a EFI tool
2141 StartTool((LOADER_ENTRY
*)ChosenEntry
);
2144 case TAG_EXIT
: // Terminate rEFInd
2145 if ((MokProtocol
) && !SecureBootUninstall()) {
2146 MainLoopRunning
= FALSE
; // just in case we get this far
2148 BeginTextScreen(L
" ");
2153 case TAG_FIRMWARE
: // Reboot into firmware's user interface
2154 RebootIntoFirmware();
2157 case TAG_CSR_ROTATE
:
2164 // If we end up here, things have gone wrong. Try to reboot, and if that
2165 // fails, go into an endless loop.
2166 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);