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/>.
67 #include "security_policy.h"
68 #include "driver_support.h"
69 #include "../include/Handle.h"
70 #include "../include/refit_call_wrapper.h"
71 #include "../EfiLib/BdsHelper.h"
72 #include "../EfiLib/legacy.h"
74 #ifdef __MAKEWITH_GNUEFI
75 #ifndef EFI_SECURITY_VIOLATION
76 #define EFI_SECURITY_VIOLATION EFIERR (26)
80 #ifndef EFI_OS_INDICATIONS_BOOT_TO_FW_UI
81 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001ULL
84 #ifdef __MAKEWITH_TIANO
85 #define LibLocateHandle gBS->LocateHandleBuffer
91 #define MACOSX_LOADER_DIR L"System\\Library\\CoreServices"
92 #define MACOSX_LOADER_PATH ( MACOSX_LOADER_DIR L"\\boot.efi" )
94 #define SHELL_NAMES L"\\EFI\\tools\\shell.efi,\\EFI\\tools\\shellx64.efi,\\shell.efi,\\shellx64.efi"
95 #define GPTSYNC_NAMES L"\\EFI\\tools\\gptsync.efi,\\EFI\\tools\\gptsync_x64.efi"
96 #define GDISK_NAMES L"\\EFI\\tools\\gdisk.efi,\\EFI\\tools\\gdisk_x64.efi"
97 #define NETBOOT_NAMES L"\\EFI\\tools\\ipxe.efi"
98 #define MEMTEST_NAMES L"memtest86.efi,memtest86_x64.efi,memtest86x64.efi,bootx64.efi"
99 #define DRIVER_DIRS L"drivers,drivers_x64"
100 #define FALLBACK_FULLNAME L"EFI\\BOOT\\bootx64.efi"
101 #define FALLBACK_BASENAME L"bootx64.efi"
102 #define EFI_STUB_ARCH 0x8664
103 EFI_GUID gFreedesktopRootGuid
= { 0x4f68bce3, 0xe8cd, 0x4db1, { 0x96, 0xe7, 0xfb, 0xca, 0xf9, 0x84, 0xb7, 0x09 }};
104 #elif defined (EFI32)
105 #define SHELL_NAMES L"\\EFI\\tools\\shell.efi,\\EFI\\tools\\shellia32.efi,\\shell.efi,\\shellia32.efi"
106 #define GPTSYNC_NAMES L"\\EFI\\tools\\gptsync.efi,\\EFI\\tools\\gptsync_ia32.efi"
107 #define GDISK_NAMES L"\\EFI\\tools\\gdisk.efi,\\EFI\\tools\\gdisk_ia32.efi"
108 #define NETBOOT_NAMES L"\\EFI\\tools\\ipxe.efi"
109 #define MEMTEST_NAMES L"memtest86.efi,memtest86_ia32.efi,memtest86ia32.efi,bootia32.efi"
110 #define DRIVER_DIRS L"drivers,drivers_ia32"
111 #define FALLBACK_FULLNAME L"EFI\\BOOT\\bootia32.efi"
112 #define FALLBACK_BASENAME L"bootia32.efi"
113 #define EFI_STUB_ARCH 0x014c
114 EFI_GUID gFreedesktopRootGuid
= { 0x44479540, 0xf297, 0x41b2, { 0x9a, 0xf7, 0xd1, 0x31, 0xd5, 0xf0, 0x45, 0x8a }};
116 #define SHELL_NAMES L"\\EFI\\tools\\shell.efi,\\shell.efi"
117 #define GPTSYNC_NAMES L"\\EFI\\tools\\gptsync.efi"
118 #define GDISK_NAMES L"\\EFI\\tools\\gdisk.efi"
119 #define NETBOOT_NAMES L"\\EFI\\tools\\ipxe.efi"
120 #define MEMTEST_NAMES L"memtest86.efi"
121 #define DRIVER_DIRS L"drivers"
122 #define FALLBACK_FULLNAME L"EFI\\BOOT\\boot.efi" /* Not really correct */
123 #define FALLBACK_BASENAME L"boot.efi" /* Not really correct */
124 // Below is GUID for ARM64
125 EFI_GUID gFreedesktopRootGuid
= { 0xb921b045, 0x1df0, 0x41c3, { 0xaf, 0x44, 0x4c, 0x6f, 0x28, 0x0d, 0x3f, 0xae }};
127 #define FAT_ARCH 0x0ef1fab9 /* ID for Apple "fat" binary */
129 #define IPXE_DISCOVER_NAME L"\\efi\\tools\\ipxe_discover.efi"
130 #define IPXE_NAME L"\\efi\\tools\\ipxe.efi"
132 // Filename patterns that identify EFI boot loaders. Note that a single case (either L"*.efi" or
133 // L"*.EFI") is fine for most systems; but Gigabyte's buggy Hybrid EFI does a case-sensitive
134 // comparison when it should do a case-insensitive comparison, so I'm doubling this up. It does
135 // no harm on other computers, AFAIK. In theory, every case variation should be done for
136 // completeness, but that's ridiculous....
137 #define LOADER_MATCH_PATTERNS L"*.efi,*.EFI"
139 // Patterns that identify Linux kernels. Added to the loader match pattern when the
140 // scan_all_linux_kernels option is set in the configuration file. Causes kernels WITHOUT
141 // a ".efi" extension to be found when scanning for boot loaders.
142 #define LINUX_MATCH_PATTERNS L"vmlinuz*,bzImage*"
144 // Maximum length of a text string in certain menus
145 #define MAX_LINE_LENGTH 65
147 static REFIT_MENU_ENTRY MenuEntryAbout
= { L
"About rEFInd", TAG_ABOUT
, 1, 0, 'A', NULL
, NULL
, NULL
};
148 static REFIT_MENU_ENTRY MenuEntryReset
= { L
"Reboot Computer", TAG_REBOOT
, 1, 0, 'R', NULL
, NULL
, NULL
};
149 static REFIT_MENU_ENTRY MenuEntryShutdown
= { L
"Shut Down Computer", TAG_SHUTDOWN
, 1, 0, 'U', NULL
, NULL
, NULL
};
150 REFIT_MENU_ENTRY MenuEntryReturn
= { L
"Return to Main Menu", TAG_RETURN
, 1, 0, 0, NULL
, NULL
, NULL
};
151 static REFIT_MENU_ENTRY MenuEntryExit
= { L
"Exit rEFInd", TAG_EXIT
, 1, 0, 0, NULL
, NULL
, NULL
};
152 static REFIT_MENU_ENTRY MenuEntryFirmware
= { L
"Reboot to Computer Setup Utility", TAG_FIRMWARE
, 1, 0, 0, NULL
, NULL
, NULL
};
154 REFIT_MENU_SCREEN MainMenu
= { L
"Main Menu", NULL
, 0, NULL
, 0, NULL
, 0, L
"Automatic boot",
155 L
"Use arrow keys to move cursor; Enter to boot;",
156 L
"Insert or F2 for more options; Esc to refresh" };
157 static REFIT_MENU_SCREEN AboutMenu
= { L
"About", NULL
, 0, NULL
, 0, NULL
, 0, NULL
, L
"Press Enter to return to main menu", L
"" };
159 REFIT_CONFIG GlobalConfig
= { FALSE
, TRUE
, FALSE
, FALSE
, TRUE
, 0, 0, 0, DONT_CHANGE_TEXT_MODE
,
160 20, 0, 0, GRAPHICS_FOR_OSX
, LEGACY_TYPE_MAC
,
161 0, 0, { DEFAULT_BIG_ICON_SIZE
/ 4, DEFAULT_SMALL_ICON_SIZE
, DEFAULT_BIG_ICON_SIZE
},
162 BANNER_NOSCALE
, NULL
, NULL
, NULL
, NULL
, CONFIG_FILE_NAME
, NULL
, NULL
, NULL
, NULL
,
163 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
164 { TAG_SHELL
, TAG_MEMTEST
, TAG_GDISK
, TAG_APPLE_RECOVERY
, TAG_WINDOWS_RECOVERY
,
165 TAG_MOK_TOOL
, TAG_ABOUT
, TAG_SHUTDOWN
, TAG_REBOOT
, TAG_FIRMWARE
,
166 0, 0, 0, 0, 0, 0, 0, 0 }
169 EFI_GUID GlobalGuid
= EFI_GLOBAL_VARIABLE
;
170 EFI_GUID RefindGuid
= REFIND_GUID_VALUE
;
172 GPT_DATA
*gPartitions
= NULL
;
174 // Structure used to hold boot loader filenames and time stamps in
175 // a linked list; used to sort entries within a directory.
179 struct LOADER_LIST
*NextEntry
;
186 static VOID
AboutrEFInd(VOID
)
188 CHAR16
*FirmwareVendor
;
190 if (AboutMenu
.EntryCount
== 0) {
191 AboutMenu
.TitleImage
= BuiltinIcon(BUILTIN_ICON_FUNC_ABOUT
);
192 AddMenuInfoLine(&AboutMenu
, L
"rEFInd Version 0.9.2.2");
193 AddMenuInfoLine(&AboutMenu
, L
"");
194 AddMenuInfoLine(&AboutMenu
, L
"Copyright (c) 2006-2010 Christoph Pfisterer");
195 AddMenuInfoLine(&AboutMenu
, L
"Copyright (c) 2012-2015 Roderick W. Smith");
196 AddMenuInfoLine(&AboutMenu
, L
"Portions Copyright (c) Intel Corporation and others");
197 AddMenuInfoLine(&AboutMenu
, L
"Distributed under the terms of the GNU GPLv3 license");
198 AddMenuInfoLine(&AboutMenu
, L
"");
199 AddMenuInfoLine(&AboutMenu
, L
"Running on:");
200 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" EFI Revision %d.%02d", ST
->Hdr
.Revision
>> 16, ST
->Hdr
.Revision
& ((1 << 16) - 1)));
202 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" Platform: x86 (32 bit); Secure Boot %s",
203 secure_mode() ? L
"active" : L
"inactive"));
204 #elif defined(EFIX64)
205 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" Platform: x86_64 (64 bit); Secure Boot %s",
206 secure_mode() ? L
"active" : L
"inactive"));
208 AddMenuInfoLine(&AboutMenu
, L
" Platform: unknown");
210 FirmwareVendor
= StrDuplicate(ST
->FirmwareVendor
);
211 LimitStringLength(FirmwareVendor
, MAX_LINE_LENGTH
); // More than ~65 causes empty info page on 800x600 display
212 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" Firmware: %s %d.%02d", FirmwareVendor
, ST
->FirmwareRevision
>> 16,
213 ST
->FirmwareRevision
& ((1 << 16) - 1)));
214 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" Screen Output: %s", egScreenDescription()));
215 AddMenuInfoLine(&AboutMenu
, L
"");
216 #if defined(__MAKEWITH_GNUEFI)
217 AddMenuInfoLine(&AboutMenu
, L
"Built with GNU-EFI");
219 AddMenuInfoLine(&AboutMenu
, L
"Built with TianoCore EDK2");
221 AddMenuInfoLine(&AboutMenu
, L
"");
222 AddMenuInfoLine(&AboutMenu
, L
"For more information, see the rEFInd Web site:");
223 AddMenuInfoLine(&AboutMenu
, L
"http://www.rodsbooks.com/refind/");
224 AddMenuEntry(&AboutMenu
, &MenuEntryReturn
);
227 RunMenu(&AboutMenu
, NULL
);
228 } /* VOID AboutrEFInd() */
230 static VOID
WarnSecureBootError(CHAR16
*Name
, BOOLEAN Verbose
) {
232 Name
= L
"the loader";
234 refit_call2_wrapper(ST
->ConOut
->SetAttribute
, ST
->ConOut
, ATTR_ERROR
);
235 Print(L
"Secure Boot validation failure loading %s!\n", Name
);
236 refit_call2_wrapper(ST
->ConOut
->SetAttribute
, ST
->ConOut
, ATTR_BASIC
);
237 if (Verbose
&& secure_mode()) {
238 Print(L
"\nThis computer is configured with Secure Boot active, but\n%s has failed validation.\n", Name
);
239 Print(L
"\nYou can:\n * Launch another boot loader\n");
240 Print(L
" * Disable Secure Boot in your firmware\n");
241 Print(L
" * Sign %s with a machine owner key (MOK)\n", Name
);
242 Print(L
" * Use a MOK utility (often present on the second row) to add a MOK with which\n");
243 Print(L
" %s has already been signed.\n", Name
);
244 Print(L
" * Use a MOK utility to register %s (\"enroll its hash\") without\n", Name
);
245 Print(L
" signing it.\n");
246 Print(L
"\nSee http://www.rodsbooks.com/refind/secureboot.html for more information\n");
249 } // VOID WarnSecureBootError()
251 // Returns TRUE if this file is a valid EFI loader file, and is proper ARCH
252 static BOOLEAN
IsValidLoader(EFI_FILE
*RootDir
, CHAR16
*FileName
) {
253 BOOLEAN IsValid
= TRUE
;
254 #if defined (EFIX64) | defined (EFI32)
256 EFI_FILE_HANDLE FileHandle
;
258 UINTN Size
= sizeof(Header
);
260 if ((RootDir
== NULL
) || (FileName
== NULL
)) {
261 // Assume valid here, because Macs produce NULL RootDir (& maybe FileName)
262 // when launching from a Firewire drive. This should be handled better, but
263 // fix would have to be in StartEFIImageList() and/or in FindVolumeAndFilename().
267 Status
= refit_call5_wrapper(RootDir
->Open
, RootDir
, &FileHandle
, FileName
, EFI_FILE_MODE_READ
, 0);
268 if (EFI_ERROR(Status
))
271 Status
= refit_call3_wrapper(FileHandle
->Read
, FileHandle
, &Size
, Header
);
272 refit_call1_wrapper(FileHandle
->Close
, FileHandle
);
274 IsValid
= !EFI_ERROR(Status
) &&
275 Size
== sizeof(Header
) &&
276 ((Header
[0] == 'M' && Header
[1] == 'Z' &&
277 (Size
= *(UINT32
*)&Header
[0x3c]) < 0x180 &&
278 Header
[Size
] == 'P' && Header
[Size
+1] == 'E' &&
279 Header
[Size
+2] == 0 && Header
[Size
+3] == 0 &&
280 *(UINT16
*)&Header
[Size
+4] == EFI_STUB_ARCH
) ||
281 (*(UINT32
*)&Header
== FAT_ARCH
));
284 } // BOOLEAN IsValidLoader()
286 // Launch an EFI binary.
287 EFI_STATUS
StartEFIImageList(IN EFI_DEVICE_PATH
**DevicePaths
,
288 IN CHAR16
*LoadOptions
, IN UINTN LoaderType
,
289 IN CHAR16
*ImageTitle
, IN CHAR8 OSType
,
290 OUT UINTN
*ErrorInStep
,
294 EFI_STATUS Status
, ReturnStatus
;
295 EFI_HANDLE ChildImageHandle
, ChildImageHandle2
;
296 EFI_LOADED_IMAGE
*ChildLoadedImage
= NULL
;
297 REFIT_VOLUME
*Volume
= NULL
;
298 UINTN DevicePathIndex
;
299 CHAR16 ErrorInfo
[256];
300 CHAR16
*FullLoadOptions
= NULL
;
301 CHAR16
*Filename
= NULL
;
304 if (ErrorInStep
!= NULL
)
308 if (LoadOptions
!= NULL
) {
309 FullLoadOptions
= StrDuplicate(LoadOptions
);
310 if ((LoaderType
== TYPE_EFI
) && (OSType
== 'M')) {
311 MergeStrings(&FullLoadOptions
, L
" ", 0);
312 // NOTE: That last space is also added by the EFI shell and seems to be significant
313 // when passing options to Apple's boot.efi...
315 } // if (LoadOptions != NULL)
317 Print(L
"Starting %s\nUsing load options '%s'\n", ImageTitle
, FullLoadOptions
? FullLoadOptions
: L
"");
319 // load the image into memory
320 ReturnStatus
= Status
= EFI_NOT_FOUND
; // in case the list is empty
321 for (DevicePathIndex
= 0; DevicePaths
[DevicePathIndex
] != NULL
; DevicePathIndex
++) {
322 FindVolumeAndFilename(DevicePaths
[DevicePathIndex
], &Volume
, &Filename
);
323 // Some EFIs crash if attempting to load driver for invalid architecture, so
324 // protect for this condition; but sometimes Volume comes back NULL, so provide
325 // an exception. (TODO: Handle this special condition better.)
326 if ((LoaderType
== TYPE_LEGACY
) || (Volume
== NULL
) || IsValidLoader(Volume
->RootDir
, Filename
)) {
327 if (Filename
&& (LoaderType
!= TYPE_LEGACY
)) {
328 Temp
= PoolPrint(L
"\\%s %s", Filename
, FullLoadOptions
? FullLoadOptions
: L
"");
330 MyFreePool(FullLoadOptions
);
331 FullLoadOptions
= Temp
;
335 // NOTE: Below commented-out line could be more efficient if file were read ahead of
336 // time and passed as a pre-loaded image to LoadImage(), but it doesn't work on my
337 // 32-bit Mac Mini or my 64-bit Intel box when launching a Linux kernel; the
338 // kernel returns a "Failed to handle fs_proto" error message.
339 // TODO: Track down the cause of this error and fix it, if possible.
340 // ReturnStatus = Status = refit_call6_wrapper(BS->LoadImage, FALSE, SelfImageHandle, DevicePaths[DevicePathIndex],
341 // ImageData, ImageSize, &ChildImageHandle);
342 ReturnStatus
= Status
= refit_call6_wrapper(BS
->LoadImage
, FALSE
, SelfImageHandle
, DevicePaths
[DevicePathIndex
],
343 NULL
, 0, &ChildImageHandle
);
344 if (secure_mode() && ShimLoaded()) {
345 // Load ourself into memory. This is a trick to work around a bug in Shim 0.8,
346 // which ties itself into the BS->LoadImage() and BS->StartImage() functions and
347 // then unregisters itself from the EFI system table when its replacement
348 // StartImage() function is called *IF* the previous LoadImage() was for the same
349 // program. The result is that rEFInd can validate only the first program it
350 // launches (often a filesystem driver). Loading a second program (rEFInd itself,
351 // here, to keep it smaller than a kernel) works around this problem. See the
352 // replacements.c file in Shim, and especially its start_image() function, for
353 // the source of the problem.
354 // NOTE: This doesn't check the return status or handle errors. It could
355 // conceivably do weird things if, say, rEFInd were on a USB drive that the
356 // user pulls before launching a program.
357 refit_call6_wrapper(BS
->LoadImage
, FALSE
, SelfImageHandle
, GlobalConfig
.SelfDevicePath
,
358 NULL
, 0, &ChildImageHandle2
);
361 Print(L
"Invalid loader file!\n");
362 ReturnStatus
= EFI_LOAD_ERROR
;
364 if (ReturnStatus
!= EFI_NOT_FOUND
) {
368 if ((Status
== EFI_ACCESS_DENIED
) || (Status
== EFI_SECURITY_VIOLATION
)) {
369 WarnSecureBootError(ImageTitle
, Verbose
);
372 SPrint(ErrorInfo
, 255, L
"while loading %s", ImageTitle
);
373 if (CheckError(Status
, ErrorInfo
)) {
374 if (ErrorInStep
!= NULL
)
379 ReturnStatus
= Status
= refit_call3_wrapper(BS
->HandleProtocol
, ChildImageHandle
, &LoadedImageProtocol
,
380 (VOID
**) &ChildLoadedImage
);
381 if (CheckError(Status
, L
"while getting a LoadedImageProtocol handle")) {
382 if (ErrorInStep
!= NULL
)
386 ChildLoadedImage
->LoadOptions
= (VOID
*)FullLoadOptions
;
387 ChildLoadedImage
->LoadOptionsSize
= FullLoadOptions
? ((UINT32
)StrLen(FullLoadOptions
) + 1) * sizeof(CHAR16
) : 0;
388 // turn control over to the image
389 // TODO: (optionally) re-enable the EFI watchdog timer!
391 // close open file handles
393 ReturnStatus
= Status
= refit_call3_wrapper(BS
->StartImage
, ChildImageHandle
, NULL
, NULL
);
395 // control returns here when the child image calls Exit()
396 SPrint(ErrorInfo
, 255, L
"returned from %s", ImageTitle
);
397 if (CheckError(Status
, ErrorInfo
)) {
398 if (ErrorInStep
!= NULL
)
402 // re-open file handles
406 // unload the image, we don't care if it works or not...
408 Status
= refit_call1_wrapper(BS
->UnloadImage
, ChildImageHandle
);
411 MyFreePool(FullLoadOptions
);
413 } /* EFI_STATUS StartEFIImageList() */
415 static EFI_STATUS
StartEFIImage(IN EFI_DEVICE_PATH
*DevicePath
,
416 IN CHAR16
*LoadOptions
, IN UINTN LoaderType
,
417 IN CHAR16
*ImageTitle
, IN CHAR8 OSType
,
418 OUT UINTN
*ErrorInStep
,
423 EFI_DEVICE_PATH
*DevicePaths
[2];
425 DevicePaths
[0] = DevicePath
;
426 DevicePaths
[1] = NULL
;
427 return StartEFIImageList(DevicePaths
, LoadOptions
, LoaderType
, ImageTitle
, OSType
, ErrorInStep
, Verbose
, IsDriver
);
428 } /* static EFI_STATUS StartEFIImage() */
430 // From gummiboot: Reboot the computer into its built-in user interface
431 static EFI_STATUS
RebootIntoFirmware(VOID
) {
437 osind
= EFI_OS_INDICATIONS_BOOT_TO_FW_UI
;
439 err
= EfivarGetRaw(&GlobalGuid
, L
"OsIndications", &b
, &size
);
440 if (err
== EFI_SUCCESS
)
444 err
= EfivarSetRaw(&GlobalGuid
, L
"OsIndications", (CHAR8
*)&osind
, sizeof(UINT64
), TRUE
);
445 if (err
!= EFI_SUCCESS
)
448 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);
449 Print(L
"Error calling ResetSystem: %r", err
);
454 // Record the value of the loader's name/description in rEFInd's "PreviousBoot" EFI variable,
455 // if it's different from what's already stored there.
456 VOID
StoreLoaderName(IN CHAR16
*Name
) {
458 CHAR16
*OldName
= NULL
;
462 Status
= EfivarGetRaw(&RefindGuid
, L
"PreviousBoot", (CHAR8
**) &OldName
, &Length
);
463 if ((Status
!= EFI_SUCCESS
) || (StrCmp(OldName
, Name
) != 0)) {
464 EfivarSetRaw(&RefindGuid
, L
"PreviousBoot", (CHAR8
*) Name
, StrLen(Name
) * 2 + 2, TRUE
);
468 } // VOID StoreLoaderName()
471 // EFI OS loader functions
474 // See http://www.thomas-krenn.com/en/wiki/Activating_the_Intel_VT_Virtualization_Feature
475 // for information on Intel VMX features
476 static VOID
DoEnableAndLockVMX(VOID
)
479 UINT32 low_bits
= 0, high_bits
= 0;
482 __asm__
volatile ("rdmsr" : "=a" (low_bits
), "=d" (high_bits
) : "c" (msr
));
484 // enable and lock vmx if not locked
485 if ((low_bits
& 1) == 0) {
489 __asm__
volatile ("wrmsr" : : "c" (msr
), "a" (low_bits
), "d" (high_bits
));
491 } // VOID DoEnableAndLockVMX()
493 static VOID
StartLoader(LOADER_ENTRY
*Entry
, CHAR16
*SelectionName
)
495 UINTN ErrorInStep
= 0;
497 if (GlobalConfig
.EnableAndLockVMX
) {
498 DoEnableAndLockVMX();
501 BeginExternalScreen(Entry
->UseGraphicsMode
, L
"Booting OS");
502 StoreLoaderName(SelectionName
);
503 StartEFIImage(Entry
->DevicePath
, Entry
->LoadOptions
, TYPE_EFI
,
504 Basename(Entry
->LoaderPath
), Entry
->OSType
, &ErrorInStep
, !Entry
->UseGraphicsMode
, FALSE
);
505 FinishExternalScreen();
508 // Locate an initrd or initramfs file that matches the kernel specified by LoaderPath.
509 // The matching file has a name that begins with "init" and includes the same version
510 // number string as is found in LoaderPath -- but not a longer version number string.
511 // For instance, if LoaderPath is \EFI\kernels\bzImage-3.3.0.efi, and if \EFI\kernels
512 // has a file called initramfs-3.3.0.img, this function will return the string
513 // '\EFI\kernels\initramfs-3.3.0.img'. If the directory ALSO contains the file
514 // initramfs-3.3.0-rc7.img or initramfs-13.3.0.img, those files will NOT match;
515 // however, initmine-3.3.0.img might match. (FindInitrd() returns the first match it
516 // finds.) Thus, care should be taken to avoid placing duplicate matching files in
517 // the kernel's directory.
518 // If no matching init file can be found, returns NULL.
519 static CHAR16
* FindInitrd(IN CHAR16
*LoaderPath
, IN REFIT_VOLUME
*Volume
) {
520 CHAR16
*InitrdName
= NULL
, *FileName
, *KernelVersion
, *InitrdVersion
, *Path
;
521 REFIT_DIR_ITER DirIter
;
522 EFI_FILE_INFO
*DirEntry
;
524 FileName
= Basename(LoaderPath
);
525 KernelVersion
= FindNumbers(FileName
);
526 Path
= FindPath(LoaderPath
);
528 // Add trailing backslash for root directory; necessary on some systems, but must
529 // NOT be added to all directories, since on other systems, a trailing backslash on
530 // anything but the root directory causes them to flake out!
531 if (StrLen(Path
) == 0) {
532 MergeStrings(&Path
, L
"\\", 0);
534 DirIterOpen(Volume
->RootDir
, Path
, &DirIter
);
535 // Now add a trailing backslash if it was NOT added earlier, for consistency in
536 // building the InitrdName later....
537 if ((StrLen(Path
) > 0) && (Path
[StrLen(Path
) - 1] != L
'\\'))
538 MergeStrings(&Path
, L
"\\", 0);
539 while ((DirIterNext(&DirIter
, 2, L
"init*", &DirEntry
)) && (InitrdName
== NULL
)) {
540 InitrdVersion
= FindNumbers(DirEntry
->FileName
);
541 if (KernelVersion
!= NULL
) {
542 if (MyStriCmp(InitrdVersion
, KernelVersion
)) {
543 InitrdName
= PoolPrint(L
"%s%s", Path
, DirEntry
->FileName
);
546 if (InitrdVersion
== NULL
) {
547 InitrdName
= PoolPrint(L
"%s%s", Path
, DirEntry
->FileName
);
550 MyFreePool(InitrdVersion
);
552 DirIterClose(&DirIter
);
554 // Note: Don't FreePool(FileName), since Basename returns a pointer WITHIN the string it's passed.
555 MyFreePool(KernelVersion
);
558 } // static CHAR16 * FindInitrd()
560 LOADER_ENTRY
* AddPreparedLoaderEntry(LOADER_ENTRY
*Entry
) {
561 AddMenuEntry(&MainMenu
, (REFIT_MENU_ENTRY
*)Entry
);
564 } // LOADER_ENTRY * AddPreparedLoaderEntry()
566 // Creates a copy of a menu screen.
567 // Returns a pointer to the copy of the menu screen.
568 static REFIT_MENU_SCREEN
* CopyMenuScreen(REFIT_MENU_SCREEN
*Entry
) {
569 REFIT_MENU_SCREEN
*NewEntry
;
572 NewEntry
= AllocateZeroPool(sizeof(REFIT_MENU_SCREEN
));
573 if ((Entry
!= NULL
) && (NewEntry
!= NULL
)) {
574 CopyMem(NewEntry
, Entry
, sizeof(REFIT_MENU_SCREEN
));
575 NewEntry
->Title
= (Entry
->Title
) ? StrDuplicate(Entry
->Title
) : NULL
;
576 NewEntry
->TimeoutText
= (Entry
->TimeoutText
) ? StrDuplicate(Entry
->TimeoutText
) : NULL
;
577 if (Entry
->TitleImage
!= NULL
) {
578 NewEntry
->TitleImage
= AllocatePool(sizeof(EG_IMAGE
));
579 if (NewEntry
->TitleImage
!= NULL
)
580 CopyMem(NewEntry
->TitleImage
, Entry
->TitleImage
, sizeof(EG_IMAGE
));
582 NewEntry
->InfoLines
= (CHAR16
**) AllocateZeroPool(Entry
->InfoLineCount
* (sizeof(CHAR16
*)));
583 for (i
= 0; i
< Entry
->InfoLineCount
&& NewEntry
->InfoLines
; i
++) {
584 NewEntry
->InfoLines
[i
] = (Entry
->InfoLines
[i
]) ? StrDuplicate(Entry
->InfoLines
[i
]) : NULL
;
586 NewEntry
->Entries
= (REFIT_MENU_ENTRY
**) AllocateZeroPool(Entry
->EntryCount
* (sizeof (REFIT_MENU_ENTRY
*)));
587 for (i
= 0; i
< Entry
->EntryCount
&& NewEntry
->Entries
; i
++) {
588 AddMenuEntry(NewEntry
, Entry
->Entries
[i
]);
590 NewEntry
->Hint1
= (Entry
->Hint1
) ? StrDuplicate(Entry
->Hint1
) : NULL
;
591 NewEntry
->Hint2
= (Entry
->Hint2
) ? StrDuplicate(Entry
->Hint2
) : NULL
;
594 } // static REFIT_MENU_SCREEN* CopyMenuScreen()
596 // Creates a copy of a menu entry. Intended to enable moving a stack-based
597 // menu entry (such as the ones for the "reboot" and "exit" functions) to
598 // to the heap. This enables easier deletion of the whole set of menu
599 // entries when re-scanning.
600 // Returns a pointer to the copy of the menu entry.
601 static REFIT_MENU_ENTRY
* CopyMenuEntry(REFIT_MENU_ENTRY
*Entry
) {
602 REFIT_MENU_ENTRY
*NewEntry
;
604 NewEntry
= AllocateZeroPool(sizeof(REFIT_MENU_ENTRY
));
605 if ((Entry
!= NULL
) && (NewEntry
!= NULL
)) {
606 CopyMem(NewEntry
, Entry
, sizeof(REFIT_MENU_ENTRY
));
607 NewEntry
->Title
= (Entry
->Title
) ? StrDuplicate(Entry
->Title
) : NULL
;
608 if (Entry
->BadgeImage
!= NULL
) {
609 NewEntry
->BadgeImage
= AllocatePool(sizeof(EG_IMAGE
));
610 if (NewEntry
->BadgeImage
!= NULL
)
611 CopyMem(NewEntry
->BadgeImage
, Entry
->BadgeImage
, sizeof(EG_IMAGE
));
613 if (Entry
->Image
!= NULL
) {
614 NewEntry
->Image
= AllocatePool(sizeof(EG_IMAGE
));
615 if (NewEntry
->Image
!= NULL
)
616 CopyMem(NewEntry
->Image
, Entry
->Image
, sizeof(EG_IMAGE
));
618 if (Entry
->SubScreen
!= NULL
) {
619 NewEntry
->SubScreen
= CopyMenuScreen(Entry
->SubScreen
);
623 } // REFIT_MENU_ENTRY* CopyMenuEntry()
625 // Creates a new LOADER_ENTRY data structure and populates it with
626 // default values from the specified Entry, or NULL values if Entry
627 // is unspecified (NULL).
628 // Returns a pointer to the new data structure, or NULL if it
629 // couldn't be allocated
630 LOADER_ENTRY
*InitializeLoaderEntry(IN LOADER_ENTRY
*Entry
) {
631 LOADER_ENTRY
*NewEntry
= NULL
;
633 NewEntry
= AllocateZeroPool(sizeof(LOADER_ENTRY
));
634 if (NewEntry
!= NULL
) {
635 NewEntry
->me
.Title
= NULL
;
636 NewEntry
->me
.Tag
= TAG_LOADER
;
637 NewEntry
->Enabled
= TRUE
;
638 NewEntry
->UseGraphicsMode
= FALSE
;
639 NewEntry
->OSType
= 0;
641 NewEntry
->LoaderPath
= (Entry
->LoaderPath
) ? StrDuplicate(Entry
->LoaderPath
) : NULL
;
642 NewEntry
->VolName
= (Entry
->VolName
) ? StrDuplicate(Entry
->VolName
) : NULL
;
643 NewEntry
->DevicePath
= Entry
->DevicePath
;
644 NewEntry
->UseGraphicsMode
= Entry
->UseGraphicsMode
;
645 NewEntry
->LoadOptions
= (Entry
->LoadOptions
) ? StrDuplicate(Entry
->LoadOptions
) : NULL
;
646 NewEntry
->InitrdPath
= (Entry
->InitrdPath
) ? StrDuplicate(Entry
->InitrdPath
) : NULL
;
650 } // LOADER_ENTRY *InitializeLoaderEntry()
652 // Adds InitrdPath to Options, but only if Options doesn't already include an
653 // initrd= line. Done to enable overriding the default initrd selection in a
654 // refind_linux.conf file's options list.
655 // Returns a pointer to a new string. The calling function is responsible for
656 // freeing its memory.
657 static CHAR16
*AddInitrdToOptions(CHAR16
*Options
, CHAR16
*InitrdPath
) {
658 CHAR16
*NewOptions
= NULL
;
661 NewOptions
= StrDuplicate(Options
);
662 if ((InitrdPath
!= NULL
) && !StriSubCmp(L
"initrd=", Options
)) {
663 MergeStrings(&NewOptions
, L
"initrd=", L
' ');
664 MergeStrings(&NewOptions
, InitrdPath
, 0);
667 } // CHAR16 *AddInitrdToOptions()
669 // Prepare a REFIT_MENU_SCREEN data structure for a subscreen entry. This sets up
670 // the default entry that launches the boot loader using the same options as the
671 // main Entry does. Subsequent options can be added by the calling function.
672 // If a subscreen already exists in the Entry that's passed to this function,
673 // it's left unchanged and a pointer to it is returned.
674 // Returns a pointer to the new subscreen data structure, or NULL if there
675 // were problems allocating memory.
676 REFIT_MENU_SCREEN
*InitializeSubScreen(IN LOADER_ENTRY
*Entry
) {
677 CHAR16
*FileName
, *MainOptions
= NULL
;
678 REFIT_MENU_SCREEN
*SubScreen
= NULL
;
679 LOADER_ENTRY
*SubEntry
;
681 FileName
= Basename(Entry
->LoaderPath
);
682 if (Entry
->me
.SubScreen
== NULL
) { // No subscreen yet; initialize default entry....
683 SubScreen
= AllocateZeroPool(sizeof(REFIT_MENU_SCREEN
));
684 if (SubScreen
!= NULL
) {
685 SubScreen
->Title
= AllocateZeroPool(sizeof(CHAR16
) * 256);
686 SPrint(SubScreen
->Title
, 255, L
"Boot Options for %s on %s",
687 (Entry
->Title
!= NULL
) ? Entry
->Title
: FileName
, Entry
->VolName
);
688 SubScreen
->TitleImage
= Entry
->me
.Image
;
690 SubEntry
= InitializeLoaderEntry(Entry
);
691 if (SubEntry
!= NULL
) {
692 SubEntry
->me
.Title
= StrDuplicate(L
"Boot using default options");
693 MainOptions
= SubEntry
->LoadOptions
;
694 SubEntry
->LoadOptions
= AddInitrdToOptions(MainOptions
, SubEntry
->InitrdPath
);
695 MyFreePool(MainOptions
);
696 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
697 } // if (SubEntry != NULL)
698 SubScreen
->Hint1
= StrDuplicate(SUBSCREEN_HINT1
);
699 if (GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_EDITOR
) {
700 SubScreen
->Hint2
= StrDuplicate(SUBSCREEN_HINT2_NO_EDITOR
);
702 SubScreen
->Hint2
= StrDuplicate(SUBSCREEN_HINT2
);
704 } // if (SubScreen != NULL)
705 } else { // existing subscreen; less initialization, and just add new entry later....
706 SubScreen
= Entry
->me
.SubScreen
;
709 } // REFIT_MENU_SCREEN *InitializeSubScreen()
711 VOID
GenerateSubScreen(LOADER_ENTRY
*Entry
, IN REFIT_VOLUME
*Volume
, IN BOOLEAN GenerateReturn
) {
712 REFIT_MENU_SCREEN
*SubScreen
;
713 LOADER_ENTRY
*SubEntry
;
715 CHAR16 DiagsFileName
[256];
720 // create the submenu
721 if (StrLen(Entry
->Title
) == 0) {
722 MyFreePool(Entry
->Title
);
725 SubScreen
= InitializeSubScreen(Entry
);
727 // loader-specific submenu entries
728 if (Entry
->OSType
== 'M') { // entries for Mac OS X
730 SubEntry
= InitializeLoaderEntry(Entry
);
731 if (SubEntry
!= NULL
) {
732 SubEntry
->me
.Title
= L
"Boot Mac OS X with a 64-bit kernel";
733 SubEntry
->LoadOptions
= L
"arch=x86_64";
734 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
735 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
738 SubEntry
= InitializeLoaderEntry(Entry
);
739 if (SubEntry
!= NULL
) {
740 SubEntry
->me
.Title
= L
"Boot Mac OS X with a 32-bit kernel";
741 SubEntry
->LoadOptions
= L
"arch=i386";
742 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
743 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
747 if (!(GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_SINGLEUSER
)) {
748 SubEntry
= InitializeLoaderEntry(Entry
);
749 if (SubEntry
!= NULL
) {
750 SubEntry
->me
.Title
= L
"Boot Mac OS X in verbose mode";
751 SubEntry
->UseGraphicsMode
= FALSE
;
752 SubEntry
->LoadOptions
= L
"-v";
753 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
757 SubEntry
= InitializeLoaderEntry(Entry
);
758 if (SubEntry
!= NULL
) {
759 SubEntry
->me
.Title
= L
"Boot Mac OS X in verbose mode (64-bit)";
760 SubEntry
->UseGraphicsMode
= FALSE
;
761 SubEntry
->LoadOptions
= L
"-v arch=x86_64";
762 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
765 SubEntry
= InitializeLoaderEntry(Entry
);
766 if (SubEntry
!= NULL
) {
767 SubEntry
->me
.Title
= L
"Boot Mac OS X in verbose mode (32-bit)";
768 SubEntry
->UseGraphicsMode
= FALSE
;
769 SubEntry
->LoadOptions
= L
"-v arch=i386";
770 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
774 SubEntry
= InitializeLoaderEntry(Entry
);
775 if (SubEntry
!= NULL
) {
776 SubEntry
->me
.Title
= L
"Boot Mac OS X in single user mode";
777 SubEntry
->UseGraphicsMode
= FALSE
;
778 SubEntry
->LoadOptions
= L
"-v -s";
779 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
781 } // single-user mode allowed
783 if (!(GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_SAFEMODE
)) {
784 SubEntry
= InitializeLoaderEntry(Entry
);
785 if (SubEntry
!= NULL
) {
786 SubEntry
->me
.Title
= L
"Boot Mac OS X in safe mode";
787 SubEntry
->UseGraphicsMode
= FALSE
;
788 SubEntry
->LoadOptions
= L
"-v -x";
789 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
791 } // safe mode allowed
793 // check for Apple hardware diagnostics
794 StrCpy(DiagsFileName
, L
"System\\Library\\CoreServices\\.diagnostics\\diags.efi");
795 if (FileExists(Volume
->RootDir
, DiagsFileName
) && !(GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_HWTEST
)) {
796 SubEntry
= InitializeLoaderEntry(Entry
);
797 if (SubEntry
!= NULL
) {
798 SubEntry
->me
.Title
= L
"Run Apple Hardware Test";
799 MyFreePool(SubEntry
->LoaderPath
);
800 SubEntry
->LoaderPath
= StrDuplicate(DiagsFileName
);
801 SubEntry
->DevicePath
= FileDevicePath(Volume
->DeviceHandle
, SubEntry
->LoaderPath
);
802 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
803 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
805 } // if diagnostics entry found
807 } else if (Entry
->OSType
== 'L') { // entries for Linux kernels with EFI stub loaders
808 File
= ReadLinuxOptionsFile(Entry
->LoaderPath
, Volume
);
810 InitrdName
= FindInitrd(Entry
->LoaderPath
, Volume
);
811 TokenCount
= ReadTokenLine(File
, &TokenList
);
812 // first entry requires special processing, since it was initially set
813 // up with a default title but correct options by InitializeSubScreen(),
815 if ((TokenCount
> 1) && (SubScreen
->Entries
!= NULL
) && (SubScreen
->Entries
[0] != NULL
)) {
816 MyFreePool(SubScreen
->Entries
[0]->Title
);
817 SubScreen
->Entries
[0]->Title
= TokenList
[0] ? StrDuplicate(TokenList
[0]) : StrDuplicate(L
"Boot Linux");
819 FreeTokenLine(&TokenList
, &TokenCount
);
820 while ((TokenCount
= ReadTokenLine(File
, &TokenList
)) > 1) {
821 SubEntry
= InitializeLoaderEntry(Entry
);
822 SubEntry
->me
.Title
= TokenList
[0] ? StrDuplicate(TokenList
[0]) : StrDuplicate(L
"Boot Linux");
823 MyFreePool(SubEntry
->LoadOptions
);
824 SubEntry
->LoadOptions
= AddInitrdToOptions(TokenList
[1], InitrdName
);
825 FreeTokenLine(&TokenList
, &TokenCount
);
826 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_LINUX
;
827 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
829 MyFreePool(InitrdName
);
833 } else if (Entry
->OSType
== 'E') { // entries for ELILO
834 SubEntry
= InitializeLoaderEntry(Entry
);
835 if (SubEntry
!= NULL
) {
836 SubEntry
->me
.Title
= L
"Run ELILO in interactive mode";
837 SubEntry
->LoadOptions
= L
"-p";
838 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
839 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
842 SubEntry
= InitializeLoaderEntry(Entry
);
843 if (SubEntry
!= NULL
) {
844 SubEntry
->me
.Title
= L
"Boot Linux for a 17\" iMac or a 15\" MacBook Pro (*)";
845 SubEntry
->LoadOptions
= L
"-d 0 i17";
846 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
847 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
850 SubEntry
= InitializeLoaderEntry(Entry
);
851 if (SubEntry
!= NULL
) {
852 SubEntry
->me
.Title
= L
"Boot Linux for a 20\" iMac (*)";
853 SubEntry
->LoadOptions
= L
"-d 0 i20";
854 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
855 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
858 SubEntry
= InitializeLoaderEntry(Entry
);
859 if (SubEntry
!= NULL
) {
860 SubEntry
->me
.Title
= L
"Boot Linux for a Mac Mini (*)";
861 SubEntry
->LoadOptions
= L
"-d 0 mini";
862 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
863 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
866 AddMenuInfoLine(SubScreen
, L
"NOTE: This is an example. Entries");
867 AddMenuInfoLine(SubScreen
, L
"marked with (*) may not work.");
869 } else if (Entry
->OSType
== 'X') { // entries for xom.efi
870 // by default, skip the built-in selection and boot from hard disk only
871 Entry
->LoadOptions
= L
"-s -h";
873 SubEntry
= InitializeLoaderEntry(Entry
);
874 if (SubEntry
!= NULL
) {
875 SubEntry
->me
.Title
= L
"Boot Windows from Hard Disk";
876 SubEntry
->LoadOptions
= L
"-s -h";
877 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
878 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
881 SubEntry
= InitializeLoaderEntry(Entry
);
882 if (SubEntry
!= NULL
) {
883 SubEntry
->me
.Title
= L
"Boot Windows from CD-ROM";
884 SubEntry
->LoadOptions
= L
"-s -c";
885 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
886 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
889 SubEntry
= InitializeLoaderEntry(Entry
);
890 if (SubEntry
!= NULL
) {
891 SubEntry
->me
.Title
= L
"Run XOM in text mode";
892 SubEntry
->LoadOptions
= L
"-v";
893 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
894 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
896 } // entries for xom.efi
898 AddMenuEntry(SubScreen
, &MenuEntryReturn
);
899 Entry
->me
.SubScreen
= SubScreen
;
900 } // VOID GenerateSubScreen()
902 // Returns options for a Linux kernel. Reads them from an options file in the
903 // kernel's directory; and if present, adds an initrd= option for an initial
904 // RAM disk file with the same version number as the kernel file.
905 static CHAR16
* GetMainLinuxOptions(IN CHAR16
* LoaderPath
, IN REFIT_VOLUME
*Volume
) {
906 CHAR16
*Options
= NULL
, *InitrdName
, *FullOptions
= NULL
;
908 Options
= GetFirstOptionsFromFile(LoaderPath
, Volume
);
909 InitrdName
= FindInitrd(LoaderPath
, Volume
);
910 FullOptions
= AddInitrdToOptions(Options
, InitrdName
);
913 MyFreePool(InitrdName
);
914 return (FullOptions
);
915 } // static CHAR16 * GetMainLinuxOptions()
917 // Read the specified file and add values of "ID", "NAME", or "DISTRIB_ID" tokens to
918 // OSIconName list. Intended for adding Linux distribution clues gleaned from
919 // /etc/lsb-release and /etc/os-release files.
920 static VOID
ParseReleaseFile(CHAR16
**OSIconName
, REFIT_VOLUME
*Volume
, CHAR16
*FileName
) {
924 UINTN TokenCount
= 0;
926 if ((Volume
== NULL
) || (FileName
== NULL
) || (OSIconName
== NULL
) || (*OSIconName
== NULL
))
929 if (FileExists(Volume
->RootDir
, FileName
) &&
930 (ReadFile(Volume
->RootDir
, FileName
, &File
, &FileSize
) == EFI_SUCCESS
)) {
932 TokenCount
= ReadTokenLine(&File
, &TokenList
);
933 if ((TokenCount
> 1) && (MyStriCmp(TokenList
[0], L
"ID") ||
934 MyStriCmp(TokenList
[0], L
"NAME") ||
935 MyStriCmp(TokenList
[0], L
"DISTRIB_ID"))) {
936 MergeWords(OSIconName
, TokenList
[1], L
',');
938 FreeTokenLine(&TokenList
, &TokenCount
);
939 } while (TokenCount
> 0);
940 MyFreePool(File
.Buffer
);
942 } // VOID ParseReleaseFile()
944 // Try to guess the name of the Linux distribution & add that name to
946 static VOID
GuessLinuxDistribution(CHAR16
**OSIconName
, REFIT_VOLUME
*Volume
, CHAR16
*LoaderPath
) {
947 // If on Linux root fs, /etc/os-release or /etc/lsb-release file probably has clues....
948 ParseReleaseFile(OSIconName
, Volume
, L
"etc\\lsb-release");
949 ParseReleaseFile(OSIconName
, Volume
, L
"etc\\os-release");
951 // Search for clues in the kernel's filename....
952 if (StriSubCmp(L
".fc", LoaderPath
))
953 MergeStrings(OSIconName
, L
"fedora", L
',');
954 if (StriSubCmp(L
".el", LoaderPath
))
955 MergeStrings(OSIconName
, L
"redhat", L
',');
956 } // VOID GuessLinuxDistribution()
958 // Sets a few defaults for a loader entry -- mainly the icon, but also the OS type
959 // code and shortcut letter. For Linux EFI stub loaders, also sets kernel options
960 // that will (with luck) work fairly automatically.
961 VOID
SetLoaderDefaults(LOADER_ENTRY
*Entry
, CHAR16
*LoaderPath
, REFIT_VOLUME
*Volume
) {
962 CHAR16
*NameClues
, *PathOnly
, *NoExtension
, *OSIconName
= NULL
, *Temp
;
963 CHAR16 ShortcutLetter
= 0;
965 NameClues
= Basename(LoaderPath
);
966 PathOnly
= FindPath(LoaderPath
);
967 NoExtension
= StripEfiExtension(NameClues
);
969 if (Volume
->DiskKind
== DISK_KIND_NET
) {
970 MergeStrings(&NameClues
, Entry
->me
.Title
, L
' ');
972 // locate a custom icon for the loader
973 // Anything found here takes precedence over the "hints" in the OSIconName variable
974 if (!Entry
->me
.Image
) {
975 Entry
->me
.Image
= egLoadIconAnyType(Volume
->RootDir
, PathOnly
, NoExtension
, GlobalConfig
.IconSizes
[ICON_SIZE_BIG
]);
977 if (!Entry
->me
.Image
) {
978 Entry
->me
.Image
= egCopyImage(Volume
->VolIconImage
);
981 // Begin creating icon "hints" by using last part of directory path leading
983 Temp
= FindLastDirName(LoaderPath
);
984 MergeStrings(&OSIconName
, Temp
, L
',');
987 if (OSIconName
!= NULL
) {
988 ShortcutLetter
= OSIconName
[0];
991 // Add every "word" in the volume label, delimited by spaces, dashes (-), or
992 // underscores (_), to the list of hints to be used in searching for OS
994 MergeWords(&OSIconName
, Volume
->VolName
, L
',');
995 } // if/else network boot
997 // detect specific loaders
998 if (StriSubCmp(L
"bzImage", NameClues
) || StriSubCmp(L
"vmlinuz", NameClues
)) {
999 if (Volume
->DiskKind
!= DISK_KIND_NET
) {
1000 GuessLinuxDistribution(&OSIconName
, Volume
, LoaderPath
);
1001 Entry
->LoadOptions
= GetMainLinuxOptions(LoaderPath
, Volume
);
1003 MergeStrings(&OSIconName
, L
"linux", L
',');
1004 Entry
->OSType
= 'L';
1005 if (ShortcutLetter
== 0)
1006 ShortcutLetter
= 'L';
1007 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_LINUX
;
1008 } else if (StriSubCmp(L
"refit", LoaderPath
)) {
1009 MergeStrings(&OSIconName
, L
"refit", L
',');
1010 Entry
->OSType
= 'R';
1011 ShortcutLetter
= 'R';
1012 } else if (StriSubCmp(L
"refind", LoaderPath
)) {
1013 MergeStrings(&OSIconName
, L
"refind", L
',');
1014 Entry
->OSType
= 'R';
1015 ShortcutLetter
= 'R';
1016 } else if (MyStriCmp(LoaderPath
, MACOSX_LOADER_PATH
)) {
1017 MergeStrings(&OSIconName
, L
"mac", L
',');
1018 Entry
->OSType
= 'M';
1019 ShortcutLetter
= 'M';
1020 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
1021 } else if (MyStriCmp(NameClues
, L
"diags.efi")) {
1022 MergeStrings(&OSIconName
, L
"hwtest", L
',');
1023 } else if (MyStriCmp(NameClues
, L
"e.efi") || MyStriCmp(NameClues
, L
"elilo.efi") || StriSubCmp(L
"elilo", NameClues
)) {
1024 MergeStrings(&OSIconName
, L
"elilo,linux", L
',');
1025 Entry
->OSType
= 'E';
1026 if (ShortcutLetter
== 0)
1027 ShortcutLetter
= 'L';
1028 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
1029 } else if (StriSubCmp(L
"grub", NameClues
)) {
1030 MergeStrings(&OSIconName
, L
"grub,linux", L
',');
1031 Entry
->OSType
= 'G';
1032 ShortcutLetter
= 'G';
1033 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_GRUB
;
1034 } else if (MyStriCmp(NameClues
, L
"cdboot.efi") ||
1035 MyStriCmp(NameClues
, L
"bootmgr.efi") ||
1036 MyStriCmp(NameClues
, L
"bootmgfw.efi") ||
1037 MyStriCmp(NameClues
, L
"bkpbootmgfw.efi")) {
1038 MergeStrings(&OSIconName
, L
"win8", L
',');
1039 Entry
->OSType
= 'W';
1040 ShortcutLetter
= 'W';
1041 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
1042 } else if (MyStriCmp(NameClues
, L
"xom.efi")) {
1043 MergeStrings(&OSIconName
, L
"xom,win,win8", L
',');
1044 Entry
->OSType
= 'X';
1045 ShortcutLetter
= 'W';
1046 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
1048 else if (StriSubCmp(L
"ipxe", NameClues
)) {
1049 Entry
->OSType
= 'N';
1050 ShortcutLetter
= 'N';
1051 MergeStrings(&OSIconName
, L
"network", L
',');
1054 if ((ShortcutLetter
>= 'a') && (ShortcutLetter
<= 'z'))
1055 ShortcutLetter
= ShortcutLetter
- 'a' + 'A'; // convert lowercase to uppercase
1056 Entry
->me
.ShortcutLetter
= ShortcutLetter
;
1057 if (Entry
->me
.Image
== NULL
)
1058 Entry
->me
.Image
= LoadOSIcon(OSIconName
, L
"unknown", FALSE
);
1059 MyFreePool(PathOnly
);
1060 } // VOID SetLoaderDefaults()
1062 // Add a specified EFI boot loader to the list, using automatic settings
1063 // for icons, options, etc.
1064 static LOADER_ENTRY
* AddLoaderEntry(IN CHAR16
*LoaderPath
, IN CHAR16
*LoaderTitle
, IN REFIT_VOLUME
*Volume
, IN BOOLEAN SubScreenReturn
) {
1065 LOADER_ENTRY
*Entry
;
1067 CleanUpPathNameSlashes(LoaderPath
);
1068 Entry
= InitializeLoaderEntry(NULL
);
1069 if (Entry
!= NULL
) {
1070 Entry
->Title
= StrDuplicate((LoaderTitle
!= NULL
) ? LoaderTitle
: LoaderPath
);
1071 Entry
->me
.Title
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1072 // Extra space at end of Entry->me.Title enables searching on Volume->VolName even if another volume
1073 // name is identical except for something added to the end (e.g., VolB1 vs. VolB12).
1074 // Note: Volume->VolName will be NULL for network boot programs.
1075 if (Volume
->VolName
)
1076 SPrint(Entry
->me
.Title
, 255, L
"Boot %s from %s ", (LoaderTitle
!= NULL
) ? LoaderTitle
: LoaderPath
, Volume
->VolName
);
1078 SPrint(Entry
->me
.Title
, 255, L
"Boot %s ", (LoaderTitle
!= NULL
) ? LoaderTitle
: LoaderPath
);
1080 Entry
->me
.BadgeImage
= Volume
->VolBadgeImage
;
1081 if ((LoaderPath
!= NULL
) && (LoaderPath
[0] != L
'\\')) {
1082 Entry
->LoaderPath
= StrDuplicate(L
"\\");
1084 Entry
->LoaderPath
= NULL
;
1086 MergeStrings(&(Entry
->LoaderPath
), LoaderPath
, 0);
1087 Entry
->VolName
= Volume
->VolName
;
1088 Entry
->DevicePath
= FileDevicePath(Volume
->DeviceHandle
, Entry
->LoaderPath
);
1089 SetLoaderDefaults(Entry
, LoaderPath
, Volume
);
1090 GenerateSubScreen(Entry
, Volume
, SubScreenReturn
);
1091 AddMenuEntry(&MainMenu
, (REFIT_MENU_ENTRY
*)Entry
);
1095 } // LOADER_ENTRY * AddLoaderEntry()
1097 // Add a Linux kernel as a submenu entry for another (pre-existing) Linux kernel entry.
1098 static VOID
AddKernelToSubmenu(LOADER_ENTRY
* TargetLoader
, CHAR16
*FileName
, REFIT_VOLUME
*Volume
) {
1100 CHAR16
**TokenList
= NULL
, *InitrdName
, *SubmenuName
= NULL
, *VolName
= NULL
, *Path
= NULL
, *Title
;
1101 REFIT_MENU_SCREEN
*SubScreen
;
1102 LOADER_ENTRY
*SubEntry
;
1105 File
= ReadLinuxOptionsFile(TargetLoader
->LoaderPath
, Volume
);
1107 SubScreen
= TargetLoader
->me
.SubScreen
;
1108 InitrdName
= FindInitrd(FileName
, Volume
);
1109 while ((TokenCount
= ReadTokenLine(File
, &TokenList
)) > 1) {
1110 SubEntry
= InitializeLoaderEntry(TargetLoader
);
1111 SplitPathName(FileName
, &VolName
, &Path
, &SubmenuName
);
1112 MergeStrings(&SubmenuName
, L
": ", '\0');
1113 MergeStrings(&SubmenuName
, TokenList
[0] ? StrDuplicate(TokenList
[0]) : StrDuplicate(L
"Boot Linux"), '\0');
1114 Title
= StrDuplicate(SubmenuName
);
1115 LimitStringLength(Title
, MAX_LINE_LENGTH
);
1116 SubEntry
->me
.Title
= Title
;
1117 MyFreePool(SubEntry
->LoadOptions
);
1118 SubEntry
->LoadOptions
= AddInitrdToOptions(TokenList
[1], InitrdName
);
1119 MyFreePool(SubEntry
->LoaderPath
);
1120 SubEntry
->LoaderPath
= StrDuplicate(FileName
);
1121 CleanUpPathNameSlashes(SubEntry
->LoaderPath
);
1122 SubEntry
->DevicePath
= FileDevicePath(Volume
->DeviceHandle
, SubEntry
->LoaderPath
);
1123 FreeTokenLine(&TokenList
, &TokenCount
);
1124 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_LINUX
;
1125 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
1127 MyFreePool(VolName
);
1129 MyFreePool(SubmenuName
);
1130 MyFreePool(InitrdName
);
1133 } // static VOID AddKernelToSubmenu()
1135 // Returns -1 if (Time1 < Time2), +1 if (Time1 > Time2), or 0 if
1136 // (Time1 == Time2). Precision is only to the nearest second; since
1137 // this is used for sorting boot loader entries, differences smaller
1138 // than this are likely to be meaningless (and unlikely!).
1139 INTN
TimeComp(IN EFI_TIME
*Time1
, IN EFI_TIME
*Time2
) {
1140 INT64 Time1InSeconds
, Time2InSeconds
;
1142 // Following values are overestimates; I'm assuming 31 days in every month.
1143 // This is fine for the purpose of this function, which is limited
1144 Time1InSeconds
= Time1
->Second
+ (Time1
->Minute
* 60) + (Time1
->Hour
* 3600) + (Time1
->Day
* 86400) +
1145 (Time1
->Month
* 2678400) + ((Time1
->Year
- 1998) * 32140800);
1146 Time2InSeconds
= Time2
->Second
+ (Time2
->Minute
* 60) + (Time2
->Hour
* 3600) + (Time2
->Day
* 86400) +
1147 (Time2
->Month
* 2678400) + ((Time2
->Year
- 1998) * 32140800);
1148 if (Time1InSeconds
< Time2InSeconds
)
1150 else if (Time1InSeconds
> Time2InSeconds
)
1154 } // INTN TimeComp()
1156 // Adds a loader list element, keeping it sorted by date. Returns the new
1157 // first element (the one with the most recent date).
1158 static struct LOADER_LIST
* AddLoaderListEntry(struct LOADER_LIST
*LoaderList
, struct LOADER_LIST
*NewEntry
) {
1159 struct LOADER_LIST
*LatestEntry
, *CurrentEntry
, *PrevEntry
= NULL
;
1161 LatestEntry
= CurrentEntry
= LoaderList
;
1162 if (LoaderList
== NULL
) {
1163 LatestEntry
= NewEntry
;
1165 while ((CurrentEntry
!= NULL
) && (TimeComp(&(NewEntry
->TimeStamp
), &(CurrentEntry
->TimeStamp
)) < 0)) {
1166 PrevEntry
= CurrentEntry
;
1167 CurrentEntry
= CurrentEntry
->NextEntry
;
1169 NewEntry
->NextEntry
= CurrentEntry
;
1170 if (PrevEntry
== NULL
) {
1171 LatestEntry
= NewEntry
;
1173 PrevEntry
->NextEntry
= NewEntry
;
1176 return (LatestEntry
);
1177 } // static VOID AddLoaderListEntry()
1179 // Delete the LOADER_LIST linked list
1180 static VOID
CleanUpLoaderList(struct LOADER_LIST
*LoaderList
) {
1181 struct LOADER_LIST
*Temp
;
1183 while (LoaderList
!= NULL
) {
1185 LoaderList
= LoaderList
->NextEntry
;
1186 MyFreePool(Temp
->FileName
);
1189 } // static VOID CleanUpLoaderList()
1191 // Returns FALSE if the specified file/volume matches the GlobalConfig.DontScanDirs
1192 // or GlobalConfig.DontScanVolumes specification, or if Path points to a volume
1193 // other than the one specified by Volume, or if the specified path is SelfDir.
1194 // Returns TRUE if none of these conditions is met -- that is, if the path is
1195 // eligible for scanning.
1196 static BOOLEAN
ShouldScan(REFIT_VOLUME
*Volume
, CHAR16
*Path
) {
1197 CHAR16
*VolName
= NULL
, *DontScanDir
, *PathCopy
= NULL
;
1199 BOOLEAN ScanIt
= TRUE
;
1201 if ((IsIn(Volume
->VolName
, GlobalConfig
.DontScanVolumes
)) || (IsIn(Volume
->PartName
, GlobalConfig
.DontScanVolumes
)))
1204 if (MyStriCmp(Path
, SelfDirPath
) && (Volume
->DeviceHandle
== SelfVolume
->DeviceHandle
))
1207 // See if Path includes an explicit volume declaration that's NOT Volume....
1208 PathCopy
= StrDuplicate(Path
);
1209 if (SplitVolumeAndFilename(&PathCopy
, &VolName
)) {
1210 VolumeNumberToName(Volume
, &VolName
);
1211 if (VolName
&& !MyStriCmp(VolName
, Volume
->VolName
)) {
1214 } // if Path includes volume specification
1215 MyFreePool(PathCopy
);
1216 MyFreePool(VolName
);
1219 // See if Volume is in GlobalConfig.DontScanDirs....
1220 while (ScanIt
&& (DontScanDir
= FindCommaDelimited(GlobalConfig
.DontScanDirs
, i
++))) {
1221 SplitVolumeAndFilename(&DontScanDir
, &VolName
);
1222 CleanUpPathNameSlashes(DontScanDir
);
1223 VolumeNumberToName(Volume
, &VolName
);
1224 if (VolName
!= NULL
) {
1225 if (MyStriCmp(VolName
, Volume
->VolName
) && MyStriCmp(DontScanDir
, Path
))
1228 if (MyStriCmp(DontScanDir
, Path
))
1231 MyFreePool(DontScanDir
);
1232 MyFreePool(VolName
);
1238 } // BOOLEAN ShouldScan()
1240 // Returns TRUE if the file is byte-for-byte identical with the fallback file
1241 // on the volume AND if the file is not itself the fallback file; returns
1242 // FALSE if the file is not identical to the fallback file OR if the file
1243 // IS the fallback file. Intended for use in excluding the fallback boot
1244 // loader when it's a duplicate of another boot loader.
1245 static BOOLEAN
DuplicatesFallback(IN REFIT_VOLUME
*Volume
, IN CHAR16
*FileName
) {
1246 CHAR8
*FileContents
, *FallbackContents
;
1247 EFI_FILE_HANDLE FileHandle
, FallbackHandle
;
1248 EFI_FILE_INFO
*FileInfo
, *FallbackInfo
;
1249 UINTN FileSize
= 0, FallbackSize
= 0;
1251 BOOLEAN AreIdentical
= FALSE
;
1253 if (!FileExists(Volume
->RootDir
, FileName
) || !FileExists(Volume
->RootDir
, FALLBACK_FULLNAME
))
1256 CleanUpPathNameSlashes(FileName
);
1258 if (MyStriCmp(FileName
, FALLBACK_FULLNAME
))
1259 return FALSE
; // identical filenames, so not a duplicate....
1261 Status
= refit_call5_wrapper(Volume
->RootDir
->Open
, Volume
->RootDir
, &FileHandle
, FileName
, EFI_FILE_MODE_READ
, 0);
1262 if (Status
== EFI_SUCCESS
) {
1263 FileInfo
= LibFileInfo(FileHandle
);
1264 FileSize
= FileInfo
->FileSize
;
1269 Status
= refit_call5_wrapper(Volume
->RootDir
->Open
, Volume
->RootDir
, &FallbackHandle
, FALLBACK_FULLNAME
, EFI_FILE_MODE_READ
, 0);
1270 if (Status
== EFI_SUCCESS
) {
1271 FallbackInfo
= LibFileInfo(FallbackHandle
);
1272 FallbackSize
= FallbackInfo
->FileSize
;
1274 refit_call1_wrapper(FileHandle
->Close
, FileHandle
);
1278 if (FallbackSize
!= FileSize
) { // not same size, so can't be identical
1279 AreIdentical
= FALSE
;
1280 } else { // could be identical; do full check....
1281 FileContents
= AllocatePool(FileSize
);
1282 FallbackContents
= AllocatePool(FallbackSize
);
1283 if (FileContents
&& FallbackContents
) {
1284 Status
= refit_call3_wrapper(FileHandle
->Read
, FileHandle
, &FileSize
, FileContents
);
1285 if (Status
== EFI_SUCCESS
) {
1286 Status
= refit_call3_wrapper(FallbackHandle
->Read
, FallbackHandle
, &FallbackSize
, FallbackContents
);
1288 if (Status
== EFI_SUCCESS
) {
1289 AreIdentical
= (CompareMem(FileContents
, FallbackContents
, FileSize
) == 0);
1292 MyFreePool(FileContents
);
1293 MyFreePool(FallbackContents
);
1296 // BUG ALERT: Some systems (e.g., DUET, some Macs with large displays) crash if the
1297 // following two calls are reversed. Go figure....
1298 refit_call1_wrapper(FileHandle
->Close
, FallbackHandle
);
1299 refit_call1_wrapper(FileHandle
->Close
, FileHandle
);
1300 return AreIdentical
;
1301 } // BOOLEAN DuplicatesFallback()
1303 // Returns FALSE if two measures of file size are identical for a single file,
1304 // TRUE if not or if the file can't be opened and the other measure is non-0.
1305 // Despite the function's name, this isn't really a direct test of symbolic
1306 // link status, since EFI doesn't officially support symlinks. It does seem
1307 // to be a reliable indicator, though. (OTOH, some disk errors might cause a
1308 // file to fail to open, which would return a false positive -- but as I use
1309 // this function to exclude symbolic links from the list of boot loaders,
1310 // that would be fine, since such boot loaders wouldn't work.)
1311 static BOOLEAN
IsSymbolicLink(REFIT_VOLUME
*Volume
, CHAR16
*Path
, EFI_FILE_INFO
*DirEntry
) {
1312 EFI_FILE_HANDLE FileHandle
;
1313 EFI_FILE_INFO
*FileInfo
= NULL
;
1315 UINTN FileSize2
= 0;
1318 FileName
= StrDuplicate(Path
);
1319 MergeStrings(&FileName
, DirEntry
->FileName
, L
'\\');
1320 CleanUpPathNameSlashes(FileName
);
1322 Status
= refit_call5_wrapper(Volume
->RootDir
->Open
, Volume
->RootDir
, &FileHandle
, FileName
, EFI_FILE_MODE_READ
, 0);
1323 if (Status
== EFI_SUCCESS
) {
1324 FileInfo
= LibFileInfo(FileHandle
);
1325 if (FileInfo
!= NULL
)
1326 FileSize2
= FileInfo
->FileSize
;
1329 MyFreePool(FileName
);
1330 MyFreePool(FileInfo
);
1332 return (DirEntry
->FileSize
!= FileSize2
);
1333 } // BOOLEAN IsSymbolicLink()
1335 // Returns TRUE if a file with the same name as the original but with
1336 // ".efi.signed" is also present in the same directory. Ubuntu is using
1337 // this filename as a signed version of the original unsigned kernel, and
1338 // there's no point in cluttering the display with two kernels that will
1339 // behave identically on non-SB systems, or when one will fail when SB
1341 static BOOLEAN
HasSignedCounterpart(IN REFIT_VOLUME
*Volume
, IN CHAR16
*Path
, IN CHAR16
*Filename
) {
1342 CHAR16
*NewFile
= NULL
;
1343 BOOLEAN retval
= FALSE
;
1345 MergeStrings(&NewFile
, Path
, 0);
1346 MergeStrings(&NewFile
, Filename
, L
'\\');
1347 MergeStrings(&NewFile
, L
".efi.signed", 0);
1348 if (NewFile
!= NULL
) {
1349 CleanUpPathNameSlashes(NewFile
);
1350 if (FileExists(Volume
->RootDir
, NewFile
))
1352 MyFreePool(NewFile
);
1356 } // BOOLEAN HasSignedCounterpart()
1358 // Scan an individual directory for EFI boot loader files and, if found,
1359 // add them to the list. Exception: Ignores FALLBACK_FULLNAME, which is picked
1360 // up in ScanEfiFiles(). Sorts the entries within the loader directory so that
1361 // the most recent one appears first in the list.
1362 // Returns TRUE if a duplicate for FALLBACK_FILENAME was found, FALSE if not.
1363 static BOOLEAN
ScanLoaderDir(IN REFIT_VOLUME
*Volume
, IN CHAR16
*Path
, IN CHAR16
*Pattern
)
1366 REFIT_DIR_ITER DirIter
;
1367 EFI_FILE_INFO
*DirEntry
;
1368 CHAR16 FileName
[256], *Extension
;
1369 struct LOADER_LIST
*LoaderList
= NULL
, *NewLoader
;
1370 LOADER_ENTRY
*FirstKernel
= NULL
, *LatestEntry
= NULL
;
1371 BOOLEAN FoundFallbackDuplicate
= FALSE
, IsLinux
= FALSE
, InSelfPath
;
1373 InSelfPath
= MyStriCmp(Path
, SelfDirPath
);
1374 if ((!SelfDirPath
|| !Path
|| (InSelfPath
&& (Volume
->DeviceHandle
!= SelfVolume
->DeviceHandle
)) ||
1375 (!InSelfPath
)) && (ShouldScan(Volume
, Path
))) {
1376 // look through contents of the directory
1377 DirIterOpen(Volume
->RootDir
, Path
, &DirIter
);
1378 while (DirIterNext(&DirIter
, 2, Pattern
, &DirEntry
)) {
1379 Extension
= FindExtension(DirEntry
->FileName
);
1380 if (DirEntry
->FileName
[0] == '.' ||
1381 MyStriCmp(Extension
, L
".icns") ||
1382 MyStriCmp(Extension
, L
".png") ||
1383 (MyStriCmp(DirEntry
->FileName
, FALLBACK_BASENAME
) && (MyStriCmp(Path
, L
"EFI\\BOOT"))) ||
1384 StriSubCmp(L
"shell", DirEntry
->FileName
) ||
1385 IsSymbolicLink(Volume
, Path
, DirEntry
) || /* is symbolic link */
1386 HasSignedCounterpart(Volume
, Path
, DirEntry
->FileName
) || /* a file with same name plus ".efi.signed" is present */
1387 FilenameIn(Volume
, Path
, DirEntry
->FileName
, GlobalConfig
.DontScanFiles
))
1388 continue; // skip this
1391 SPrint(FileName
, 255, L
"\\%s\\%s", Path
, DirEntry
->FileName
);
1393 SPrint(FileName
, 255, L
"\\%s", DirEntry
->FileName
);
1394 CleanUpPathNameSlashes(FileName
);
1396 if(!IsValidLoader(Volume
->RootDir
, FileName
))
1399 NewLoader
= AllocateZeroPool(sizeof(struct LOADER_LIST
));
1400 if (NewLoader
!= NULL
) {
1401 NewLoader
->FileName
= StrDuplicate(FileName
);
1402 NewLoader
->TimeStamp
= DirEntry
->ModificationTime
;
1403 LoaderList
= AddLoaderListEntry(LoaderList
, NewLoader
);
1404 if (DuplicatesFallback(Volume
, FileName
))
1405 FoundFallbackDuplicate
= TRUE
;
1407 MyFreePool(Extension
);
1410 NewLoader
= LoaderList
;
1411 while (NewLoader
!= NULL
) {
1412 IsLinux
= (StriSubCmp(L
"bzImage", NewLoader
->FileName
) || StriSubCmp(L
"vmlinuz", NewLoader
->FileName
));
1413 if ((FirstKernel
!= NULL
) && IsLinux
&& GlobalConfig
.FoldLinuxKernels
) {
1414 AddKernelToSubmenu(FirstKernel
, NewLoader
->FileName
, Volume
);
1416 LatestEntry
= AddLoaderEntry(NewLoader
->FileName
, NULL
, Volume
, !(IsLinux
&& GlobalConfig
.FoldLinuxKernels
));
1417 if (IsLinux
&& (FirstKernel
== NULL
))
1418 FirstKernel
= LatestEntry
;
1420 NewLoader
= NewLoader
->NextEntry
;
1422 if ((NewLoader
!= NULL
) && (FirstKernel
!= NULL
) && IsLinux
&& GlobalConfig
.FoldLinuxKernels
)
1423 AddMenuEntry(FirstKernel
->me
.SubScreen
, &MenuEntryReturn
);
1425 CleanUpLoaderList(LoaderList
);
1426 Status
= DirIterClose(&DirIter
);
1427 // NOTE: EFI_INVALID_PARAMETER really is an error that should be reported;
1428 // but I've gotten reports from users who are getting this error occasionally
1429 // and I can't find anything wrong or reproduce the problem, so I'm putting
1430 // it down to buggy EFI implementations and ignoring that particular error....
1431 if ((Status
!= EFI_NOT_FOUND
) && (Status
!= EFI_INVALID_PARAMETER
)) {
1433 SPrint(FileName
, 255, L
"while scanning the %s directory", Path
);
1435 StrCpy(FileName
, L
"while scanning the root directory");
1436 CheckError(Status
, FileName
);
1437 } // if (Status != EFI_NOT_FOUND)
1438 } // if not scanning a blacklisted directory
1440 return FoundFallbackDuplicate
;
1441 } /* static VOID ScanLoaderDir() */
1443 // Run the IPXE_DISCOVER_NAME program, which obtains the IP address of the boot
1444 // server and the name of the boot file it delivers.
1445 CHAR16
* RuniPXEDiscover(EFI_HANDLE Volume
)
1448 EFI_DEVICE_PATH
*FilePath
;
1449 EFI_HANDLE iPXEHandle
;
1450 CHAR16
*boot_info
= NULL
;
1451 UINTN boot_info_size
= 0;
1453 FilePath
= FileDevicePath (Volume
, IPXE_DISCOVER_NAME
);
1454 Status
= refit_call6_wrapper(BS
->LoadImage
, FALSE
, SelfImageHandle
, FilePath
, NULL
, 0, &iPXEHandle
);
1458 Status
= refit_call3_wrapper(BS
->StartImage
, iPXEHandle
, &boot_info_size
, &boot_info
);
1461 } // RuniPXEDiscover()
1463 // Scan for network (PXE) boot servers. This function relies on the presence
1464 // of the IPXE_DISCOVER_NAME and IPXE_NAME program files on the volume from
1465 // which rEFInd launched. As of December 6, 2014, these tools aren't entirely
1466 // reliable. See BUILDING.txt for information on building them.
1467 static VOID
ScanNetboot() {
1468 CHAR16
*iPXEFileName
= IPXE_NAME
;
1470 REFIT_VOLUME
*NetVolume
;
1472 if (FileExists(SelfVolume
->RootDir
, IPXE_DISCOVER_NAME
) &&
1473 FileExists(SelfVolume
->RootDir
, IPXE_NAME
) &&
1474 IsValidLoader(SelfVolume
->RootDir
, IPXE_DISCOVER_NAME
) &&
1475 IsValidLoader(SelfVolume
->RootDir
, IPXE_NAME
)) {
1476 Location
= RuniPXEDiscover(SelfVolume
->DeviceHandle
);
1477 if (Location
!= NULL
&& FileExists(SelfVolume
->RootDir
, iPXEFileName
)) {
1478 NetVolume
= AllocatePool(sizeof(REFIT_VOLUME
));
1479 CopyMem(NetVolume
, SelfVolume
, sizeof(REFIT_VOLUME
));
1480 NetVolume
->DiskKind
= DISK_KIND_NET
;
1481 NetVolume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_NET
);
1482 NetVolume
->PartName
= NetVolume
->VolName
= NULL
;
1483 AddLoaderEntry(iPXEFileName
, Location
, NetVolume
, TRUE
);
1484 MyFreePool(NetVolume
);
1485 } // if support files exist and are valid
1487 } // VOID ScanNetBoot()
1489 static VOID
ScanEfiFiles(REFIT_VOLUME
*Volume
) {
1491 REFIT_DIR_ITER EfiDirIter
;
1492 EFI_FILE_INFO
*EfiDirEntry
;
1493 CHAR16 FileName
[256], *Directory
= NULL
, *MatchPatterns
, *VolName
= NULL
, *SelfPath
;
1495 BOOLEAN ScanFallbackLoader
= TRUE
;
1496 BOOLEAN FoundBRBackup
= FALSE
;
1498 if (Volume
&& (Volume
->RootDir
!= NULL
) && (Volume
->VolName
!= NULL
) && (Volume
->IsReadable
)) {
1499 MatchPatterns
= StrDuplicate(LOADER_MATCH_PATTERNS
);
1500 if (GlobalConfig
.ScanAllLinux
)
1501 MergeStrings(&MatchPatterns
, LINUX_MATCH_PATTERNS
, L
',');
1503 // check for Mac OS X boot loader
1504 if (ShouldScan(Volume
, MACOSX_LOADER_DIR
)) {
1505 StrCpy(FileName
, MACOSX_LOADER_PATH
);
1506 if (FileExists(Volume
->RootDir
, FileName
) && !FilenameIn(Volume
, MACOSX_LOADER_DIR
, L
"boot.efi", GlobalConfig
.DontScanFiles
)) {
1507 AddLoaderEntry(FileName
, L
"Mac OS X", Volume
, TRUE
);
1508 if (DuplicatesFallback(Volume
, FileName
))
1509 ScanFallbackLoader
= FALSE
;
1513 StrCpy(FileName
, L
"System\\Library\\CoreServices\\xom.efi");
1514 if (FileExists(Volume
->RootDir
, FileName
) && !FilenameIn(Volume
, MACOSX_LOADER_DIR
, L
"xom.efi", GlobalConfig
.DontScanFiles
)) {
1515 AddLoaderEntry(FileName
, L
"Windows XP (XoM)", Volume
, TRUE
);
1516 if (DuplicatesFallback(Volume
, FileName
))
1517 ScanFallbackLoader
= FALSE
;
1519 } // if should scan Mac directory
1521 // check for Microsoft boot loader/menu
1522 if (ShouldScan(Volume
, L
"EFI\\Microsoft\\Boot")) {
1523 StrCpy(FileName
, L
"EFI\\Microsoft\\Boot\\bkpbootmgfw.efi");
1524 if (FileExists(Volume
->RootDir
, FileName
) && !FilenameIn(Volume
, L
"EFI\\Microsoft\\Boot", L
"bkpbootmgfw.efi",
1525 GlobalConfig
.DontScanFiles
)) {
1526 AddLoaderEntry(FileName
, L
"Microsoft EFI boot (Boot Repair backup)", Volume
, TRUE
);
1527 FoundBRBackup
= TRUE
;
1528 if (DuplicatesFallback(Volume
, FileName
))
1529 ScanFallbackLoader
= FALSE
;
1531 StrCpy(FileName
, L
"EFI\\Microsoft\\Boot\\bootmgfw.efi");
1532 if (FileExists(Volume
->RootDir
, FileName
) &&
1533 !FilenameIn(Volume
, L
"EFI\\Microsoft\\Boot", L
"bootmgfw.efi", GlobalConfig
.DontScanFiles
)) {
1535 AddLoaderEntry(FileName
, L
"Supposed Microsoft EFI boot (probably GRUB)", Volume
, TRUE
);
1537 AddLoaderEntry(FileName
, L
"Microsoft EFI boot", Volume
, TRUE
);
1538 if (DuplicatesFallback(Volume
, FileName
))
1539 ScanFallbackLoader
= FALSE
;
1543 // scan the root directory for EFI executables
1544 if (ScanLoaderDir(Volume
, L
"\\", MatchPatterns
))
1545 ScanFallbackLoader
= FALSE
;
1547 // scan subdirectories of the EFI directory (as per the standard)
1548 DirIterOpen(Volume
->RootDir
, L
"EFI", &EfiDirIter
);
1549 while (DirIterNext(&EfiDirIter
, 1, NULL
, &EfiDirEntry
)) {
1550 if (MyStriCmp(EfiDirEntry
->FileName
, L
"tools") || EfiDirEntry
->FileName
[0] == '.')
1551 continue; // skip this, doesn't contain boot loaders or is scanned later
1552 SPrint(FileName
, 255, L
"EFI\\%s", EfiDirEntry
->FileName
);
1553 if (ScanLoaderDir(Volume
, FileName
, MatchPatterns
))
1554 ScanFallbackLoader
= FALSE
;
1556 Status
= DirIterClose(&EfiDirIter
);
1557 if ((Status
!= EFI_NOT_FOUND
) && (Status
!= EFI_INVALID_PARAMETER
))
1558 CheckError(Status
, L
"while scanning the EFI directory");
1560 // Scan user-specified (or additional default) directories....
1562 while ((Directory
= FindCommaDelimited(GlobalConfig
.AlsoScan
, i
++)) != NULL
) {
1563 if (ShouldScan(Volume
, Directory
)) {
1564 SplitVolumeAndFilename(&Directory
, &VolName
);
1565 CleanUpPathNameSlashes(Directory
);
1566 Length
= StrLen(Directory
);
1567 if ((Length
> 0) && ScanLoaderDir(Volume
, Directory
, MatchPatterns
))
1568 ScanFallbackLoader
= FALSE
;
1569 MyFreePool(VolName
);
1570 } // if should scan dir
1571 MyFreePool(Directory
);
1574 // Don't scan the fallback loader if it's on the same volume and a duplicate of rEFInd itself....
1575 SelfPath
= DevicePathToStr(SelfLoadedImage
->FilePath
);
1576 CleanUpPathNameSlashes(SelfPath
);
1577 if ((Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
) && DuplicatesFallback(Volume
, SelfPath
))
1578 ScanFallbackLoader
= FALSE
;
1580 // If not a duplicate & if it exists & if it's not us, create an entry
1581 // for the fallback boot loader
1582 if (ScanFallbackLoader
&& FileExists(Volume
->RootDir
, FALLBACK_FULLNAME
) && ShouldScan(Volume
, L
"EFI\\BOOT")) {
1583 AddLoaderEntry(FALLBACK_FULLNAME
, L
"Fallback boot loader", Volume
, TRUE
);
1586 } // static VOID ScanEfiFiles()
1588 // Scan internal disks for valid EFI boot loaders....
1589 static VOID
ScanInternal(VOID
) {
1592 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1593 if (Volumes
[VolumeIndex
]->DiskKind
== DISK_KIND_INTERNAL
) {
1594 ScanEfiFiles(Volumes
[VolumeIndex
]);
1597 } // static VOID ScanInternal()
1599 // Scan external disks for valid EFI boot loaders....
1600 static VOID
ScanExternal(VOID
) {
1603 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1604 if (Volumes
[VolumeIndex
]->DiskKind
== DISK_KIND_EXTERNAL
) {
1605 ScanEfiFiles(Volumes
[VolumeIndex
]);
1608 } // static VOID ScanExternal()
1610 // Scan internal disks for valid EFI boot loaders....
1611 static VOID
ScanOptical(VOID
) {
1614 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1615 if (Volumes
[VolumeIndex
]->DiskKind
== DISK_KIND_OPTICAL
) {
1616 ScanEfiFiles(Volumes
[VolumeIndex
]);
1619 } // static VOID ScanOptical()
1621 // default volume badge icon based on disk kind
1622 EG_IMAGE
* GetDiskBadge(IN UINTN DiskType
) {
1623 EG_IMAGE
* Badge
= NULL
;
1627 Badge
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
1630 Badge
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
1633 Badge
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
1637 } // EG_IMAGE * GetDiskBadge()
1640 // pre-boot tool functions
1643 static VOID
StartTool(IN LOADER_ENTRY
*Entry
)
1645 BeginExternalScreen(Entry
->UseGraphicsMode
, Entry
->me
.Title
+ 6); // assumes "Start <title>" as assigned below
1646 StoreLoaderName(Entry
->me
.Title
);
1647 StartEFIImage(Entry
->DevicePath
, Entry
->LoadOptions
, TYPE_EFI
,
1648 Basename(Entry
->LoaderPath
), Entry
->OSType
, NULL
, TRUE
, FALSE
);
1649 FinishExternalScreen();
1650 } /* static VOID StartTool() */
1652 static LOADER_ENTRY
* AddToolEntry(EFI_HANDLE DeviceHandle
, IN CHAR16
*LoaderPath
, IN CHAR16
*LoaderTitle
, IN EG_IMAGE
*Image
,
1653 IN CHAR16 ShortcutLetter
, IN BOOLEAN UseGraphicsMode
)
1655 LOADER_ENTRY
*Entry
;
1656 CHAR16
*TitleStr
= NULL
;
1658 Entry
= AllocateZeroPool(sizeof(LOADER_ENTRY
));
1660 TitleStr
= PoolPrint(L
"Start %s", LoaderTitle
);
1661 Entry
->me
.Title
= TitleStr
;
1662 Entry
->me
.Tag
= TAG_TOOL
;
1664 Entry
->me
.ShortcutLetter
= ShortcutLetter
;
1665 Entry
->me
.Image
= Image
;
1666 Entry
->LoaderPath
= (LoaderPath
) ? StrDuplicate(LoaderPath
) : NULL
;
1667 Entry
->DevicePath
= FileDevicePath(DeviceHandle
, Entry
->LoaderPath
);
1668 Entry
->UseGraphicsMode
= UseGraphicsMode
;
1670 AddMenuEntry(&MainMenu
, (REFIT_MENU_ENTRY
*)Entry
);
1672 } /* static LOADER_ENTRY * AddToolEntry() */
1675 // pre-boot driver functions
1678 static UINTN
ScanDriverDir(IN CHAR16
*Path
)
1681 REFIT_DIR_ITER DirIter
;
1683 EFI_FILE_INFO
*DirEntry
;
1684 CHAR16 FileName
[256];
1686 CleanUpPathNameSlashes(Path
);
1687 // look through contents of the directory
1688 DirIterOpen(SelfRootDir
, Path
, &DirIter
);
1689 while (DirIterNext(&DirIter
, 2, LOADER_MATCH_PATTERNS
, &DirEntry
)) {
1690 if (DirEntry
->FileName
[0] == '.')
1691 continue; // skip this
1693 SPrint(FileName
, 255, L
"%s\\%s", Path
, DirEntry
->FileName
);
1695 Status
= StartEFIImage(FileDevicePath(SelfLoadedImage
->DeviceHandle
, FileName
),
1696 L
"", TYPE_EFI
, DirEntry
->FileName
, 0, NULL
, FALSE
, TRUE
);
1698 Status
= DirIterClose(&DirIter
);
1699 if ((Status
!= EFI_NOT_FOUND
) && (Status
!= EFI_INVALID_PARAMETER
)) {
1700 SPrint(FileName
, 255, L
"while scanning the %s directory", Path
);
1701 CheckError(Status
, FileName
);
1706 #ifdef __MAKEWITH_GNUEFI
1707 static EFI_STATUS
ConnectAllDriversToAllControllers(VOID
)
1710 UINTN AllHandleCount
;
1711 EFI_HANDLE
*AllHandleBuffer
;
1714 EFI_HANDLE
*HandleBuffer
;
1720 Status
= LibLocateHandle(AllHandles
,
1725 if (EFI_ERROR(Status
))
1728 for (Index
= 0; Index
< AllHandleCount
; Index
++) {
1730 // Scan the handle database
1732 Status
= LibScanHandleDatabase(NULL
,
1734 AllHandleBuffer
[Index
],
1739 if (EFI_ERROR (Status
))
1743 if (HandleType
[Index
] & EFI_HANDLE_TYPE_DRIVER_BINDING_HANDLE
)
1745 if (HandleType
[Index
] & EFI_HANDLE_TYPE_IMAGE_HANDLE
)
1750 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1751 if (HandleType
[HandleIndex
] & EFI_HANDLE_TYPE_PARENT_HANDLE
)
1756 if (HandleType
[Index
] & EFI_HANDLE_TYPE_DEVICE_HANDLE
) {
1757 Status
= refit_call4_wrapper(BS
->ConnectController
,
1758 AllHandleBuffer
[Index
],
1766 MyFreePool (HandleBuffer
);
1767 MyFreePool (HandleType
);
1771 MyFreePool (AllHandleBuffer
);
1773 } /* EFI_STATUS ConnectAllDriversToAllControllers() */
1775 static EFI_STATUS
ConnectAllDriversToAllControllers(VOID
) {
1776 BdsLibConnectAllDriversToAllControllers();
1781 // Load all EFI drivers from rEFInd's "drivers" subdirectory and from the
1782 // directories specified by the user in the "scan_driver_dirs" configuration
1784 static VOID
LoadDrivers(VOID
)
1786 CHAR16
*Directory
, *SelfDirectory
;
1787 UINTN i
= 0, Length
, NumFound
= 0;
1789 // load drivers from the subdirectories of rEFInd's home directory specified
1790 // in the DRIVER_DIRS constant.
1791 while ((Directory
= FindCommaDelimited(DRIVER_DIRS
, i
++)) != NULL
) {
1792 SelfDirectory
= SelfDirPath
? StrDuplicate(SelfDirPath
) : NULL
;
1793 CleanUpPathNameSlashes(SelfDirectory
);
1794 MergeStrings(&SelfDirectory
, Directory
, L
'\\');
1795 NumFound
+= ScanDriverDir(SelfDirectory
);
1796 MyFreePool(Directory
);
1797 MyFreePool(SelfDirectory
);
1800 // Scan additional user-specified driver directories....
1802 while ((Directory
= FindCommaDelimited(GlobalConfig
.DriverDirs
, i
++)) != NULL
) {
1803 CleanUpPathNameSlashes(Directory
);
1804 Length
= StrLen(Directory
);
1806 NumFound
+= ScanDriverDir(Directory
);
1808 MyFreePool(Directory
);
1811 // connect all devices
1813 ConnectAllDriversToAllControllers();
1815 } /* static VOID LoadDrivers() */
1817 // Locates boot loaders. NOTE: This assumes that GlobalConfig.LegacyType is set correctly.
1818 static VOID
ScanForBootloaders(VOID
) {
1821 BOOLEAN ScanForLegacy
= FALSE
;
1823 // Determine up-front if we'll be scanning for legacy loaders....
1824 for (i
= 0; i
< NUM_SCAN_OPTIONS
; i
++) {
1825 s
= GlobalConfig
.ScanFor
[i
];
1826 if ((s
== 'c') || (s
== 'C') || (s
== 'h') || (s
== 'H') || (s
== 'b') || (s
== 'B'))
1827 ScanForLegacy
= TRUE
;
1830 // If UEFI & scanning for legacy loaders & deep legacy scan, update NVRAM boot manager list
1831 if ((GlobalConfig
.LegacyType
== LEGACY_TYPE_UEFI
) && ScanForLegacy
&& GlobalConfig
.DeepLegacyScan
) {
1832 BdsDeleteAllInvalidLegacyBootOptions();
1833 BdsAddNonExistingLegacyBootOptions();
1836 // scan for loaders and tools, add them to the menu
1837 for (i
= 0; i
< NUM_SCAN_OPTIONS
; i
++) {
1838 switch(GlobalConfig
.ScanFor
[i
]) {
1843 ScanLegacyInternal();
1846 ScanLegacyExternal();
1849 ScanUserConfigured(GlobalConfig
.ConfigFilename
);
1866 // assign shortcut keys
1867 for (i
= 0; i
< MainMenu
.EntryCount
&& MainMenu
.Entries
[i
]->Row
== 0 && i
< 9; i
++)
1868 MainMenu
.Entries
[i
]->ShortcutDigit
= (CHAR16
)('1' + i
);
1870 // wait for user ACK when there were errors
1871 FinishTextScreen(FALSE
);
1872 } // static VOID ScanForBootloaders()
1874 // Locate a single tool from the specified Locations using one of the
1875 // specified Names and add it to the menu.
1876 static VOID
FindTool(CHAR16
*Locations
, CHAR16
*Names
, CHAR16
*Description
, UINTN Icon
) {
1877 UINTN j
= 0, k
, VolumeIndex
;
1878 CHAR16
*DirName
, *FileName
, *PathName
, FullDescription
[256];
1880 while ((DirName
= FindCommaDelimited(Locations
, j
++)) != NULL
) {
1882 while ((FileName
= FindCommaDelimited(Names
, k
++)) != NULL
) {
1883 PathName
= StrDuplicate(DirName
);
1884 MergeStrings(&PathName
, FileName
, MyStriCmp(PathName
, L
"\\") ? 0 : L
'\\');
1885 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1886 if ((Volumes
[VolumeIndex
]->RootDir
!= NULL
) &&
1887 (FileExists(Volumes
[VolumeIndex
]->RootDir
, PathName
)) &&
1888 IsValidLoader(Volumes
[VolumeIndex
]->RootDir
, PathName
)) {
1889 SPrint(FullDescription
, 255, L
"%s at %s on %s", Description
, PathName
, Volumes
[VolumeIndex
]->VolName
);
1890 AddToolEntry(Volumes
[VolumeIndex
]->DeviceHandle
, PathName
, FullDescription
, BuiltinIcon(Icon
), 'S', FALSE
);
1893 MyFreePool(PathName
);
1894 MyFreePool(FileName
);
1896 MyFreePool(DirName
);
1897 } // while Locations
1898 } // VOID FindTool()
1900 // Add the second-row tags containing built-in and external tools (EFI shell,
1902 static VOID
ScanForTools(VOID
) {
1903 CHAR16
*FileName
= NULL
, *VolName
= NULL
, *MokLocations
, Description
[256];
1904 REFIT_MENU_ENTRY
*TempMenuEntry
;
1905 UINTN i
, j
, VolumeIndex
;
1909 MokLocations
= StrDuplicate(MOK_LOCATIONS
);
1910 if (MokLocations
!= NULL
)
1911 MergeStrings(&MokLocations
, SelfDirPath
, L
',');
1913 for (i
= 0; i
< NUM_TOOLS
; i
++) {
1914 switch(GlobalConfig
.ShowTools
[i
]) {
1915 // NOTE: Be sure that FileName is NULL at the end of each case.
1917 TempMenuEntry
= CopyMenuEntry(&MenuEntryShutdown
);
1918 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_SHUTDOWN
);
1919 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1923 TempMenuEntry
= CopyMenuEntry(&MenuEntryReset
);
1924 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_RESET
);
1925 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1929 TempMenuEntry
= CopyMenuEntry(&MenuEntryAbout
);
1930 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_ABOUT
);
1931 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1935 TempMenuEntry
= CopyMenuEntry(&MenuEntryExit
);
1936 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_EXIT
);
1937 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1941 if (EfivarGetRaw(&GlobalGuid
, L
"OsIndicationsSupported", &b
, &j
) == EFI_SUCCESS
) {
1943 if (osind
& EFI_OS_INDICATIONS_BOOT_TO_FW_UI
) {
1944 TempMenuEntry
= CopyMenuEntry(&MenuEntryFirmware
);
1945 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_FIRMWARE
);
1946 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1953 while ((FileName
= FindCommaDelimited(SHELL_NAMES
, j
++)) != NULL
) {
1954 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1955 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"EFI Shell", BuiltinIcon(BUILTIN_ICON_TOOL_SHELL
),
1958 MyFreePool(FileName
);
1964 while ((FileName
= FindCommaDelimited(GPTSYNC_NAMES
, j
++)) != NULL
) {
1965 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1966 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"Hybrid MBR tool", BuiltinIcon(BUILTIN_ICON_TOOL_PART
),
1969 MyFreePool(FileName
);
1976 while ((FileName
= FindCommaDelimited(GDISK_NAMES
, j
++)) != NULL
) {
1977 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1978 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"disk partitioning tool",
1979 BuiltinIcon(BUILTIN_ICON_TOOL_PART
), 'G', FALSE
);
1981 MyFreePool(FileName
);
1988 while ((FileName
= FindCommaDelimited(NETBOOT_NAMES
, j
++)) != NULL
) {
1989 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1990 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"Netboot",
1991 BuiltinIcon(BUILTIN_ICON_TOOL_NETBOOT
), 'N', FALSE
);
1993 MyFreePool(FileName
);
1998 case TAG_APPLE_RECOVERY
:
1999 FileName
= StrDuplicate(L
"\\com.apple.recovery.boot\\boot.efi");
2000 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
2001 if ((Volumes
[VolumeIndex
]->RootDir
!= NULL
) &&
2002 (FileExists(Volumes
[VolumeIndex
]->RootDir
, FileName
)) &&
2003 IsValidLoader(Volumes
[VolumeIndex
]->RootDir
, FileName
)) {
2004 SPrint(Description
, 255, L
"Apple Recovery on %s", Volumes
[VolumeIndex
]->VolName
);
2005 AddToolEntry(Volumes
[VolumeIndex
]->DeviceHandle
, FileName
, Description
,
2006 BuiltinIcon(BUILTIN_ICON_TOOL_APPLE_RESCUE
), 'R', TRUE
);
2009 MyFreePool(FileName
);
2013 case TAG_WINDOWS_RECOVERY
:
2015 while ((FileName
= FindCommaDelimited(GlobalConfig
.WindowsRecoveryFiles
, j
++)) != NULL
) {
2016 SplitVolumeAndFilename(&FileName
, &VolName
);
2017 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
2018 if ((Volumes
[VolumeIndex
]->RootDir
!= NULL
) &&
2019 (FileExists(Volumes
[VolumeIndex
]->RootDir
, FileName
)) &&
2020 IsValidLoader(Volumes
[VolumeIndex
]->RootDir
, FileName
) &&
2021 ((VolName
== NULL
) || MyStriCmp(VolName
, Volumes
[VolumeIndex
]->VolName
))) {
2022 SPrint(Description
, 255, L
"Microsoft Recovery on %s", Volumes
[VolumeIndex
]->VolName
);
2023 AddToolEntry(Volumes
[VolumeIndex
]->DeviceHandle
, FileName
, Description
,
2024 BuiltinIcon(BUILTIN_ICON_TOOL_WINDOWS_RESCUE
), 'R', TRUE
);
2028 MyFreePool(FileName
);
2030 MyFreePool(VolName
);
2035 FindTool(MokLocations
, MOK_NAMES
, L
"MOK utility", BUILTIN_ICON_TOOL_MOK_TOOL
);
2039 FindTool(MEMTEST_LOCATIONS
, MEMTEST_NAMES
, L
"Memory test utility", BUILTIN_ICON_TOOL_MEMTEST
);
2044 } // static VOID ScanForTools
2046 // Rescan for boot loaders
2047 static VOID
RescanAll(BOOLEAN DisplayMessage
) {
2055 egDisplayMessage(L
"Scanning for new boot loaders; please wait....", &BGColor
);
2056 FreeList((VOID
***) &(MainMenu
.Entries
), &MainMenu
.EntryCount
);
2057 MainMenu
.Entries
= NULL
;
2058 MainMenu
.EntryCount
= 0;
2059 ReadConfig(GlobalConfig
.ConfigFilename
);
2060 ConnectAllDriversToAllControllers();
2062 ScanForBootloaders();
2065 } // VOID RescanAll()
2067 #ifdef __MAKEWITH_TIANO
2069 // Minimal initialization function
2070 static VOID
InitializeLib(IN EFI_HANDLE ImageHandle
, IN EFI_SYSTEM_TABLE
*SystemTable
) {
2072 // gImageHandle = ImageHandle;
2073 gBS
= SystemTable
->BootServices
;
2074 // gRS = SystemTable->RuntimeServices;
2075 gRT
= SystemTable
->RuntimeServices
; // Some BDS functions need gRT to be set
2076 EfiGetSystemConfigurationTable (&gEfiDxeServicesTableGuid
, (VOID
**) &gDS
);
2081 // Set up our own Secure Boot extensions....
2082 // Returns TRUE on success, FALSE otherwise
2083 static BOOLEAN
SecureBootSetup(VOID
) {
2085 BOOLEAN Success
= FALSE
;
2087 if (secure_mode() && ShimLoaded()) {
2088 Status
= security_policy_install();
2089 if (Status
== EFI_SUCCESS
) {
2092 Print(L
"Failed to install MOK Secure Boot extensions");
2097 } // VOID SecureBootSetup()
2099 // Remove our own Secure Boot extensions....
2100 // Returns TRUE on success, FALSE otherwise
2101 static BOOLEAN
SecureBootUninstall(VOID
) {
2103 BOOLEAN Success
= TRUE
;
2105 if (secure_mode()) {
2106 Status
= security_policy_uninstall();
2107 if (Status
!= EFI_SUCCESS
) {
2109 BeginTextScreen(L
"Secure Boot Policy Failure");
2110 Print(L
"Failed to uninstall MOK Secure Boot extensions; forcing a reboot.");
2112 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);
2116 } // VOID SecureBootUninstall
2118 // Sets the global configuration filename; will be CONFIG_FILE_NAME unless the
2119 // "-c" command-line option is set, in which case that takes precedence.
2120 // If an error is encountered, leaves the value alone (it should be set to
2121 // CONFIG_FILE_NAME when GlobalConfig is initialized).
2122 static VOID
SetConfigFilename(EFI_HANDLE ImageHandle
) {
2123 EFI_LOADED_IMAGE
*Info
;
2124 CHAR16
*Options
, *FileName
, *SubString
;
2127 Status
= refit_call3_wrapper(BS
->HandleProtocol
, ImageHandle
, &LoadedImageProtocol
, (VOID
**) &Info
);
2128 if ((Status
== EFI_SUCCESS
) && (Info
->LoadOptionsSize
> 0)) {
2129 Options
= (CHAR16
*) Info
->LoadOptions
;
2130 SubString
= MyStrStr(Options
, L
" -c ");
2132 FileName
= StrDuplicate(&SubString
[4]);
2134 LimitStringLength(FileName
, 256);
2137 if (FileExists(SelfDir
, FileName
)) {
2138 GlobalConfig
.ConfigFilename
= FileName
;
2140 Print(L
"Specified configuration file (%s) doesn't exist; using\n'refind.conf' default\n", FileName
);
2141 MyFreePool(FileName
);
2145 } // VOID SetConfigFilename()
2148 #define EFI_APPLE_SET_OS_PROTOCOL_GUID \
2149 { 0xc5c5da95, 0x7d5c, 0x45e6, \
2150 { 0xb2, 0xf1, 0x3f, 0xd5, 0x2b, 0xb1, 0x00, 0x77 } \
2153 typedef struct EfiAppleSetOsInterface
{
2155 EFI_STATUS
EFIAPI (*SetOsVersion
) (IN CHAR8
*Version
);
2156 EFI_STATUS
EFIAPI (*SetOsVendor
) (IN CHAR8
*Vendor
);
2157 } EfiAppleSetOsInterface
;
2159 // Function to tell the firmware that OS X is being launched. This is
2160 // required to work around problems on some Macs that don't fully
2161 // initialize some hardware (especially video displays) when third-party
2162 // OSes are launched in EFI mode.
2163 static EFI_STATUS
SetAppleOSInfo() {
2164 CHAR16
*AppleOSVersion
= NULL
;
2165 CHAR8
*AppleOSVersion8
= NULL
;
2167 EFI_GUID apple_set_os_guid
= EFI_APPLE_SET_OS_PROTOCOL_GUID
;
2168 EfiAppleSetOsInterface
*SetOs
= NULL
;
2170 Status
= refit_call3_wrapper(BS
->LocateProtocol
, &apple_set_os_guid
, NULL
, (VOID
**) &SetOs
);
2172 // Not a Mac, so ignore the call....
2173 if ((Status
!= EFI_SUCCESS
) || (!SetOs
))
2176 if ((SetOs
->Version
!= 0) && GlobalConfig
.SpoofOSXVersion
) {
2177 AppleOSVersion
= StrDuplicate(L
"Mac OS X");
2178 MergeStrings(&AppleOSVersion
, GlobalConfig
.SpoofOSXVersion
, ' ');
2179 AppleOSVersion8
= AllocateZeroPool((StrLen(AppleOSVersion
) + 1) * sizeof(CHAR8
));
2180 UnicodeStrToAsciiStr(AppleOSVersion
, AppleOSVersion8
);
2181 if (AppleOSVersion8
) {
2182 Status
= refit_call1_wrapper (SetOs
->SetOsVersion
, AppleOSVersion8
);
2183 if (!EFI_ERROR(Status
))
2184 Status
= EFI_SUCCESS
;
2186 Status
= EFI_OUT_OF_RESOURCES
;
2187 Print(L
"Out of resources!\n");
2189 if ((Status
== EFI_SUCCESS
) && (SetOs
->Version
== 2))
2190 Status
= refit_call1_wrapper (SetOs
->SetOsVendor
, "Apple Inc.");
2193 if (Status
!= EFI_SUCCESS
)
2194 Print(L
"Unable to set firmware boot type!\n");
2196 MyFreePool(AppleOSVersion
);
2197 MyFreePool(AppleOSVersion8
);
2199 } // EFI_STATUS SetAppleOSInfo()
2206 efi_main (EFI_HANDLE ImageHandle
, EFI_SYSTEM_TABLE
*SystemTable
)
2209 BOOLEAN MainLoopRunning
= TRUE
;
2210 BOOLEAN MokProtocol
;
2211 REFIT_MENU_ENTRY
*ChosenEntry
;
2213 CHAR16
*SelectionName
= NULL
;
2217 InitializeLib(ImageHandle
, SystemTable
);
2218 Status
= InitRefitLib(ImageHandle
);
2219 if (EFI_ERROR(Status
))
2222 // read configuration
2223 CopyMem(GlobalConfig
.ScanFor
, "ieom ", NUM_SCAN_OPTIONS
);
2224 FindLegacyBootType();
2225 if (GlobalConfig
.LegacyType
== LEGACY_TYPE_MAC
)
2226 CopyMem(GlobalConfig
.ScanFor
, "ihebocm ", NUM_SCAN_OPTIONS
);
2227 SetConfigFilename(ImageHandle
);
2228 ReadConfig(GlobalConfig
.ConfigFilename
);
2230 if (GlobalConfig
.SpoofOSXVersion
) {
2235 WarnIfLegacyProblems();
2236 MainMenu
.TimeoutSeconds
= GlobalConfig
.Timeout
;
2238 // disable EFI watchdog timer
2239 refit_call4_wrapper(BS
->SetWatchdogTimer
, 0x0000, 0x0000, 0x0000, NULL
);
2241 // further bootstrap (now with config available)
2242 MokProtocol
= SecureBootSetup();
2245 ScanForBootloaders();
2249 if (GlobalConfig
.ScanDelay
> 0) {
2254 if (GlobalConfig
.ScanDelay
> 1)
2255 egDisplayMessage(L
"Pausing before disk scan; please wait....", &BGColor
);
2256 for (i
= 0; i
< GlobalConfig
.ScanDelay
; i
++)
2257 refit_call1_wrapper(BS
->Stall
, 1000000);
2258 RescanAll(GlobalConfig
.ScanDelay
> 1);
2261 if (GlobalConfig
.DefaultSelection
)
2262 SelectionName
= StrDuplicate(GlobalConfig
.DefaultSelection
);
2264 while (MainLoopRunning
) {
2265 MenuExit
= RunMainMenu(&MainMenu
, &SelectionName
, &ChosenEntry
);
2267 // The Escape key triggers a re-scan operation....
2268 if (MenuExit
== MENU_EXIT_ESCAPE
) {
2274 switch (ChosenEntry
->Tag
) {
2276 case TAG_REBOOT
: // Reboot
2278 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);
2279 MainLoopRunning
= FALSE
; // just in case we get this far
2282 case TAG_SHUTDOWN
: // Shut Down
2284 refit_call4_wrapper(RT
->ResetSystem
, EfiResetShutdown
, EFI_SUCCESS
, 0, NULL
);
2285 MainLoopRunning
= FALSE
; // just in case we get this far
2288 case TAG_ABOUT
: // About rEFInd
2292 case TAG_LOADER
: // Boot OS via .EFI loader
2293 StartLoader((LOADER_ENTRY
*)ChosenEntry
, SelectionName
);
2296 case TAG_LEGACY
: // Boot legacy OS
2297 StartLegacy((LEGACY_ENTRY
*)ChosenEntry
, SelectionName
);
2300 case TAG_LEGACY_UEFI
: // Boot a legacy OS on a non-Mac
2301 StartLegacyUEFI((LEGACY_ENTRY
*)ChosenEntry
, SelectionName
);
2304 case TAG_TOOL
: // Start a EFI tool
2305 StartTool((LOADER_ENTRY
*)ChosenEntry
);
2308 case TAG_EXIT
: // Terminate rEFInd
2309 if ((MokProtocol
) && !SecureBootUninstall()) {
2310 MainLoopRunning
= FALSE
; // just in case we get this far
2312 BeginTextScreen(L
" ");
2317 case TAG_FIRMWARE
: // Reboot into firmware's user interface
2318 RebootIntoFirmware();
2324 // If we end up here, things have gone wrong. Try to reboot, and if that
2325 // fails, go into an endless loop.
2326 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);