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 DRIVER_DIRS L"drivers,drivers_x64"
102 #define FALLBACK_FULLNAME L"EFI\\BOOT\\bootx64.efi"
103 #define FALLBACK_BASENAME L"bootx64.efi"
104 #define EFI_STUB_ARCH 0x8664
105 EFI_GUID gFreedesktopRootGuid
= { 0x4f68bce3, 0xe8cd, 0x4db1, { 0x96, 0xe7, 0xfb, 0xca, 0xf9, 0x84, 0xb7, 0x09 }};
106 #elif defined (EFI32)
107 #define SHELL_NAMES L"\\EFI\\tools\\shell.efi,\\EFI\\tools\\shellia32.efi,\\shell.efi,\\shellia32.efi"
108 #define GPTSYNC_NAMES L"\\EFI\\tools\\gptsync.efi,\\EFI\\tools\\gptsync_ia32.efi"
109 #define GDISK_NAMES L"\\EFI\\tools\\gdisk.efi,\\EFI\\tools\\gdisk_ia32.efi"
110 #define NETBOOT_NAMES L"\\EFI\\tools\\ipxe.efi"
111 #define MEMTEST_NAMES L"memtest86.efi,memtest86_ia32.efi,memtest86ia32.efi,bootia32.efi"
112 #define DRIVER_DIRS L"drivers,drivers_ia32"
113 #define FALLBACK_FULLNAME L"EFI\\BOOT\\bootia32.efi"
114 #define FALLBACK_BASENAME L"bootia32.efi"
115 #define EFI_STUB_ARCH 0x014c
116 EFI_GUID gFreedesktopRootGuid
= { 0x44479540, 0xf297, 0x41b2, { 0x9a, 0xf7, 0xd1, 0x31, 0xd5, 0xf0, 0x45, 0x8a }};
117 #elif defined (EFIAARCH64)
118 #define SHELL_NAMES L"\\EFI\\tools\\shell.efi,\\EFI\\tools\\shellaa64.efi,\\shell.efi,\\shellaa64.efi"
119 #define GPTSYNC_NAMES L"\\EFI\\tools\\gptsync.efi,\\EFI\\tools\\gptsync_aa64.efi"
120 #define GDISK_NAMES L"\\EFI\\tools\\gdisk.efi,\\EFI\\tools\\gdisk_aa64.efi"
121 #define NETBOOT_NAMES L"\\EFI\\tools\\ipxe.efi"
122 #define MEMTEST_NAMES L"memtest86.efi,memtest86_aa64.efi,memtest86aa64.efi,bootaa64.efi"
123 #define DRIVER_DIRS L"drivers,drivers_aa64"
124 #define FALLBACK_FULLNAME L"EFI\\BOOT\\bootaa64.efi"
125 #define FALLBACK_BASENAME L"bootaa64.efi"
126 #define EFI_STUB_ARCH 0xaa64
127 EFI_GUID gFreedesktopRootGuid
= { 0xb921b045, 0x1df0, 0x41c3, { 0xaf, 0x44, 0x4c, 0x6f, 0x28, 0x0d, 0x3f, 0xae }};
129 #define SHELL_NAMES L"\\EFI\\tools\\shell.efi,\\shell.efi"
130 #define GPTSYNC_NAMES L"\\EFI\\tools\\gptsync.efi"
131 #define GDISK_NAMES L"\\EFI\\tools\\gdisk.efi"
132 #define NETBOOT_NAMES L"\\EFI\\tools\\ipxe.efi"
133 #define MEMTEST_NAMES L"memtest86.efi"
134 #define DRIVER_DIRS L"drivers"
135 #define FALLBACK_FULLNAME L"EFI\\BOOT\\boot.efi" /* Not really correct */
136 #define FALLBACK_BASENAME L"boot.efi" /* Not really correct */
137 // Below is GUID for ARM64
138 EFI_GUID gFreedesktopRootGuid
= { 0xb921b045, 0x1df0, 0x41c3, { 0xaf, 0x44, 0x4c, 0x6f, 0x28, 0x0d, 0x3f, 0xae }};
140 #define FAT_ARCH 0x0ef1fab9 /* ID for Apple "fat" binary */
142 #define IPXE_DISCOVER_NAME L"\\efi\\tools\\ipxe_discover.efi"
143 #define IPXE_NAME L"\\efi\\tools\\ipxe.efi"
145 // Filename patterns that identify EFI boot loaders. Note that a single case (either L"*.efi" or
146 // L"*.EFI") is fine for most systems; but Gigabyte's buggy Hybrid EFI does a case-sensitive
147 // comparison when it should do a case-insensitive comparison, so I'm doubling this up. It does
148 // no harm on other computers, AFAIK. In theory, every case variation should be done for
149 // completeness, but that's ridiculous....
150 #define LOADER_MATCH_PATTERNS L"*.efi,*.EFI"
152 // Patterns that identify Linux kernels. Added to the loader match pattern when the
153 // scan_all_linux_kernels option is set in the configuration file. Causes kernels WITHOUT
154 // a ".efi" extension to be found when scanning for boot loaders.
155 #define LINUX_MATCH_PATTERNS L"vmlinuz*,bzImage*,kernel*"
157 // Maximum length of a text string in certain menus
158 #define MAX_LINE_LENGTH 65
160 static REFIT_MENU_ENTRY MenuEntryAbout
= { L
"About rEFInd", TAG_ABOUT
, 1, 0, 'A', NULL
, NULL
, NULL
};
161 static REFIT_MENU_ENTRY MenuEntryReset
= { L
"Reboot Computer", TAG_REBOOT
, 1, 0, 'R', NULL
, NULL
, NULL
};
162 static REFIT_MENU_ENTRY MenuEntryShutdown
= { L
"Shut Down Computer", TAG_SHUTDOWN
, 1, 0, 'U', NULL
, NULL
, NULL
};
163 REFIT_MENU_ENTRY MenuEntryReturn
= { L
"Return to Main Menu", TAG_RETURN
, 1, 0, 0, NULL
, NULL
, NULL
};
164 static REFIT_MENU_ENTRY MenuEntryExit
= { L
"Exit rEFInd", TAG_EXIT
, 1, 0, 0, NULL
, NULL
, NULL
};
165 static REFIT_MENU_ENTRY MenuEntryFirmware
= { L
"Reboot to Computer Setup Utility", TAG_FIRMWARE
, 1, 0, 0, NULL
, NULL
, NULL
};
166 static REFIT_MENU_ENTRY MenuEntryRotateCsr
= { L
"Change SIP Policy", TAG_CSR_ROTATE
, 1, 0, 0, NULL
, NULL
, NULL
};
168 REFIT_MENU_SCREEN MainMenu
= { L
"Main Menu", NULL
, 0, NULL
, 0, NULL
, 0, L
"Automatic boot",
169 L
"Use arrow keys to move cursor; Enter to boot;",
170 L
"Insert or F2 for more options; Esc to refresh" };
171 static REFIT_MENU_SCREEN AboutMenu
= { L
"About", NULL
, 0, NULL
, 0, NULL
, 0, NULL
, L
"Press Enter to return to main menu", L
"" };
173 REFIT_CONFIG GlobalConfig
= { FALSE
, TRUE
, FALSE
, FALSE
, TRUE
, 0, 0, 0, DONT_CHANGE_TEXT_MODE
,
174 20, 0, 0, GRAPHICS_FOR_OSX
, LEGACY_TYPE_MAC
,
175 0, 0, { DEFAULT_BIG_ICON_SIZE
/ 4, DEFAULT_SMALL_ICON_SIZE
, DEFAULT_BIG_ICON_SIZE
},
176 BANNER_NOSCALE
, NULL
, NULL
, NULL
, NULL
, CONFIG_FILE_NAME
, NULL
, NULL
, NULL
, NULL
,
177 NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
,
178 { TAG_SHELL
, TAG_MEMTEST
, TAG_GDISK
, TAG_APPLE_RECOVERY
, TAG_WINDOWS_RECOVERY
,
179 TAG_MOK_TOOL
, TAG_ABOUT
, TAG_SHUTDOWN
, TAG_REBOOT
, TAG_FIRMWARE
,
180 0, 0, 0, 0, 0, 0, 0, 0 }
183 EFI_GUID GlobalGuid
= EFI_GLOBAL_VARIABLE
;
184 EFI_GUID RefindGuid
= REFIND_GUID_VALUE
;
186 GPT_DATA
*gPartitions
= NULL
;
188 // Structure used to hold boot loader filenames and time stamps in
189 // a linked list; used to sort entries within a directory.
193 struct LOADER_LIST
*NextEntry
;
200 static VOID
AboutrEFInd(VOID
)
202 CHAR16
*FirmwareVendor
;
205 if (AboutMenu
.EntryCount
== 0) {
206 AboutMenu
.TitleImage
= BuiltinIcon(BUILTIN_ICON_FUNC_ABOUT
);
207 AddMenuInfoLine(&AboutMenu
, L
"rEFInd Version 0.10.0.5");
208 AddMenuInfoLine(&AboutMenu
, L
"");
209 AddMenuInfoLine(&AboutMenu
, L
"Copyright (c) 2006-2010 Christoph Pfisterer");
210 AddMenuInfoLine(&AboutMenu
, L
"Copyright (c) 2012-2015 Roderick W. Smith");
211 AddMenuInfoLine(&AboutMenu
, L
"Portions Copyright (c) Intel Corporation and others");
212 AddMenuInfoLine(&AboutMenu
, L
"Distributed under the terms of the GNU GPLv3 license");
213 AddMenuInfoLine(&AboutMenu
, L
"");
214 AddMenuInfoLine(&AboutMenu
, L
"Running on:");
215 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" EFI Revision %d.%02d", ST
->Hdr
.Revision
>> 16, ST
->Hdr
.Revision
& ((1 << 16) - 1)));
217 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" Platform: x86 (32 bit); Secure Boot %s",
218 secure_mode() ? L
"active" : L
"inactive"));
219 #elif defined(EFIX64)
220 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" Platform: x86_64 (64 bit); Secure Boot %s",
221 secure_mode() ? L
"active" : L
"inactive"));
222 #elif defined(EFIAARCH64)
223 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" Platform: ARM (64 bit); Secure Boot %s",
224 secure_mode() ? L
"active" : L
"inactive"));
226 AddMenuInfoLine(&AboutMenu
, L
" Platform: unknown");
228 if (GetCsrStatus(&CsrStatus
) == EFI_SUCCESS
) {
229 RecordgCsrStatus(CsrStatus
, FALSE
);
230 AddMenuInfoLine(&AboutMenu
, gCsrStatus
);
232 FirmwareVendor
= StrDuplicate(ST
->FirmwareVendor
);
233 LimitStringLength(FirmwareVendor
, MAX_LINE_LENGTH
); // More than ~65 causes empty info page on 800x600 display
234 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" Firmware: %s %d.%02d", FirmwareVendor
, ST
->FirmwareRevision
>> 16,
235 ST
->FirmwareRevision
& ((1 << 16) - 1)));
236 AddMenuInfoLine(&AboutMenu
, PoolPrint(L
" Screen Output: %s", egScreenDescription()));
237 AddMenuInfoLine(&AboutMenu
, L
"");
238 #if defined(__MAKEWITH_GNUEFI)
239 AddMenuInfoLine(&AboutMenu
, L
"Built with GNU-EFI");
241 AddMenuInfoLine(&AboutMenu
, L
"Built with TianoCore EDK2");
243 AddMenuInfoLine(&AboutMenu
, L
"");
244 AddMenuInfoLine(&AboutMenu
, L
"For more information, see the rEFInd Web site:");
245 AddMenuInfoLine(&AboutMenu
, L
"http://www.rodsbooks.com/refind/");
246 AddMenuEntry(&AboutMenu
, &MenuEntryReturn
);
249 RunMenu(&AboutMenu
, NULL
);
250 } /* VOID AboutrEFInd() */
252 static VOID
WarnSecureBootError(CHAR16
*Name
, BOOLEAN Verbose
) {
254 Name
= L
"the loader";
256 refit_call2_wrapper(ST
->ConOut
->SetAttribute
, ST
->ConOut
, ATTR_ERROR
);
257 Print(L
"Secure Boot validation failure loading %s!\n", Name
);
258 refit_call2_wrapper(ST
->ConOut
->SetAttribute
, ST
->ConOut
, ATTR_BASIC
);
259 if (Verbose
&& secure_mode()) {
260 Print(L
"\nThis computer is configured with Secure Boot active, but\n%s has failed validation.\n", Name
);
261 Print(L
"\nYou can:\n * Launch another boot loader\n");
262 Print(L
" * Disable Secure Boot in your firmware\n");
263 Print(L
" * Sign %s with a machine owner key (MOK)\n", Name
);
264 Print(L
" * Use a MOK utility (often present on the second row) to add a MOK with which\n");
265 Print(L
" %s has already been signed.\n", Name
);
266 Print(L
" * Use a MOK utility to register %s (\"enroll its hash\") without\n", Name
);
267 Print(L
" signing it.\n");
268 Print(L
"\nSee http://www.rodsbooks.com/refind/secureboot.html for more information\n");
271 } // VOID WarnSecureBootError()
273 // Returns TRUE if this file is a valid EFI loader file, and is proper ARCH
274 static BOOLEAN
IsValidLoader(EFI_FILE
*RootDir
, CHAR16
*FileName
) {
275 BOOLEAN IsValid
= TRUE
;
276 #if defined (EFIX64) | defined (EFI32) | defined (EFIAARCH64)
278 EFI_FILE_HANDLE FileHandle
;
280 UINTN Size
= sizeof(Header
);
282 if ((RootDir
== NULL
) || (FileName
== NULL
)) {
283 // Assume valid here, because Macs produce NULL RootDir (& maybe FileName)
284 // when launching from a Firewire drive. This should be handled better, but
285 // fix would have to be in StartEFIImageList() and/or in FindVolumeAndFilename().
289 Status
= refit_call5_wrapper(RootDir
->Open
, RootDir
, &FileHandle
, FileName
, EFI_FILE_MODE_READ
, 0);
290 if (EFI_ERROR(Status
))
293 Status
= refit_call3_wrapper(FileHandle
->Read
, FileHandle
, &Size
, Header
);
294 refit_call1_wrapper(FileHandle
->Close
, FileHandle
);
296 IsValid
= !EFI_ERROR(Status
) &&
297 Size
== sizeof(Header
) &&
298 ((Header
[0] == 'M' && Header
[1] == 'Z' &&
299 (Size
= *(UINT32
*)&Header
[0x3c]) < 0x180 &&
300 Header
[Size
] == 'P' && Header
[Size
+1] == 'E' &&
301 Header
[Size
+2] == 0 && Header
[Size
+3] == 0 &&
302 *(UINT16
*)&Header
[Size
+4] == EFI_STUB_ARCH
) ||
303 (*(UINT32
*)&Header
== FAT_ARCH
));
306 } // BOOLEAN IsValidLoader()
308 // Launch an EFI binary.
309 EFI_STATUS
StartEFIImageList(IN EFI_DEVICE_PATH
**DevicePaths
,
310 IN CHAR16
*LoadOptions
, IN UINTN LoaderType
,
311 IN CHAR16
*ImageTitle
, IN CHAR8 OSType
,
312 OUT UINTN
*ErrorInStep
,
316 EFI_STATUS Status
, ReturnStatus
;
317 EFI_HANDLE ChildImageHandle
, ChildImageHandle2
;
318 EFI_LOADED_IMAGE
*ChildLoadedImage
= NULL
;
319 REFIT_VOLUME
*Volume
= NULL
;
320 UINTN DevicePathIndex
;
321 CHAR16 ErrorInfo
[256];
322 CHAR16
*FullLoadOptions
= NULL
;
323 CHAR16
*Filename
= NULL
;
326 if (ErrorInStep
!= NULL
)
330 if (LoadOptions
!= NULL
) {
331 FullLoadOptions
= StrDuplicate(LoadOptions
);
332 if ((LoaderType
== TYPE_EFI
) && (OSType
== 'M')) {
333 MergeStrings(&FullLoadOptions
, L
" ", 0);
334 // NOTE: That last space is also added by the EFI shell and seems to be significant
335 // when passing options to Apple's boot.efi...
337 } // if (LoadOptions != NULL)
339 Print(L
"Starting %s\nUsing load options '%s'\n", ImageTitle
, FullLoadOptions
? FullLoadOptions
: L
"");
341 // load the image into memory
342 ReturnStatus
= Status
= EFI_NOT_FOUND
; // in case the list is empty
343 for (DevicePathIndex
= 0; DevicePaths
[DevicePathIndex
] != NULL
; DevicePathIndex
++) {
344 FindVolumeAndFilename(DevicePaths
[DevicePathIndex
], &Volume
, &Filename
);
345 // Some EFIs crash if attempting to load driver for invalid architecture, so
346 // protect for this condition; but sometimes Volume comes back NULL, so provide
347 // an exception. (TODO: Handle this special condition better.)
348 if ((LoaderType
== TYPE_LEGACY
) || (Volume
== NULL
) || IsValidLoader(Volume
->RootDir
, Filename
)) {
349 if (Filename
&& (LoaderType
!= TYPE_LEGACY
)) {
350 Temp
= PoolPrint(L
"\\%s %s", Filename
, FullLoadOptions
? FullLoadOptions
: L
"");
352 MyFreePool(FullLoadOptions
);
353 FullLoadOptions
= Temp
;
357 // NOTE: Below commented-out line could be more efficient if file were read ahead of
358 // time and passed as a pre-loaded image to LoadImage(), but it doesn't work on my
359 // 32-bit Mac Mini or my 64-bit Intel box when launching a Linux kernel; the
360 // kernel returns a "Failed to handle fs_proto" error message.
361 // TODO: Track down the cause of this error and fix it, if possible.
362 // ReturnStatus = Status = refit_call6_wrapper(BS->LoadImage, FALSE, SelfImageHandle, DevicePaths[DevicePathIndex],
363 // ImageData, ImageSize, &ChildImageHandle);
364 ReturnStatus
= Status
= refit_call6_wrapper(BS
->LoadImage
, FALSE
, SelfImageHandle
, DevicePaths
[DevicePathIndex
],
365 NULL
, 0, &ChildImageHandle
);
366 if (secure_mode() && ShimLoaded()) {
367 // Load ourself into memory. This is a trick to work around a bug in Shim 0.8,
368 // which ties itself into the BS->LoadImage() and BS->StartImage() functions and
369 // then unregisters itself from the EFI system table when its replacement
370 // StartImage() function is called *IF* the previous LoadImage() was for the same
371 // program. The result is that rEFInd can validate only the first program it
372 // launches (often a filesystem driver). Loading a second program (rEFInd itself,
373 // here, to keep it smaller than a kernel) works around this problem. See the
374 // replacements.c file in Shim, and especially its start_image() function, for
375 // the source of the problem.
376 // NOTE: This doesn't check the return status or handle errors. It could
377 // conceivably do weird things if, say, rEFInd were on a USB drive that the
378 // user pulls before launching a program.
379 refit_call6_wrapper(BS
->LoadImage
, FALSE
, SelfImageHandle
, GlobalConfig
.SelfDevicePath
,
380 NULL
, 0, &ChildImageHandle2
);
383 Print(L
"Invalid loader file!\n");
384 ReturnStatus
= EFI_LOAD_ERROR
;
386 if (ReturnStatus
!= EFI_NOT_FOUND
) {
390 if ((Status
== EFI_ACCESS_DENIED
) || (Status
== EFI_SECURITY_VIOLATION
)) {
391 WarnSecureBootError(ImageTitle
, Verbose
);
394 SPrint(ErrorInfo
, 255, L
"while loading %s", ImageTitle
);
395 if (CheckError(Status
, ErrorInfo
)) {
396 if (ErrorInStep
!= NULL
)
401 ReturnStatus
= Status
= refit_call3_wrapper(BS
->HandleProtocol
, ChildImageHandle
, &LoadedImageProtocol
,
402 (VOID
**) &ChildLoadedImage
);
403 if (CheckError(Status
, L
"while getting a LoadedImageProtocol handle")) {
404 if (ErrorInStep
!= NULL
)
408 ChildLoadedImage
->LoadOptions
= (VOID
*)FullLoadOptions
;
409 ChildLoadedImage
->LoadOptionsSize
= FullLoadOptions
? ((UINT32
)StrLen(FullLoadOptions
) + 1) * sizeof(CHAR16
) : 0;
410 // turn control over to the image
411 // TODO: (optionally) re-enable the EFI watchdog timer!
413 // close open file handles
415 ReturnStatus
= Status
= refit_call3_wrapper(BS
->StartImage
, ChildImageHandle
, NULL
, NULL
);
417 // control returns here when the child image calls Exit()
418 SPrint(ErrorInfo
, 255, L
"returned from %s", ImageTitle
);
419 if (CheckError(Status
, ErrorInfo
)) {
420 if (ErrorInStep
!= NULL
)
424 // re-open file handles
428 // unload the image, we don't care if it works or not...
430 Status
= refit_call1_wrapper(BS
->UnloadImage
, ChildImageHandle
);
433 MyFreePool(FullLoadOptions
);
435 } /* EFI_STATUS StartEFIImageList() */
437 static EFI_STATUS
StartEFIImage(IN EFI_DEVICE_PATH
*DevicePath
,
438 IN CHAR16
*LoadOptions
, IN UINTN LoaderType
,
439 IN CHAR16
*ImageTitle
, IN CHAR8 OSType
,
440 OUT UINTN
*ErrorInStep
,
445 EFI_DEVICE_PATH
*DevicePaths
[2];
447 DevicePaths
[0] = DevicePath
;
448 DevicePaths
[1] = NULL
;
449 return StartEFIImageList(DevicePaths
, LoadOptions
, LoaderType
, ImageTitle
, OSType
, ErrorInStep
, Verbose
, IsDriver
);
450 } /* static EFI_STATUS StartEFIImage() */
452 // From gummiboot: Reboot the computer into its built-in user interface
453 static EFI_STATUS
RebootIntoFirmware(VOID
) {
459 osind
= EFI_OS_INDICATIONS_BOOT_TO_FW_UI
;
461 err
= EfivarGetRaw(&GlobalGuid
, L
"OsIndications", &b
, &size
);
462 if (err
== EFI_SUCCESS
)
466 err
= EfivarSetRaw(&GlobalGuid
, L
"OsIndications", (CHAR8
*)&osind
, sizeof(UINT64
), TRUE
);
467 if (err
!= EFI_SUCCESS
)
470 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);
471 Print(L
"Error calling ResetSystem: %r", err
);
476 // Record the value of the loader's name/description in rEFInd's "PreviousBoot" EFI variable,
477 // if it's different from what's already stored there.
478 VOID
StoreLoaderName(IN CHAR16
*Name
) {
480 CHAR16
*OldName
= NULL
;
484 Status
= EfivarGetRaw(&RefindGuid
, L
"PreviousBoot", (CHAR8
**) &OldName
, &Length
);
485 if ((Status
!= EFI_SUCCESS
) || (StrCmp(OldName
, Name
) != 0)) {
486 EfivarSetRaw(&RefindGuid
, L
"PreviousBoot", (CHAR8
*) Name
, StrLen(Name
) * 2 + 2, TRUE
);
490 } // VOID StoreLoaderName()
493 // EFI OS loader functions
496 // See http://www.thomas-krenn.com/en/wiki/Activating_the_Intel_VT_Virtualization_Feature
497 // for information on Intel VMX features
498 static VOID
DoEnableAndLockVMX(VOID
)
500 #if defined (EFIX64) | defined (EFI32)
502 UINT32 low_bits
= 0, high_bits
= 0;
505 __asm__
volatile ("rdmsr" : "=a" (low_bits
), "=d" (high_bits
) : "c" (msr
));
507 // enable and lock vmx if not locked
508 if ((low_bits
& 1) == 0) {
512 __asm__
volatile ("wrmsr" : : "c" (msr
), "a" (low_bits
), "d" (high_bits
));
515 } // VOID DoEnableAndLockVMX()
517 static VOID
StartLoader(LOADER_ENTRY
*Entry
, CHAR16
*SelectionName
)
519 UINTN ErrorInStep
= 0;
521 if (GlobalConfig
.EnableAndLockVMX
) {
522 DoEnableAndLockVMX();
525 BeginExternalScreen(Entry
->UseGraphicsMode
, L
"Booting OS");
526 StoreLoaderName(SelectionName
);
527 StartEFIImage(Entry
->DevicePath
, Entry
->LoadOptions
, TYPE_EFI
,
528 Basename(Entry
->LoaderPath
), Entry
->OSType
, &ErrorInStep
, !Entry
->UseGraphicsMode
, FALSE
);
529 FinishExternalScreen();
532 // Locate an initrd or initramfs file that matches the kernel specified by LoaderPath.
533 // The matching file has a name that begins with "init" and includes the same version
534 // number string as is found in LoaderPath -- but not a longer version number string.
535 // For instance, if LoaderPath is \EFI\kernels\bzImage-3.3.0.efi, and if \EFI\kernels
536 // has a file called initramfs-3.3.0.img, this function will return the string
537 // '\EFI\kernels\initramfs-3.3.0.img'. If the directory ALSO contains the file
538 // initramfs-3.3.0-rc7.img or initramfs-13.3.0.img, those files will NOT match;
539 // however, initmine-3.3.0.img might match. (FindInitrd() returns the first match it
540 // finds.) Thus, care should be taken to avoid placing duplicate matching files in
541 // the kernel's directory.
542 // If no matching init file can be found, returns NULL.
543 static CHAR16
* FindInitrd(IN CHAR16
*LoaderPath
, IN REFIT_VOLUME
*Volume
) {
544 CHAR16
*InitrdName
= NULL
, *FileName
, *KernelVersion
, *InitrdVersion
, *Path
;
545 REFIT_DIR_ITER DirIter
;
546 EFI_FILE_INFO
*DirEntry
;
548 FileName
= Basename(LoaderPath
);
549 KernelVersion
= FindNumbers(FileName
);
550 Path
= FindPath(LoaderPath
);
552 // Add trailing backslash for root directory; necessary on some systems, but must
553 // NOT be added to all directories, since on other systems, a trailing backslash on
554 // anything but the root directory causes them to flake out!
555 if (StrLen(Path
) == 0) {
556 MergeStrings(&Path
, L
"\\", 0);
558 DirIterOpen(Volume
->RootDir
, Path
, &DirIter
);
559 // Now add a trailing backslash if it was NOT added earlier, for consistency in
560 // building the InitrdName later....
561 if ((StrLen(Path
) > 0) && (Path
[StrLen(Path
) - 1] != L
'\\'))
562 MergeStrings(&Path
, L
"\\", 0);
563 while ((DirIterNext(&DirIter
, 2, L
"init*", &DirEntry
)) && (InitrdName
== NULL
)) {
564 InitrdVersion
= FindNumbers(DirEntry
->FileName
);
565 if (KernelVersion
!= NULL
) {
566 if (MyStriCmp(InitrdVersion
, KernelVersion
)) {
567 InitrdName
= PoolPrint(L
"%s%s", Path
, DirEntry
->FileName
);
570 if (InitrdVersion
== NULL
) {
571 InitrdName
= PoolPrint(L
"%s%s", Path
, DirEntry
->FileName
);
574 MyFreePool(InitrdVersion
);
576 DirIterClose(&DirIter
);
578 // Note: Don't FreePool(FileName), since Basename returns a pointer WITHIN the string it's passed.
579 MyFreePool(KernelVersion
);
582 } // static CHAR16 * FindInitrd()
584 LOADER_ENTRY
* AddPreparedLoaderEntry(LOADER_ENTRY
*Entry
) {
585 AddMenuEntry(&MainMenu
, (REFIT_MENU_ENTRY
*)Entry
);
588 } // LOADER_ENTRY * AddPreparedLoaderEntry()
590 // Creates a copy of a menu screen.
591 // Returns a pointer to the copy of the menu screen.
592 static REFIT_MENU_SCREEN
* CopyMenuScreen(REFIT_MENU_SCREEN
*Entry
) {
593 REFIT_MENU_SCREEN
*NewEntry
;
596 NewEntry
= AllocateZeroPool(sizeof(REFIT_MENU_SCREEN
));
597 if ((Entry
!= NULL
) && (NewEntry
!= NULL
)) {
598 CopyMem(NewEntry
, Entry
, sizeof(REFIT_MENU_SCREEN
));
599 NewEntry
->Title
= (Entry
->Title
) ? StrDuplicate(Entry
->Title
) : NULL
;
600 NewEntry
->TimeoutText
= (Entry
->TimeoutText
) ? StrDuplicate(Entry
->TimeoutText
) : NULL
;
601 if (Entry
->TitleImage
!= NULL
) {
602 NewEntry
->TitleImage
= AllocatePool(sizeof(EG_IMAGE
));
603 if (NewEntry
->TitleImage
!= NULL
)
604 CopyMem(NewEntry
->TitleImage
, Entry
->TitleImage
, sizeof(EG_IMAGE
));
606 NewEntry
->InfoLines
= (CHAR16
**) AllocateZeroPool(Entry
->InfoLineCount
* (sizeof(CHAR16
*)));
607 for (i
= 0; i
< Entry
->InfoLineCount
&& NewEntry
->InfoLines
; i
++) {
608 NewEntry
->InfoLines
[i
] = (Entry
->InfoLines
[i
]) ? StrDuplicate(Entry
->InfoLines
[i
]) : NULL
;
610 NewEntry
->Entries
= (REFIT_MENU_ENTRY
**) AllocateZeroPool(Entry
->EntryCount
* (sizeof (REFIT_MENU_ENTRY
*)));
611 for (i
= 0; i
< Entry
->EntryCount
&& NewEntry
->Entries
; i
++) {
612 AddMenuEntry(NewEntry
, Entry
->Entries
[i
]);
614 NewEntry
->Hint1
= (Entry
->Hint1
) ? StrDuplicate(Entry
->Hint1
) : NULL
;
615 NewEntry
->Hint2
= (Entry
->Hint2
) ? StrDuplicate(Entry
->Hint2
) : NULL
;
618 } // static REFIT_MENU_SCREEN* CopyMenuScreen()
620 // Creates a copy of a menu entry. Intended to enable moving a stack-based
621 // menu entry (such as the ones for the "reboot" and "exit" functions) to
622 // to the heap. This enables easier deletion of the whole set of menu
623 // entries when re-scanning.
624 // Returns a pointer to the copy of the menu entry.
625 static REFIT_MENU_ENTRY
* CopyMenuEntry(REFIT_MENU_ENTRY
*Entry
) {
626 REFIT_MENU_ENTRY
*NewEntry
;
628 NewEntry
= AllocateZeroPool(sizeof(REFIT_MENU_ENTRY
));
629 if ((Entry
!= NULL
) && (NewEntry
!= NULL
)) {
630 CopyMem(NewEntry
, Entry
, sizeof(REFIT_MENU_ENTRY
));
631 NewEntry
->Title
= (Entry
->Title
) ? StrDuplicate(Entry
->Title
) : NULL
;
632 if (Entry
->BadgeImage
!= NULL
) {
633 NewEntry
->BadgeImage
= AllocatePool(sizeof(EG_IMAGE
));
634 if (NewEntry
->BadgeImage
!= NULL
)
635 CopyMem(NewEntry
->BadgeImage
, Entry
->BadgeImage
, sizeof(EG_IMAGE
));
637 if (Entry
->Image
!= NULL
) {
638 NewEntry
->Image
= AllocatePool(sizeof(EG_IMAGE
));
639 if (NewEntry
->Image
!= NULL
)
640 CopyMem(NewEntry
->Image
, Entry
->Image
, sizeof(EG_IMAGE
));
642 if (Entry
->SubScreen
!= NULL
) {
643 NewEntry
->SubScreen
= CopyMenuScreen(Entry
->SubScreen
);
647 } // REFIT_MENU_ENTRY* CopyMenuEntry()
649 // Creates a new LOADER_ENTRY data structure and populates it with
650 // default values from the specified Entry, or NULL values if Entry
651 // is unspecified (NULL).
652 // Returns a pointer to the new data structure, or NULL if it
653 // couldn't be allocated
654 LOADER_ENTRY
*InitializeLoaderEntry(IN LOADER_ENTRY
*Entry
) {
655 LOADER_ENTRY
*NewEntry
= NULL
;
657 NewEntry
= AllocateZeroPool(sizeof(LOADER_ENTRY
));
658 if (NewEntry
!= NULL
) {
659 NewEntry
->me
.Title
= NULL
;
660 NewEntry
->me
.Tag
= TAG_LOADER
;
661 NewEntry
->Enabled
= TRUE
;
662 NewEntry
->UseGraphicsMode
= FALSE
;
663 NewEntry
->OSType
= 0;
665 NewEntry
->LoaderPath
= (Entry
->LoaderPath
) ? StrDuplicate(Entry
->LoaderPath
) : NULL
;
666 NewEntry
->VolName
= (Entry
->VolName
) ? StrDuplicate(Entry
->VolName
) : NULL
;
667 NewEntry
->DevicePath
= Entry
->DevicePath
;
668 NewEntry
->UseGraphicsMode
= Entry
->UseGraphicsMode
;
669 NewEntry
->LoadOptions
= (Entry
->LoadOptions
) ? StrDuplicate(Entry
->LoadOptions
) : NULL
;
670 NewEntry
->InitrdPath
= (Entry
->InitrdPath
) ? StrDuplicate(Entry
->InitrdPath
) : NULL
;
674 } // LOADER_ENTRY *InitializeLoaderEntry()
676 // Adds InitrdPath to Options, but only if Options doesn't already include an
677 // initrd= line. Done to enable overriding the default initrd selection in a
678 // refind_linux.conf file's options list.
679 // Returns a pointer to a new string. The calling function is responsible for
680 // freeing its memory.
681 static CHAR16
*AddInitrdToOptions(CHAR16
*Options
, CHAR16
*InitrdPath
) {
682 CHAR16
*NewOptions
= NULL
;
685 NewOptions
= StrDuplicate(Options
);
686 if ((InitrdPath
!= NULL
) && !StriSubCmp(L
"initrd=", Options
)) {
687 MergeStrings(&NewOptions
, L
"initrd=", L
' ');
688 MergeStrings(&NewOptions
, InitrdPath
, 0);
691 } // CHAR16 *AddInitrdToOptions()
693 // Prepare a REFIT_MENU_SCREEN data structure for a subscreen entry. This sets up
694 // the default entry that launches the boot loader using the same options as the
695 // main Entry does. Subsequent options can be added by the calling function.
696 // If a subscreen already exists in the Entry that's passed to this function,
697 // it's left unchanged and a pointer to it is returned.
698 // Returns a pointer to the new subscreen data structure, or NULL if there
699 // were problems allocating memory.
700 REFIT_MENU_SCREEN
*InitializeSubScreen(IN LOADER_ENTRY
*Entry
) {
701 CHAR16
*FileName
, *MainOptions
= NULL
;
702 REFIT_MENU_SCREEN
*SubScreen
= NULL
;
703 LOADER_ENTRY
*SubEntry
;
705 FileName
= Basename(Entry
->LoaderPath
);
706 if (Entry
->me
.SubScreen
== NULL
) { // No subscreen yet; initialize default entry....
707 SubScreen
= AllocateZeroPool(sizeof(REFIT_MENU_SCREEN
));
708 if (SubScreen
!= NULL
) {
709 SubScreen
->Title
= AllocateZeroPool(sizeof(CHAR16
) * 256);
710 SPrint(SubScreen
->Title
, 255, L
"Boot Options for %s on %s",
711 (Entry
->Title
!= NULL
) ? Entry
->Title
: FileName
, Entry
->VolName
);
712 SubScreen
->TitleImage
= Entry
->me
.Image
;
714 SubEntry
= InitializeLoaderEntry(Entry
);
715 if (SubEntry
!= NULL
) {
716 SubEntry
->me
.Title
= StrDuplicate(L
"Boot using default options");
717 MainOptions
= SubEntry
->LoadOptions
;
718 SubEntry
->LoadOptions
= AddInitrdToOptions(MainOptions
, SubEntry
->InitrdPath
);
719 MyFreePool(MainOptions
);
720 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
721 } // if (SubEntry != NULL)
722 SubScreen
->Hint1
= StrDuplicate(SUBSCREEN_HINT1
);
723 if (GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_EDITOR
) {
724 SubScreen
->Hint2
= StrDuplicate(SUBSCREEN_HINT2_NO_EDITOR
);
726 SubScreen
->Hint2
= StrDuplicate(SUBSCREEN_HINT2
);
728 } // if (SubScreen != NULL)
729 } else { // existing subscreen; less initialization, and just add new entry later....
730 SubScreen
= Entry
->me
.SubScreen
;
733 } // REFIT_MENU_SCREEN *InitializeSubScreen()
735 VOID
GenerateSubScreen(LOADER_ENTRY
*Entry
, IN REFIT_VOLUME
*Volume
, IN BOOLEAN GenerateReturn
) {
736 REFIT_MENU_SCREEN
*SubScreen
;
737 LOADER_ENTRY
*SubEntry
;
739 CHAR16 DiagsFileName
[256];
744 // create the submenu
745 if (StrLen(Entry
->Title
) == 0) {
746 MyFreePool(Entry
->Title
);
749 SubScreen
= InitializeSubScreen(Entry
);
751 // loader-specific submenu entries
752 if (Entry
->OSType
== 'M') { // entries for Mac OS X
754 SubEntry
= InitializeLoaderEntry(Entry
);
755 if (SubEntry
!= NULL
) {
756 SubEntry
->me
.Title
= L
"Boot Mac OS X with a 64-bit kernel";
757 SubEntry
->LoadOptions
= L
"arch=x86_64";
758 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
759 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
762 SubEntry
= InitializeLoaderEntry(Entry
);
763 if (SubEntry
!= NULL
) {
764 SubEntry
->me
.Title
= L
"Boot Mac OS X with a 32-bit kernel";
765 SubEntry
->LoadOptions
= L
"arch=i386";
766 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
767 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
771 if (!(GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_SINGLEUSER
)) {
772 SubEntry
= InitializeLoaderEntry(Entry
);
773 if (SubEntry
!= NULL
) {
774 SubEntry
->me
.Title
= L
"Boot Mac OS X in verbose mode";
775 SubEntry
->UseGraphicsMode
= FALSE
;
776 SubEntry
->LoadOptions
= L
"-v";
777 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
781 SubEntry
= InitializeLoaderEntry(Entry
);
782 if (SubEntry
!= NULL
) {
783 SubEntry
->me
.Title
= L
"Boot Mac OS X in verbose mode (64-bit)";
784 SubEntry
->UseGraphicsMode
= FALSE
;
785 SubEntry
->LoadOptions
= L
"-v arch=x86_64";
786 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
789 SubEntry
= InitializeLoaderEntry(Entry
);
790 if (SubEntry
!= NULL
) {
791 SubEntry
->me
.Title
= L
"Boot Mac OS X in verbose mode (32-bit)";
792 SubEntry
->UseGraphicsMode
= FALSE
;
793 SubEntry
->LoadOptions
= L
"-v arch=i386";
794 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
798 SubEntry
= InitializeLoaderEntry(Entry
);
799 if (SubEntry
!= NULL
) {
800 SubEntry
->me
.Title
= L
"Boot Mac OS X in single user mode";
801 SubEntry
->UseGraphicsMode
= FALSE
;
802 SubEntry
->LoadOptions
= L
"-v -s";
803 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
805 } // single-user mode allowed
807 if (!(GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_SAFEMODE
)) {
808 SubEntry
= InitializeLoaderEntry(Entry
);
809 if (SubEntry
!= NULL
) {
810 SubEntry
->me
.Title
= L
"Boot Mac OS X in safe mode";
811 SubEntry
->UseGraphicsMode
= FALSE
;
812 SubEntry
->LoadOptions
= L
"-v -x";
813 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
815 } // safe mode allowed
817 // check for Apple hardware diagnostics
818 StrCpy(DiagsFileName
, L
"System\\Library\\CoreServices\\.diagnostics\\diags.efi");
819 if (FileExists(Volume
->RootDir
, DiagsFileName
) && !(GlobalConfig
.HideUIFlags
& HIDEUI_FLAG_HWTEST
)) {
820 SubEntry
= InitializeLoaderEntry(Entry
);
821 if (SubEntry
!= NULL
) {
822 SubEntry
->me
.Title
= L
"Run Apple Hardware Test";
823 MyFreePool(SubEntry
->LoaderPath
);
824 SubEntry
->LoaderPath
= StrDuplicate(DiagsFileName
);
825 SubEntry
->DevicePath
= FileDevicePath(Volume
->DeviceHandle
, SubEntry
->LoaderPath
);
826 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
827 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
829 } // if diagnostics entry found
831 } else if (Entry
->OSType
== 'L') { // entries for Linux kernels with EFI stub loaders
832 File
= ReadLinuxOptionsFile(Entry
->LoaderPath
, Volume
);
834 InitrdName
= FindInitrd(Entry
->LoaderPath
, Volume
);
835 TokenCount
= ReadTokenLine(File
, &TokenList
);
836 // first entry requires special processing, since it was initially set
837 // up with a default title but correct options by InitializeSubScreen(),
839 if ((TokenCount
> 1) && (SubScreen
->Entries
!= NULL
) && (SubScreen
->Entries
[0] != NULL
)) {
840 MyFreePool(SubScreen
->Entries
[0]->Title
);
841 SubScreen
->Entries
[0]->Title
= TokenList
[0] ? StrDuplicate(TokenList
[0]) : StrDuplicate(L
"Boot Linux");
843 FreeTokenLine(&TokenList
, &TokenCount
);
844 while ((TokenCount
= ReadTokenLine(File
, &TokenList
)) > 1) {
845 SubEntry
= InitializeLoaderEntry(Entry
);
846 SubEntry
->me
.Title
= TokenList
[0] ? StrDuplicate(TokenList
[0]) : StrDuplicate(L
"Boot Linux");
847 MyFreePool(SubEntry
->LoadOptions
);
848 SubEntry
->LoadOptions
= AddInitrdToOptions(TokenList
[1], InitrdName
);
849 FreeTokenLine(&TokenList
, &TokenCount
);
850 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_LINUX
;
851 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
853 MyFreePool(InitrdName
);
857 } else if (Entry
->OSType
== 'E') { // entries for ELILO
858 SubEntry
= InitializeLoaderEntry(Entry
);
859 if (SubEntry
!= NULL
) {
860 SubEntry
->me
.Title
= L
"Run ELILO in interactive mode";
861 SubEntry
->LoadOptions
= L
"-p";
862 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
863 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
866 SubEntry
= InitializeLoaderEntry(Entry
);
867 if (SubEntry
!= NULL
) {
868 SubEntry
->me
.Title
= L
"Boot Linux for a 17\" iMac or a 15\" MacBook Pro (*)";
869 SubEntry
->LoadOptions
= L
"-d 0 i17";
870 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
871 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
874 SubEntry
= InitializeLoaderEntry(Entry
);
875 if (SubEntry
!= NULL
) {
876 SubEntry
->me
.Title
= L
"Boot Linux for a 20\" iMac (*)";
877 SubEntry
->LoadOptions
= L
"-d 0 i20";
878 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
879 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
882 SubEntry
= InitializeLoaderEntry(Entry
);
883 if (SubEntry
!= NULL
) {
884 SubEntry
->me
.Title
= L
"Boot Linux for a Mac Mini (*)";
885 SubEntry
->LoadOptions
= L
"-d 0 mini";
886 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
887 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
890 AddMenuInfoLine(SubScreen
, L
"NOTE: This is an example. Entries");
891 AddMenuInfoLine(SubScreen
, L
"marked with (*) may not work.");
893 } else if (Entry
->OSType
== 'X') { // entries for xom.efi
894 // by default, skip the built-in selection and boot from hard disk only
895 Entry
->LoadOptions
= L
"-s -h";
897 SubEntry
= InitializeLoaderEntry(Entry
);
898 if (SubEntry
!= NULL
) {
899 SubEntry
->me
.Title
= L
"Boot Windows from Hard Disk";
900 SubEntry
->LoadOptions
= L
"-s -h";
901 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
902 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
905 SubEntry
= InitializeLoaderEntry(Entry
);
906 if (SubEntry
!= NULL
) {
907 SubEntry
->me
.Title
= L
"Boot Windows from CD-ROM";
908 SubEntry
->LoadOptions
= L
"-s -c";
909 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
910 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
913 SubEntry
= InitializeLoaderEntry(Entry
);
914 if (SubEntry
!= NULL
) {
915 SubEntry
->me
.Title
= L
"Run XOM in text mode";
916 SubEntry
->LoadOptions
= L
"-v";
917 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
918 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
920 } // entries for xom.efi
922 AddMenuEntry(SubScreen
, &MenuEntryReturn
);
923 Entry
->me
.SubScreen
= SubScreen
;
924 } // VOID GenerateSubScreen()
926 // Returns options for a Linux kernel. Reads them from an options file in the
927 // kernel's directory; and if present, adds an initrd= option for an initial
928 // RAM disk file with the same version number as the kernel file.
929 static CHAR16
* GetMainLinuxOptions(IN CHAR16
* LoaderPath
, IN REFIT_VOLUME
*Volume
) {
930 CHAR16
*Options
= NULL
, *InitrdName
, *FullOptions
= NULL
;
932 Options
= GetFirstOptionsFromFile(LoaderPath
, Volume
);
933 InitrdName
= FindInitrd(LoaderPath
, Volume
);
934 FullOptions
= AddInitrdToOptions(Options
, InitrdName
);
937 MyFreePool(InitrdName
);
938 return (FullOptions
);
939 } // static CHAR16 * GetMainLinuxOptions()
941 // Read the specified file and add values of "ID", "NAME", or "DISTRIB_ID" tokens to
942 // OSIconName list. Intended for adding Linux distribution clues gleaned from
943 // /etc/lsb-release and /etc/os-release files.
944 static VOID
ParseReleaseFile(CHAR16
**OSIconName
, REFIT_VOLUME
*Volume
, CHAR16
*FileName
) {
948 UINTN TokenCount
= 0;
950 if ((Volume
== NULL
) || (FileName
== NULL
) || (OSIconName
== NULL
) || (*OSIconName
== NULL
))
953 if (FileExists(Volume
->RootDir
, FileName
) &&
954 (ReadFile(Volume
->RootDir
, FileName
, &File
, &FileSize
) == EFI_SUCCESS
)) {
956 TokenCount
= ReadTokenLine(&File
, &TokenList
);
957 if ((TokenCount
> 1) && (MyStriCmp(TokenList
[0], L
"ID") ||
958 MyStriCmp(TokenList
[0], L
"NAME") ||
959 MyStriCmp(TokenList
[0], L
"DISTRIB_ID"))) {
960 MergeWords(OSIconName
, TokenList
[1], L
',');
962 FreeTokenLine(&TokenList
, &TokenCount
);
963 } while (TokenCount
> 0);
964 MyFreePool(File
.Buffer
);
966 } // VOID ParseReleaseFile()
968 // Try to guess the name of the Linux distribution & add that name to
970 static VOID
GuessLinuxDistribution(CHAR16
**OSIconName
, REFIT_VOLUME
*Volume
, CHAR16
*LoaderPath
) {
971 // If on Linux root fs, /etc/os-release or /etc/lsb-release file probably has clues....
972 ParseReleaseFile(OSIconName
, Volume
, L
"etc\\lsb-release");
973 ParseReleaseFile(OSIconName
, Volume
, L
"etc\\os-release");
975 // Search for clues in the kernel's filename....
976 if (StriSubCmp(L
".fc", LoaderPath
))
977 MergeStrings(OSIconName
, L
"fedora", L
',');
978 if (StriSubCmp(L
".el", LoaderPath
))
979 MergeStrings(OSIconName
, L
"redhat", L
',');
980 } // VOID GuessLinuxDistribution()
982 // Sets a few defaults for a loader entry -- mainly the icon, but also the OS type
983 // code and shortcut letter. For Linux EFI stub loaders, also sets kernel options
984 // that will (with luck) work fairly automatically.
985 VOID
SetLoaderDefaults(LOADER_ENTRY
*Entry
, CHAR16
*LoaderPath
, REFIT_VOLUME
*Volume
) {
986 CHAR16
*NameClues
, *PathOnly
, *NoExtension
, *OSIconName
= NULL
, *Temp
;
987 CHAR16 ShortcutLetter
= 0;
989 NameClues
= Basename(LoaderPath
);
990 PathOnly
= FindPath(LoaderPath
);
991 NoExtension
= StripEfiExtension(NameClues
);
993 if (Volume
->DiskKind
== DISK_KIND_NET
) {
994 MergeStrings(&NameClues
, Entry
->me
.Title
, L
' ');
996 // locate a custom icon for the loader
997 // Anything found here takes precedence over the "hints" in the OSIconName variable
998 if (!Entry
->me
.Image
) {
999 Entry
->me
.Image
= egLoadIconAnyType(Volume
->RootDir
, PathOnly
, NoExtension
, GlobalConfig
.IconSizes
[ICON_SIZE_BIG
]);
1001 if (!Entry
->me
.Image
) {
1002 Entry
->me
.Image
= egCopyImage(Volume
->VolIconImage
);
1005 // Begin creating icon "hints" by using last part of directory path leading
1007 Temp
= FindLastDirName(LoaderPath
);
1008 MergeStrings(&OSIconName
, Temp
, L
',');
1011 if (OSIconName
!= NULL
) {
1012 ShortcutLetter
= OSIconName
[0];
1015 // Add every "word" in the volume label, delimited by spaces, dashes (-), or
1016 // underscores (_), to the list of hints to be used in searching for OS
1018 MergeWords(&OSIconName
, Volume
->VolName
, L
',');
1019 } // if/else network boot
1021 // detect specific loaders
1022 if (StriSubCmp(L
"bzImage", NameClues
) || StriSubCmp(L
"vmlinuz", NameClues
) || StriSubCmp(L
"kernel", NameClues
)) {
1023 if (Volume
->DiskKind
!= DISK_KIND_NET
) {
1024 GuessLinuxDistribution(&OSIconName
, Volume
, LoaderPath
);
1025 Entry
->LoadOptions
= GetMainLinuxOptions(LoaderPath
, Volume
);
1027 MergeStrings(&OSIconName
, L
"linux", L
',');
1028 Entry
->OSType
= 'L';
1029 if (ShortcutLetter
== 0)
1030 ShortcutLetter
= 'L';
1031 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_LINUX
;
1032 } else if (StriSubCmp(L
"refit", LoaderPath
)) {
1033 MergeStrings(&OSIconName
, L
"refit", L
',');
1034 Entry
->OSType
= 'R';
1035 ShortcutLetter
= 'R';
1036 } else if (StriSubCmp(L
"refind", LoaderPath
)) {
1037 MergeStrings(&OSIconName
, L
"refind", L
',');
1038 Entry
->OSType
= 'R';
1039 ShortcutLetter
= 'R';
1040 } else if (MyStriCmp(LoaderPath
, MACOSX_LOADER_PATH
)) {
1041 MergeStrings(&OSIconName
, L
"mac", L
',');
1042 Entry
->OSType
= 'M';
1043 ShortcutLetter
= 'M';
1044 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_OSX
;
1045 } else if (MyStriCmp(NameClues
, L
"diags.efi")) {
1046 MergeStrings(&OSIconName
, L
"hwtest", L
',');
1047 } else if (MyStriCmp(NameClues
, L
"e.efi") || MyStriCmp(NameClues
, L
"elilo.efi") || StriSubCmp(L
"elilo", NameClues
)) {
1048 MergeStrings(&OSIconName
, L
"elilo,linux", L
',');
1049 Entry
->OSType
= 'E';
1050 if (ShortcutLetter
== 0)
1051 ShortcutLetter
= 'L';
1052 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_ELILO
;
1053 } else if (StriSubCmp(L
"grub", NameClues
)) {
1054 MergeStrings(&OSIconName
, L
"grub,linux", L
',');
1055 Entry
->OSType
= 'G';
1056 ShortcutLetter
= 'G';
1057 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_GRUB
;
1058 } else if (MyStriCmp(NameClues
, L
"cdboot.efi") ||
1059 MyStriCmp(NameClues
, L
"bootmgr.efi") ||
1060 MyStriCmp(NameClues
, L
"bootmgfw.efi") ||
1061 MyStriCmp(NameClues
, L
"bkpbootmgfw.efi")) {
1062 MergeStrings(&OSIconName
, L
"win8", L
',');
1063 Entry
->OSType
= 'W';
1064 ShortcutLetter
= 'W';
1065 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
1066 } else if (MyStriCmp(NameClues
, L
"xom.efi")) {
1067 MergeStrings(&OSIconName
, L
"xom,win,win8", L
',');
1068 Entry
->OSType
= 'X';
1069 ShortcutLetter
= 'W';
1070 Entry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_WINDOWS
;
1072 else if (StriSubCmp(L
"ipxe", NameClues
)) {
1073 Entry
->OSType
= 'N';
1074 ShortcutLetter
= 'N';
1075 MergeStrings(&OSIconName
, L
"network", L
',');
1078 if ((ShortcutLetter
>= 'a') && (ShortcutLetter
<= 'z'))
1079 ShortcutLetter
= ShortcutLetter
- 'a' + 'A'; // convert lowercase to uppercase
1080 Entry
->me
.ShortcutLetter
= ShortcutLetter
;
1081 if (Entry
->me
.Image
== NULL
)
1082 Entry
->me
.Image
= LoadOSIcon(OSIconName
, L
"unknown", FALSE
);
1083 MyFreePool(PathOnly
);
1084 } // VOID SetLoaderDefaults()
1086 // Add a specified EFI boot loader to the list, using automatic settings
1087 // for icons, options, etc.
1088 static LOADER_ENTRY
* AddLoaderEntry(IN CHAR16
*LoaderPath
, IN CHAR16
*LoaderTitle
, IN REFIT_VOLUME
*Volume
, IN BOOLEAN SubScreenReturn
) {
1089 LOADER_ENTRY
*Entry
;
1091 CleanUpPathNameSlashes(LoaderPath
);
1092 Entry
= InitializeLoaderEntry(NULL
);
1093 if (Entry
!= NULL
) {
1094 Entry
->Title
= StrDuplicate((LoaderTitle
!= NULL
) ? LoaderTitle
: LoaderPath
);
1095 Entry
->me
.Title
= AllocateZeroPool(sizeof(CHAR16
) * 256);
1096 // Extra space at end of Entry->me.Title enables searching on Volume->VolName even if another volume
1097 // name is identical except for something added to the end (e.g., VolB1 vs. VolB12).
1098 // Note: Volume->VolName will be NULL for network boot programs.
1099 if (Volume
->VolName
)
1100 SPrint(Entry
->me
.Title
, 255, L
"Boot %s from %s ", (LoaderTitle
!= NULL
) ? LoaderTitle
: LoaderPath
, Volume
->VolName
);
1102 SPrint(Entry
->me
.Title
, 255, L
"Boot %s ", (LoaderTitle
!= NULL
) ? LoaderTitle
: LoaderPath
);
1104 Entry
->me
.BadgeImage
= Volume
->VolBadgeImage
;
1105 if ((LoaderPath
!= NULL
) && (LoaderPath
[0] != L
'\\')) {
1106 Entry
->LoaderPath
= StrDuplicate(L
"\\");
1108 Entry
->LoaderPath
= NULL
;
1110 MergeStrings(&(Entry
->LoaderPath
), LoaderPath
, 0);
1111 Entry
->VolName
= Volume
->VolName
;
1112 Entry
->DevicePath
= FileDevicePath(Volume
->DeviceHandle
, Entry
->LoaderPath
);
1113 SetLoaderDefaults(Entry
, LoaderPath
, Volume
);
1114 GenerateSubScreen(Entry
, Volume
, SubScreenReturn
);
1115 AddMenuEntry(&MainMenu
, (REFIT_MENU_ENTRY
*)Entry
);
1119 } // LOADER_ENTRY * AddLoaderEntry()
1121 // Add a Linux kernel as a submenu entry for another (pre-existing) Linux kernel entry.
1122 static VOID
AddKernelToSubmenu(LOADER_ENTRY
* TargetLoader
, CHAR16
*FileName
, REFIT_VOLUME
*Volume
) {
1124 CHAR16
**TokenList
= NULL
, *InitrdName
, *SubmenuName
= NULL
, *VolName
= NULL
, *Path
= NULL
, *Title
;
1125 REFIT_MENU_SCREEN
*SubScreen
;
1126 LOADER_ENTRY
*SubEntry
;
1129 File
= ReadLinuxOptionsFile(TargetLoader
->LoaderPath
, Volume
);
1131 SubScreen
= TargetLoader
->me
.SubScreen
;
1132 InitrdName
= FindInitrd(FileName
, Volume
);
1133 while ((TokenCount
= ReadTokenLine(File
, &TokenList
)) > 1) {
1134 SubEntry
= InitializeLoaderEntry(TargetLoader
);
1135 SplitPathName(FileName
, &VolName
, &Path
, &SubmenuName
);
1136 MergeStrings(&SubmenuName
, L
": ", '\0');
1137 MergeStrings(&SubmenuName
, TokenList
[0] ? StrDuplicate(TokenList
[0]) : StrDuplicate(L
"Boot Linux"), '\0');
1138 Title
= StrDuplicate(SubmenuName
);
1139 LimitStringLength(Title
, MAX_LINE_LENGTH
);
1140 SubEntry
->me
.Title
= Title
;
1141 MyFreePool(SubEntry
->LoadOptions
);
1142 SubEntry
->LoadOptions
= AddInitrdToOptions(TokenList
[1], InitrdName
);
1143 MyFreePool(SubEntry
->LoaderPath
);
1144 SubEntry
->LoaderPath
= StrDuplicate(FileName
);
1145 CleanUpPathNameSlashes(SubEntry
->LoaderPath
);
1146 SubEntry
->DevicePath
= FileDevicePath(Volume
->DeviceHandle
, SubEntry
->LoaderPath
);
1147 FreeTokenLine(&TokenList
, &TokenCount
);
1148 SubEntry
->UseGraphicsMode
= GlobalConfig
.GraphicsFor
& GRAPHICS_FOR_LINUX
;
1149 AddMenuEntry(SubScreen
, (REFIT_MENU_ENTRY
*)SubEntry
);
1151 MyFreePool(VolName
);
1153 MyFreePool(SubmenuName
);
1154 MyFreePool(InitrdName
);
1157 } // static VOID AddKernelToSubmenu()
1159 // Returns -1 if (Time1 < Time2), +1 if (Time1 > Time2), or 0 if
1160 // (Time1 == Time2). Precision is only to the nearest second; since
1161 // this is used for sorting boot loader entries, differences smaller
1162 // than this are likely to be meaningless (and unlikely!).
1163 INTN
TimeComp(IN EFI_TIME
*Time1
, IN EFI_TIME
*Time2
) {
1164 INT64 Time1InSeconds
, Time2InSeconds
;
1166 // Following values are overestimates; I'm assuming 31 days in every month.
1167 // This is fine for the purpose of this function, which is limited
1168 Time1InSeconds
= Time1
->Second
+ (Time1
->Minute
* 60) + (Time1
->Hour
* 3600) + (Time1
->Day
* 86400) +
1169 (Time1
->Month
* 2678400) + ((Time1
->Year
- 1998) * 32140800);
1170 Time2InSeconds
= Time2
->Second
+ (Time2
->Minute
* 60) + (Time2
->Hour
* 3600) + (Time2
->Day
* 86400) +
1171 (Time2
->Month
* 2678400) + ((Time2
->Year
- 1998) * 32140800);
1172 if (Time1InSeconds
< Time2InSeconds
)
1174 else if (Time1InSeconds
> Time2InSeconds
)
1178 } // INTN TimeComp()
1180 // Adds a loader list element, keeping it sorted by date. Returns the new
1181 // first element (the one with the most recent date).
1182 static struct LOADER_LIST
* AddLoaderListEntry(struct LOADER_LIST
*LoaderList
, struct LOADER_LIST
*NewEntry
) {
1183 struct LOADER_LIST
*LatestEntry
, *CurrentEntry
, *PrevEntry
= NULL
;
1185 LatestEntry
= CurrentEntry
= LoaderList
;
1186 if (LoaderList
== NULL
) {
1187 LatestEntry
= NewEntry
;
1189 while ((CurrentEntry
!= NULL
) && (TimeComp(&(NewEntry
->TimeStamp
), &(CurrentEntry
->TimeStamp
)) < 0)) {
1190 PrevEntry
= CurrentEntry
;
1191 CurrentEntry
= CurrentEntry
->NextEntry
;
1193 NewEntry
->NextEntry
= CurrentEntry
;
1194 if (PrevEntry
== NULL
) {
1195 LatestEntry
= NewEntry
;
1197 PrevEntry
->NextEntry
= NewEntry
;
1200 return (LatestEntry
);
1201 } // static VOID AddLoaderListEntry()
1203 // Delete the LOADER_LIST linked list
1204 static VOID
CleanUpLoaderList(struct LOADER_LIST
*LoaderList
) {
1205 struct LOADER_LIST
*Temp
;
1207 while (LoaderList
!= NULL
) {
1209 LoaderList
= LoaderList
->NextEntry
;
1210 MyFreePool(Temp
->FileName
);
1213 } // static VOID CleanUpLoaderList()
1215 // Returns FALSE if the specified file/volume matches the GlobalConfig.DontScanDirs
1216 // or GlobalConfig.DontScanVolumes specification, or if Path points to a volume
1217 // other than the one specified by Volume, or if the specified path is SelfDir.
1218 // Returns TRUE if none of these conditions is met -- that is, if the path is
1219 // eligible for scanning.
1220 static BOOLEAN
ShouldScan(REFIT_VOLUME
*Volume
, CHAR16
*Path
) {
1221 CHAR16
*VolName
= NULL
, *DontScanDir
, *PathCopy
= NULL
;
1223 BOOLEAN ScanIt
= TRUE
;
1225 if ((IsIn(Volume
->VolName
, GlobalConfig
.DontScanVolumes
)) || (IsIn(Volume
->PartName
, GlobalConfig
.DontScanVolumes
)))
1228 if (MyStriCmp(Path
, SelfDirPath
) && (Volume
->DeviceHandle
== SelfVolume
->DeviceHandle
))
1231 // See if Path includes an explicit volume declaration that's NOT Volume....
1232 PathCopy
= StrDuplicate(Path
);
1233 if (SplitVolumeAndFilename(&PathCopy
, &VolName
)) {
1234 VolumeNumberToName(Volume
, &VolName
);
1235 if (VolName
&& !MyStriCmp(VolName
, Volume
->VolName
)) {
1238 } // if Path includes volume specification
1239 MyFreePool(PathCopy
);
1240 MyFreePool(VolName
);
1243 // See if Volume is in GlobalConfig.DontScanDirs....
1244 while (ScanIt
&& (DontScanDir
= FindCommaDelimited(GlobalConfig
.DontScanDirs
, i
++))) {
1245 SplitVolumeAndFilename(&DontScanDir
, &VolName
);
1246 CleanUpPathNameSlashes(DontScanDir
);
1247 VolumeNumberToName(Volume
, &VolName
);
1248 if (VolName
!= NULL
) {
1249 if (MyStriCmp(VolName
, Volume
->VolName
) && MyStriCmp(DontScanDir
, Path
))
1252 if (MyStriCmp(DontScanDir
, Path
))
1255 MyFreePool(DontScanDir
);
1256 MyFreePool(VolName
);
1262 } // BOOLEAN ShouldScan()
1264 // Returns TRUE if the file is byte-for-byte identical with the fallback file
1265 // on the volume AND if the file is not itself the fallback file; returns
1266 // FALSE if the file is not identical to the fallback file OR if the file
1267 // IS the fallback file. Intended for use in excluding the fallback boot
1268 // loader when it's a duplicate of another boot loader.
1269 static BOOLEAN
DuplicatesFallback(IN REFIT_VOLUME
*Volume
, IN CHAR16
*FileName
) {
1270 CHAR8
*FileContents
, *FallbackContents
;
1271 EFI_FILE_HANDLE FileHandle
, FallbackHandle
;
1272 EFI_FILE_INFO
*FileInfo
, *FallbackInfo
;
1273 UINTN FileSize
= 0, FallbackSize
= 0;
1275 BOOLEAN AreIdentical
= FALSE
;
1277 if (!FileExists(Volume
->RootDir
, FileName
) || !FileExists(Volume
->RootDir
, FALLBACK_FULLNAME
))
1280 CleanUpPathNameSlashes(FileName
);
1282 if (MyStriCmp(FileName
, FALLBACK_FULLNAME
))
1283 return FALSE
; // identical filenames, so not a duplicate....
1285 Status
= refit_call5_wrapper(Volume
->RootDir
->Open
, Volume
->RootDir
, &FileHandle
, FileName
, EFI_FILE_MODE_READ
, 0);
1286 if (Status
== EFI_SUCCESS
) {
1287 FileInfo
= LibFileInfo(FileHandle
);
1288 FileSize
= FileInfo
->FileSize
;
1293 Status
= refit_call5_wrapper(Volume
->RootDir
->Open
, Volume
->RootDir
, &FallbackHandle
, FALLBACK_FULLNAME
, EFI_FILE_MODE_READ
, 0);
1294 if (Status
== EFI_SUCCESS
) {
1295 FallbackInfo
= LibFileInfo(FallbackHandle
);
1296 FallbackSize
= FallbackInfo
->FileSize
;
1298 refit_call1_wrapper(FileHandle
->Close
, FileHandle
);
1302 if (FallbackSize
!= FileSize
) { // not same size, so can't be identical
1303 AreIdentical
= FALSE
;
1304 } else { // could be identical; do full check....
1305 FileContents
= AllocatePool(FileSize
);
1306 FallbackContents
= AllocatePool(FallbackSize
);
1307 if (FileContents
&& FallbackContents
) {
1308 Status
= refit_call3_wrapper(FileHandle
->Read
, FileHandle
, &FileSize
, FileContents
);
1309 if (Status
== EFI_SUCCESS
) {
1310 Status
= refit_call3_wrapper(FallbackHandle
->Read
, FallbackHandle
, &FallbackSize
, FallbackContents
);
1312 if (Status
== EFI_SUCCESS
) {
1313 AreIdentical
= (CompareMem(FileContents
, FallbackContents
, FileSize
) == 0);
1316 MyFreePool(FileContents
);
1317 MyFreePool(FallbackContents
);
1320 // BUG ALERT: Some systems (e.g., DUET, some Macs with large displays) crash if the
1321 // following two calls are reversed. Go figure....
1322 refit_call1_wrapper(FileHandle
->Close
, FallbackHandle
);
1323 refit_call1_wrapper(FileHandle
->Close
, FileHandle
);
1324 return AreIdentical
;
1325 } // BOOLEAN DuplicatesFallback()
1327 // Returns FALSE if two measures of file size are identical for a single file,
1328 // TRUE if not or if the file can't be opened and the other measure is non-0.
1329 // Despite the function's name, this isn't really a direct test of symbolic
1330 // link status, since EFI doesn't officially support symlinks. It does seem
1331 // to be a reliable indicator, though. (OTOH, some disk errors might cause a
1332 // file to fail to open, which would return a false positive -- but as I use
1333 // this function to exclude symbolic links from the list of boot loaders,
1334 // that would be fine, since such boot loaders wouldn't work.)
1335 static BOOLEAN
IsSymbolicLink(REFIT_VOLUME
*Volume
, CHAR16
*Path
, EFI_FILE_INFO
*DirEntry
) {
1336 EFI_FILE_HANDLE FileHandle
;
1337 EFI_FILE_INFO
*FileInfo
= NULL
;
1339 UINTN FileSize2
= 0;
1342 FileName
= StrDuplicate(Path
);
1343 MergeStrings(&FileName
, DirEntry
->FileName
, L
'\\');
1344 CleanUpPathNameSlashes(FileName
);
1346 Status
= refit_call5_wrapper(Volume
->RootDir
->Open
, Volume
->RootDir
, &FileHandle
, FileName
, EFI_FILE_MODE_READ
, 0);
1347 if (Status
== EFI_SUCCESS
) {
1348 FileInfo
= LibFileInfo(FileHandle
);
1349 if (FileInfo
!= NULL
)
1350 FileSize2
= FileInfo
->FileSize
;
1353 MyFreePool(FileName
);
1354 MyFreePool(FileInfo
);
1356 return (DirEntry
->FileSize
!= FileSize2
);
1357 } // BOOLEAN IsSymbolicLink()
1359 // Returns TRUE if a file with the same name as the original but with
1360 // ".efi.signed" is also present in the same directory. Ubuntu is using
1361 // this filename as a signed version of the original unsigned kernel, and
1362 // there's no point in cluttering the display with two kernels that will
1363 // behave identically on non-SB systems, or when one will fail when SB
1365 static BOOLEAN
HasSignedCounterpart(IN REFIT_VOLUME
*Volume
, IN CHAR16
*Path
, IN CHAR16
*Filename
) {
1366 CHAR16
*NewFile
= NULL
;
1367 BOOLEAN retval
= FALSE
;
1369 MergeStrings(&NewFile
, Path
, 0);
1370 MergeStrings(&NewFile
, Filename
, L
'\\');
1371 MergeStrings(&NewFile
, L
".efi.signed", 0);
1372 if (NewFile
!= NULL
) {
1373 CleanUpPathNameSlashes(NewFile
);
1374 if (FileExists(Volume
->RootDir
, NewFile
))
1376 MyFreePool(NewFile
);
1380 } // BOOLEAN HasSignedCounterpart()
1382 // Scan an individual directory for EFI boot loader files and, if found,
1383 // add them to the list. Exception: Ignores FALLBACK_FULLNAME, which is picked
1384 // up in ScanEfiFiles(). Sorts the entries within the loader directory so that
1385 // the most recent one appears first in the list.
1386 // Returns TRUE if a duplicate for FALLBACK_FILENAME was found, FALSE if not.
1387 static BOOLEAN
ScanLoaderDir(IN REFIT_VOLUME
*Volume
, IN CHAR16
*Path
, IN CHAR16
*Pattern
)
1390 REFIT_DIR_ITER DirIter
;
1391 EFI_FILE_INFO
*DirEntry
;
1392 CHAR16 FileName
[256], *Extension
;
1393 struct LOADER_LIST
*LoaderList
= NULL
, *NewLoader
;
1394 LOADER_ENTRY
*FirstKernel
= NULL
, *LatestEntry
= NULL
;
1395 BOOLEAN FoundFallbackDuplicate
= FALSE
, IsLinux
= FALSE
, InSelfPath
;
1397 InSelfPath
= MyStriCmp(Path
, SelfDirPath
);
1398 if ((!SelfDirPath
|| !Path
|| (InSelfPath
&& (Volume
->DeviceHandle
!= SelfVolume
->DeviceHandle
)) ||
1399 (!InSelfPath
)) && (ShouldScan(Volume
, Path
))) {
1400 // look through contents of the directory
1401 DirIterOpen(Volume
->RootDir
, Path
, &DirIter
);
1402 while (DirIterNext(&DirIter
, 2, Pattern
, &DirEntry
)) {
1403 Extension
= FindExtension(DirEntry
->FileName
);
1404 if (DirEntry
->FileName
[0] == '.' ||
1405 MyStriCmp(Extension
, L
".icns") ||
1406 MyStriCmp(Extension
, L
".png") ||
1407 (MyStriCmp(DirEntry
->FileName
, FALLBACK_BASENAME
) && (MyStriCmp(Path
, L
"EFI\\BOOT"))) ||
1408 StriSubCmp(L
"shell", DirEntry
->FileName
) ||
1409 IsSymbolicLink(Volume
, Path
, DirEntry
) || /* is symbolic link */
1410 HasSignedCounterpart(Volume
, Path
, DirEntry
->FileName
) || /* a file with same name plus ".efi.signed" is present */
1411 FilenameIn(Volume
, Path
, DirEntry
->FileName
, GlobalConfig
.DontScanFiles
))
1412 continue; // skip this
1415 SPrint(FileName
, 255, L
"\\%s\\%s", Path
, DirEntry
->FileName
);
1417 SPrint(FileName
, 255, L
"\\%s", DirEntry
->FileName
);
1418 CleanUpPathNameSlashes(FileName
);
1420 if(!IsValidLoader(Volume
->RootDir
, FileName
))
1423 NewLoader
= AllocateZeroPool(sizeof(struct LOADER_LIST
));
1424 if (NewLoader
!= NULL
) {
1425 NewLoader
->FileName
= StrDuplicate(FileName
);
1426 NewLoader
->TimeStamp
= DirEntry
->ModificationTime
;
1427 LoaderList
= AddLoaderListEntry(LoaderList
, NewLoader
);
1428 if (DuplicatesFallback(Volume
, FileName
))
1429 FoundFallbackDuplicate
= TRUE
;
1431 MyFreePool(Extension
);
1434 NewLoader
= LoaderList
;
1435 while (NewLoader
!= NULL
) {
1436 IsLinux
= (StriSubCmp(L
"bzImage", NewLoader
->FileName
) ||
1437 StriSubCmp(L
"vmlinuz", NewLoader
->FileName
) ||
1438 StriSubCmp(L
"kernel", NewLoader
->FileName
));
1439 if ((FirstKernel
!= NULL
) && IsLinux
&& GlobalConfig
.FoldLinuxKernels
) {
1440 AddKernelToSubmenu(FirstKernel
, NewLoader
->FileName
, Volume
);
1442 LatestEntry
= AddLoaderEntry(NewLoader
->FileName
, NULL
, Volume
, !(IsLinux
&& GlobalConfig
.FoldLinuxKernels
));
1443 if (IsLinux
&& (FirstKernel
== NULL
))
1444 FirstKernel
= LatestEntry
;
1446 NewLoader
= NewLoader
->NextEntry
;
1448 if ((NewLoader
!= NULL
) && (FirstKernel
!= NULL
) && IsLinux
&& GlobalConfig
.FoldLinuxKernels
)
1449 AddMenuEntry(FirstKernel
->me
.SubScreen
, &MenuEntryReturn
);
1451 CleanUpLoaderList(LoaderList
);
1452 Status
= DirIterClose(&DirIter
);
1453 // NOTE: EFI_INVALID_PARAMETER really is an error that should be reported;
1454 // but I've gotten reports from users who are getting this error occasionally
1455 // and I can't find anything wrong or reproduce the problem, so I'm putting
1456 // it down to buggy EFI implementations and ignoring that particular error....
1457 if ((Status
!= EFI_NOT_FOUND
) && (Status
!= EFI_INVALID_PARAMETER
)) {
1459 SPrint(FileName
, 255, L
"while scanning the %s directory", Path
);
1461 StrCpy(FileName
, L
"while scanning the root directory");
1462 CheckError(Status
, FileName
);
1463 } // if (Status != EFI_NOT_FOUND)
1464 } // if not scanning a blacklisted directory
1466 return FoundFallbackDuplicate
;
1467 } /* static VOID ScanLoaderDir() */
1469 // Run the IPXE_DISCOVER_NAME program, which obtains the IP address of the boot
1470 // server and the name of the boot file it delivers.
1471 CHAR16
* RuniPXEDiscover(EFI_HANDLE Volume
)
1474 EFI_DEVICE_PATH
*FilePath
;
1475 EFI_HANDLE iPXEHandle
;
1476 CHAR16
*boot_info
= NULL
;
1477 UINTN boot_info_size
= 0;
1479 FilePath
= FileDevicePath (Volume
, IPXE_DISCOVER_NAME
);
1480 Status
= refit_call6_wrapper(BS
->LoadImage
, FALSE
, SelfImageHandle
, FilePath
, NULL
, 0, &iPXEHandle
);
1484 Status
= refit_call3_wrapper(BS
->StartImage
, iPXEHandle
, &boot_info_size
, &boot_info
);
1487 } // RuniPXEDiscover()
1489 // Scan for network (PXE) boot servers. This function relies on the presence
1490 // of the IPXE_DISCOVER_NAME and IPXE_NAME program files on the volume from
1491 // which rEFInd launched. As of December 6, 2014, these tools aren't entirely
1492 // reliable. See BUILDING.txt for information on building them.
1493 static VOID
ScanNetboot() {
1494 CHAR16
*iPXEFileName
= IPXE_NAME
;
1496 REFIT_VOLUME
*NetVolume
;
1498 if (FileExists(SelfVolume
->RootDir
, IPXE_DISCOVER_NAME
) &&
1499 FileExists(SelfVolume
->RootDir
, IPXE_NAME
) &&
1500 IsValidLoader(SelfVolume
->RootDir
, IPXE_DISCOVER_NAME
) &&
1501 IsValidLoader(SelfVolume
->RootDir
, IPXE_NAME
)) {
1502 Location
= RuniPXEDiscover(SelfVolume
->DeviceHandle
);
1503 if (Location
!= NULL
&& FileExists(SelfVolume
->RootDir
, iPXEFileName
)) {
1504 NetVolume
= AllocatePool(sizeof(REFIT_VOLUME
));
1505 CopyMem(NetVolume
, SelfVolume
, sizeof(REFIT_VOLUME
));
1506 NetVolume
->DiskKind
= DISK_KIND_NET
;
1507 NetVolume
->VolBadgeImage
= BuiltinIcon(BUILTIN_ICON_VOL_NET
);
1508 NetVolume
->PartName
= NetVolume
->VolName
= NULL
;
1509 AddLoaderEntry(iPXEFileName
, Location
, NetVolume
, TRUE
);
1510 MyFreePool(NetVolume
);
1511 } // if support files exist and are valid
1513 } // VOID ScanNetBoot()
1515 static VOID
ScanEfiFiles(REFIT_VOLUME
*Volume
) {
1517 REFIT_DIR_ITER EfiDirIter
;
1518 EFI_FILE_INFO
*EfiDirEntry
;
1519 CHAR16 FileName
[256], *Directory
= NULL
, *MatchPatterns
, *VolName
= NULL
, *SelfPath
;
1521 BOOLEAN ScanFallbackLoader
= TRUE
;
1522 BOOLEAN FoundBRBackup
= FALSE
;
1524 if (Volume
&& (Volume
->RootDir
!= NULL
) && (Volume
->VolName
!= NULL
) && (Volume
->IsReadable
)) {
1525 MatchPatterns
= StrDuplicate(LOADER_MATCH_PATTERNS
);
1526 if (GlobalConfig
.ScanAllLinux
)
1527 MergeStrings(&MatchPatterns
, LINUX_MATCH_PATTERNS
, L
',');
1529 // check for Mac OS X boot loader
1530 if (ShouldScan(Volume
, MACOSX_LOADER_DIR
)) {
1531 StrCpy(FileName
, MACOSX_LOADER_PATH
);
1532 if (FileExists(Volume
->RootDir
, FileName
) && !FilenameIn(Volume
, MACOSX_LOADER_DIR
, L
"boot.efi", GlobalConfig
.DontScanFiles
)) {
1533 AddLoaderEntry(FileName
, L
"Mac OS X", Volume
, TRUE
);
1534 if (DuplicatesFallback(Volume
, FileName
))
1535 ScanFallbackLoader
= FALSE
;
1539 StrCpy(FileName
, L
"System\\Library\\CoreServices\\xom.efi");
1540 if (FileExists(Volume
->RootDir
, FileName
) && !FilenameIn(Volume
, MACOSX_LOADER_DIR
, L
"xom.efi", GlobalConfig
.DontScanFiles
)) {
1541 AddLoaderEntry(FileName
, L
"Windows XP (XoM)", Volume
, TRUE
);
1542 if (DuplicatesFallback(Volume
, FileName
))
1543 ScanFallbackLoader
= FALSE
;
1545 } // if should scan Mac directory
1547 // check for Microsoft boot loader/menu
1548 if (ShouldScan(Volume
, L
"EFI\\Microsoft\\Boot")) {
1549 StrCpy(FileName
, L
"EFI\\Microsoft\\Boot\\bkpbootmgfw.efi");
1550 if (FileExists(Volume
->RootDir
, FileName
) && !FilenameIn(Volume
, L
"EFI\\Microsoft\\Boot", L
"bkpbootmgfw.efi",
1551 GlobalConfig
.DontScanFiles
)) {
1552 AddLoaderEntry(FileName
, L
"Microsoft EFI boot (Boot Repair backup)", Volume
, TRUE
);
1553 FoundBRBackup
= TRUE
;
1554 if (DuplicatesFallback(Volume
, FileName
))
1555 ScanFallbackLoader
= FALSE
;
1557 StrCpy(FileName
, L
"EFI\\Microsoft\\Boot\\bootmgfw.efi");
1558 if (FileExists(Volume
->RootDir
, FileName
) &&
1559 !FilenameIn(Volume
, L
"EFI\\Microsoft\\Boot", L
"bootmgfw.efi", GlobalConfig
.DontScanFiles
)) {
1561 AddLoaderEntry(FileName
, L
"Supposed Microsoft EFI boot (probably GRUB)", Volume
, TRUE
);
1563 AddLoaderEntry(FileName
, L
"Microsoft EFI boot", Volume
, TRUE
);
1564 if (DuplicatesFallback(Volume
, FileName
))
1565 ScanFallbackLoader
= FALSE
;
1569 // scan the root directory for EFI executables
1570 if (ScanLoaderDir(Volume
, L
"\\", MatchPatterns
))
1571 ScanFallbackLoader
= FALSE
;
1573 // scan subdirectories of the EFI directory (as per the standard)
1574 DirIterOpen(Volume
->RootDir
, L
"EFI", &EfiDirIter
);
1575 while (DirIterNext(&EfiDirIter
, 1, NULL
, &EfiDirEntry
)) {
1576 if (MyStriCmp(EfiDirEntry
->FileName
, L
"tools") || EfiDirEntry
->FileName
[0] == '.')
1577 continue; // skip this, doesn't contain boot loaders or is scanned later
1578 SPrint(FileName
, 255, L
"EFI\\%s", EfiDirEntry
->FileName
);
1579 if (ScanLoaderDir(Volume
, FileName
, MatchPatterns
))
1580 ScanFallbackLoader
= FALSE
;
1582 Status
= DirIterClose(&EfiDirIter
);
1583 if ((Status
!= EFI_NOT_FOUND
) && (Status
!= EFI_INVALID_PARAMETER
))
1584 CheckError(Status
, L
"while scanning the EFI directory");
1586 // Scan user-specified (or additional default) directories....
1588 while ((Directory
= FindCommaDelimited(GlobalConfig
.AlsoScan
, i
++)) != NULL
) {
1589 if (ShouldScan(Volume
, Directory
)) {
1590 SplitVolumeAndFilename(&Directory
, &VolName
);
1591 CleanUpPathNameSlashes(Directory
);
1592 Length
= StrLen(Directory
);
1593 if ((Length
> 0) && ScanLoaderDir(Volume
, Directory
, MatchPatterns
))
1594 ScanFallbackLoader
= FALSE
;
1595 MyFreePool(VolName
);
1596 } // if should scan dir
1597 MyFreePool(Directory
);
1600 // Don't scan the fallback loader if it's on the same volume and a duplicate of rEFInd itself....
1601 SelfPath
= DevicePathToStr(SelfLoadedImage
->FilePath
);
1602 CleanUpPathNameSlashes(SelfPath
);
1603 if ((Volume
->DeviceHandle
== SelfLoadedImage
->DeviceHandle
) && DuplicatesFallback(Volume
, SelfPath
))
1604 ScanFallbackLoader
= FALSE
;
1606 // If not a duplicate & if it exists & if it's not us, create an entry
1607 // for the fallback boot loader
1608 if (ScanFallbackLoader
&& FileExists(Volume
->RootDir
, FALLBACK_FULLNAME
) && ShouldScan(Volume
, L
"EFI\\BOOT")) {
1609 AddLoaderEntry(FALLBACK_FULLNAME
, L
"Fallback boot loader", Volume
, TRUE
);
1612 } // static VOID ScanEfiFiles()
1614 // Scan internal disks for valid EFI boot loaders....
1615 static VOID
ScanInternal(VOID
) {
1618 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1619 if (Volumes
[VolumeIndex
]->DiskKind
== DISK_KIND_INTERNAL
) {
1620 ScanEfiFiles(Volumes
[VolumeIndex
]);
1623 } // static VOID ScanInternal()
1625 // Scan external disks for valid EFI boot loaders....
1626 static VOID
ScanExternal(VOID
) {
1629 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1630 if (Volumes
[VolumeIndex
]->DiskKind
== DISK_KIND_EXTERNAL
) {
1631 ScanEfiFiles(Volumes
[VolumeIndex
]);
1634 } // static VOID ScanExternal()
1636 // Scan internal disks for valid EFI boot loaders....
1637 static VOID
ScanOptical(VOID
) {
1640 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1641 if (Volumes
[VolumeIndex
]->DiskKind
== DISK_KIND_OPTICAL
) {
1642 ScanEfiFiles(Volumes
[VolumeIndex
]);
1645 } // static VOID ScanOptical()
1647 // default volume badge icon based on disk kind
1648 EG_IMAGE
* GetDiskBadge(IN UINTN DiskType
) {
1649 EG_IMAGE
* Badge
= NULL
;
1653 Badge
= BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL
);
1656 Badge
= BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL
);
1659 Badge
= BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL
);
1663 } // EG_IMAGE * GetDiskBadge()
1666 // pre-boot tool functions
1669 static VOID
StartTool(IN LOADER_ENTRY
*Entry
)
1671 BeginExternalScreen(Entry
->UseGraphicsMode
, Entry
->me
.Title
+ 6); // assumes "Start <title>" as assigned below
1672 StoreLoaderName(Entry
->me
.Title
);
1673 StartEFIImage(Entry
->DevicePath
, Entry
->LoadOptions
, TYPE_EFI
,
1674 Basename(Entry
->LoaderPath
), Entry
->OSType
, NULL
, TRUE
, FALSE
);
1675 FinishExternalScreen();
1676 } /* static VOID StartTool() */
1678 static LOADER_ENTRY
* AddToolEntry(EFI_HANDLE DeviceHandle
, IN CHAR16
*LoaderPath
, IN CHAR16
*LoaderTitle
, IN EG_IMAGE
*Image
,
1679 IN CHAR16 ShortcutLetter
, IN BOOLEAN UseGraphicsMode
)
1681 LOADER_ENTRY
*Entry
;
1682 CHAR16
*TitleStr
= NULL
;
1684 Entry
= AllocateZeroPool(sizeof(LOADER_ENTRY
));
1686 TitleStr
= PoolPrint(L
"Start %s", LoaderTitle
);
1687 Entry
->me
.Title
= TitleStr
;
1688 Entry
->me
.Tag
= TAG_TOOL
;
1690 Entry
->me
.ShortcutLetter
= ShortcutLetter
;
1691 Entry
->me
.Image
= Image
;
1692 Entry
->LoaderPath
= (LoaderPath
) ? StrDuplicate(LoaderPath
) : NULL
;
1693 Entry
->DevicePath
= FileDevicePath(DeviceHandle
, Entry
->LoaderPath
);
1694 Entry
->UseGraphicsMode
= UseGraphicsMode
;
1696 AddMenuEntry(&MainMenu
, (REFIT_MENU_ENTRY
*)Entry
);
1698 } /* static LOADER_ENTRY * AddToolEntry() */
1701 // pre-boot driver functions
1704 static UINTN
ScanDriverDir(IN CHAR16
*Path
)
1707 REFIT_DIR_ITER DirIter
;
1709 EFI_FILE_INFO
*DirEntry
;
1710 CHAR16 FileName
[256];
1712 CleanUpPathNameSlashes(Path
);
1713 // look through contents of the directory
1714 DirIterOpen(SelfRootDir
, Path
, &DirIter
);
1715 while (DirIterNext(&DirIter
, 2, LOADER_MATCH_PATTERNS
, &DirEntry
)) {
1716 if (DirEntry
->FileName
[0] == '.')
1717 continue; // skip this
1719 SPrint(FileName
, 255, L
"%s\\%s", Path
, DirEntry
->FileName
);
1721 Status
= StartEFIImage(FileDevicePath(SelfLoadedImage
->DeviceHandle
, FileName
),
1722 L
"", TYPE_EFI
, DirEntry
->FileName
, 0, NULL
, FALSE
, TRUE
);
1724 Status
= DirIterClose(&DirIter
);
1725 if ((Status
!= EFI_NOT_FOUND
) && (Status
!= EFI_INVALID_PARAMETER
)) {
1726 SPrint(FileName
, 255, L
"while scanning the %s directory", Path
);
1727 CheckError(Status
, FileName
);
1732 #ifdef __MAKEWITH_GNUEFI
1733 static EFI_STATUS
ConnectAllDriversToAllControllers(VOID
)
1736 UINTN AllHandleCount
;
1737 EFI_HANDLE
*AllHandleBuffer
;
1740 EFI_HANDLE
*HandleBuffer
;
1746 Status
= LibLocateHandle(AllHandles
,
1751 if (EFI_ERROR(Status
))
1754 for (Index
= 0; Index
< AllHandleCount
; Index
++) {
1756 // Scan the handle database
1758 Status
= LibScanHandleDatabase(NULL
,
1760 AllHandleBuffer
[Index
],
1765 if (EFI_ERROR (Status
))
1769 if (HandleType
[Index
] & EFI_HANDLE_TYPE_DRIVER_BINDING_HANDLE
)
1771 if (HandleType
[Index
] & EFI_HANDLE_TYPE_IMAGE_HANDLE
)
1776 for (HandleIndex
= 0; HandleIndex
< HandleCount
; HandleIndex
++) {
1777 if (HandleType
[HandleIndex
] & EFI_HANDLE_TYPE_PARENT_HANDLE
)
1782 if (HandleType
[Index
] & EFI_HANDLE_TYPE_DEVICE_HANDLE
) {
1783 Status
= refit_call4_wrapper(BS
->ConnectController
,
1784 AllHandleBuffer
[Index
],
1792 MyFreePool (HandleBuffer
);
1793 MyFreePool (HandleType
);
1797 MyFreePool (AllHandleBuffer
);
1799 } /* EFI_STATUS ConnectAllDriversToAllControllers() */
1801 static EFI_STATUS
ConnectAllDriversToAllControllers(VOID
) {
1802 BdsLibConnectAllDriversToAllControllers();
1807 // Load all EFI drivers from rEFInd's "drivers" subdirectory and from the
1808 // directories specified by the user in the "scan_driver_dirs" configuration
1810 static VOID
LoadDrivers(VOID
)
1812 CHAR16
*Directory
, *SelfDirectory
;
1813 UINTN i
= 0, Length
, NumFound
= 0;
1815 // load drivers from the subdirectories of rEFInd's home directory specified
1816 // in the DRIVER_DIRS constant.
1817 while ((Directory
= FindCommaDelimited(DRIVER_DIRS
, i
++)) != NULL
) {
1818 SelfDirectory
= SelfDirPath
? StrDuplicate(SelfDirPath
) : NULL
;
1819 CleanUpPathNameSlashes(SelfDirectory
);
1820 MergeStrings(&SelfDirectory
, Directory
, L
'\\');
1821 NumFound
+= ScanDriverDir(SelfDirectory
);
1822 MyFreePool(Directory
);
1823 MyFreePool(SelfDirectory
);
1826 // Scan additional user-specified driver directories....
1828 while ((Directory
= FindCommaDelimited(GlobalConfig
.DriverDirs
, i
++)) != NULL
) {
1829 CleanUpPathNameSlashes(Directory
);
1830 Length
= StrLen(Directory
);
1832 NumFound
+= ScanDriverDir(Directory
);
1834 MyFreePool(Directory
);
1837 // connect all devices
1839 ConnectAllDriversToAllControllers();
1841 } /* static VOID LoadDrivers() */
1843 // Locates boot loaders. NOTE: This assumes that GlobalConfig.LegacyType is set correctly.
1844 static VOID
ScanForBootloaders(VOID
) {
1847 BOOLEAN ScanForLegacy
= FALSE
;
1849 // Determine up-front if we'll be scanning for legacy loaders....
1850 for (i
= 0; i
< NUM_SCAN_OPTIONS
; i
++) {
1851 s
= GlobalConfig
.ScanFor
[i
];
1852 if ((s
== 'c') || (s
== 'C') || (s
== 'h') || (s
== 'H') || (s
== 'b') || (s
== 'B'))
1853 ScanForLegacy
= TRUE
;
1856 // If UEFI & scanning for legacy loaders & deep legacy scan, update NVRAM boot manager list
1857 if ((GlobalConfig
.LegacyType
== LEGACY_TYPE_UEFI
) && ScanForLegacy
&& GlobalConfig
.DeepLegacyScan
) {
1858 BdsDeleteAllInvalidLegacyBootOptions();
1859 BdsAddNonExistingLegacyBootOptions();
1862 // scan for loaders and tools, add them to the menu
1863 for (i
= 0; i
< NUM_SCAN_OPTIONS
; i
++) {
1864 switch(GlobalConfig
.ScanFor
[i
]) {
1869 ScanLegacyInternal();
1872 ScanLegacyExternal();
1875 ScanUserConfigured(GlobalConfig
.ConfigFilename
);
1892 // assign shortcut keys
1893 for (i
= 0; i
< MainMenu
.EntryCount
&& MainMenu
.Entries
[i
]->Row
== 0 && i
< 9; i
++)
1894 MainMenu
.Entries
[i
]->ShortcutDigit
= (CHAR16
)('1' + i
);
1896 // wait for user ACK when there were errors
1897 FinishTextScreen(FALSE
);
1898 } // static VOID ScanForBootloaders()
1900 // Locate a single tool from the specified Locations using one of the
1901 // specified Names and add it to the menu.
1902 static VOID
FindTool(CHAR16
*Locations
, CHAR16
*Names
, CHAR16
*Description
, UINTN Icon
) {
1903 UINTN j
= 0, k
, VolumeIndex
;
1904 CHAR16
*DirName
, *FileName
, *PathName
, FullDescription
[256];
1906 while ((DirName
= FindCommaDelimited(Locations
, j
++)) != NULL
) {
1908 while ((FileName
= FindCommaDelimited(Names
, k
++)) != NULL
) {
1909 PathName
= StrDuplicate(DirName
);
1910 MergeStrings(&PathName
, FileName
, MyStriCmp(PathName
, L
"\\") ? 0 : L
'\\');
1911 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
1912 if ((Volumes
[VolumeIndex
]->RootDir
!= NULL
) &&
1913 (FileExists(Volumes
[VolumeIndex
]->RootDir
, PathName
)) &&
1914 IsValidLoader(Volumes
[VolumeIndex
]->RootDir
, PathName
)) {
1915 SPrint(FullDescription
, 255, L
"%s at %s on %s", Description
, PathName
, Volumes
[VolumeIndex
]->VolName
);
1916 AddToolEntry(Volumes
[VolumeIndex
]->DeviceHandle
, PathName
, FullDescription
, BuiltinIcon(Icon
), 'S', FALSE
);
1919 MyFreePool(PathName
);
1920 MyFreePool(FileName
);
1922 MyFreePool(DirName
);
1923 } // while Locations
1924 } // VOID FindTool()
1926 // Add the second-row tags containing built-in and external tools (EFI shell,
1928 static VOID
ScanForTools(VOID
) {
1929 CHAR16
*FileName
= NULL
, *VolName
= NULL
, *MokLocations
, Description
[256];
1930 REFIT_MENU_ENTRY
*TempMenuEntry
;
1931 UINTN i
, j
, VolumeIndex
;
1936 MokLocations
= StrDuplicate(MOK_LOCATIONS
);
1937 if (MokLocations
!= NULL
)
1938 MergeStrings(&MokLocations
, SelfDirPath
, L
',');
1940 for (i
= 0; i
< NUM_TOOLS
; i
++) {
1941 switch(GlobalConfig
.ShowTools
[i
]) {
1942 // NOTE: Be sure that FileName is NULL at the end of each case.
1944 TempMenuEntry
= CopyMenuEntry(&MenuEntryShutdown
);
1945 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_SHUTDOWN
);
1946 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1950 TempMenuEntry
= CopyMenuEntry(&MenuEntryReset
);
1951 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_RESET
);
1952 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1956 TempMenuEntry
= CopyMenuEntry(&MenuEntryAbout
);
1957 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_ABOUT
);
1958 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1962 TempMenuEntry
= CopyMenuEntry(&MenuEntryExit
);
1963 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_EXIT
);
1964 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1968 if (EfivarGetRaw(&GlobalGuid
, L
"OsIndicationsSupported", &b
, &j
) == EFI_SUCCESS
) {
1970 if (osind
& EFI_OS_INDICATIONS_BOOT_TO_FW_UI
) {
1971 TempMenuEntry
= CopyMenuEntry(&MenuEntryFirmware
);
1972 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_FIRMWARE
);
1973 AddMenuEntry(&MainMenu
, TempMenuEntry
);
1980 while ((FileName
= FindCommaDelimited(SHELL_NAMES
, j
++)) != NULL
) {
1981 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1982 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"EFI Shell", BuiltinIcon(BUILTIN_ICON_TOOL_SHELL
),
1985 MyFreePool(FileName
);
1991 while ((FileName
= FindCommaDelimited(GPTSYNC_NAMES
, j
++)) != NULL
) {
1992 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
1993 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"Hybrid MBR tool", BuiltinIcon(BUILTIN_ICON_TOOL_PART
),
1996 MyFreePool(FileName
);
2003 while ((FileName
= FindCommaDelimited(GDISK_NAMES
, j
++)) != NULL
) {
2004 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
2005 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"disk partitioning tool",
2006 BuiltinIcon(BUILTIN_ICON_TOOL_PART
), 'G', FALSE
);
2008 MyFreePool(FileName
);
2015 while ((FileName
= FindCommaDelimited(NETBOOT_NAMES
, j
++)) != NULL
) {
2016 if (FileExists(SelfRootDir
, FileName
) && IsValidLoader(SelfRootDir
, FileName
)) {
2017 AddToolEntry(SelfLoadedImage
->DeviceHandle
, FileName
, L
"Netboot",
2018 BuiltinIcon(BUILTIN_ICON_TOOL_NETBOOT
), 'N', FALSE
);
2020 MyFreePool(FileName
);
2025 case TAG_APPLE_RECOVERY
:
2026 FileName
= StrDuplicate(L
"\\com.apple.recovery.boot\\boot.efi");
2027 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
2028 if ((Volumes
[VolumeIndex
]->RootDir
!= NULL
) &&
2029 (FileExists(Volumes
[VolumeIndex
]->RootDir
, FileName
)) &&
2030 IsValidLoader(Volumes
[VolumeIndex
]->RootDir
, FileName
)) {
2031 SPrint(Description
, 255, L
"Apple Recovery on %s", Volumes
[VolumeIndex
]->VolName
);
2032 AddToolEntry(Volumes
[VolumeIndex
]->DeviceHandle
, FileName
, Description
,
2033 BuiltinIcon(BUILTIN_ICON_TOOL_APPLE_RESCUE
), 'R', TRUE
);
2036 MyFreePool(FileName
);
2040 case TAG_WINDOWS_RECOVERY
:
2042 while ((FileName
= FindCommaDelimited(GlobalConfig
.WindowsRecoveryFiles
, j
++)) != NULL
) {
2043 SplitVolumeAndFilename(&FileName
, &VolName
);
2044 for (VolumeIndex
= 0; VolumeIndex
< VolumesCount
; VolumeIndex
++) {
2045 if ((Volumes
[VolumeIndex
]->RootDir
!= NULL
) &&
2046 (FileExists(Volumes
[VolumeIndex
]->RootDir
, FileName
)) &&
2047 IsValidLoader(Volumes
[VolumeIndex
]->RootDir
, FileName
) &&
2048 ((VolName
== NULL
) || MyStriCmp(VolName
, Volumes
[VolumeIndex
]->VolName
))) {
2049 SPrint(Description
, 255, L
"Microsoft Recovery on %s", Volumes
[VolumeIndex
]->VolName
);
2050 AddToolEntry(Volumes
[VolumeIndex
]->DeviceHandle
, FileName
, Description
,
2051 BuiltinIcon(BUILTIN_ICON_TOOL_WINDOWS_RESCUE
), 'R', TRUE
);
2055 MyFreePool(FileName
);
2057 MyFreePool(VolName
);
2062 FindTool(MokLocations
, MOK_NAMES
, L
"MOK utility", BUILTIN_ICON_TOOL_MOK_TOOL
);
2065 case TAG_CSR_ROTATE
:
2066 if ((GetCsrStatus(&CsrValue
) == EFI_SUCCESS
) && (GlobalConfig
.CsrValues
)) {
2067 TempMenuEntry
= CopyMenuEntry(&MenuEntryRotateCsr
);
2068 TempMenuEntry
->Image
= BuiltinIcon(BUILTIN_ICON_FUNC_CSR_ROTATE
);
2069 AddMenuEntry(&MainMenu
, TempMenuEntry
);
2074 FindTool(MEMTEST_LOCATIONS
, MEMTEST_NAMES
, L
"Memory test utility", BUILTIN_ICON_TOOL_MEMTEST
);
2079 } // static VOID ScanForTools
2081 // Rescan for boot loaders
2082 static VOID
RescanAll(BOOLEAN DisplayMessage
) {
2090 egDisplayMessage(L
"Scanning for new boot loaders; please wait....", &BGColor
);
2091 FreeList((VOID
***) &(MainMenu
.Entries
), &MainMenu
.EntryCount
);
2092 MainMenu
.Entries
= NULL
;
2093 MainMenu
.EntryCount
= 0;
2094 ConnectAllDriversToAllControllers();
2096 ReadConfig(GlobalConfig
.ConfigFilename
);
2097 ScanForBootloaders();
2100 } // VOID RescanAll()
2102 #ifdef __MAKEWITH_TIANO
2104 // Minimal initialization function
2105 static VOID
InitializeLib(IN EFI_HANDLE ImageHandle
, IN EFI_SYSTEM_TABLE
*SystemTable
) {
2107 // gImageHandle = ImageHandle;
2108 gBS
= SystemTable
->BootServices
;
2109 // gRS = SystemTable->RuntimeServices;
2110 gRT
= SystemTable
->RuntimeServices
; // Some BDS functions need gRT to be set
2111 EfiGetSystemConfigurationTable (&gEfiDxeServicesTableGuid
, (VOID
**) &gDS
);
2116 // Set up our own Secure Boot extensions....
2117 // Returns TRUE on success, FALSE otherwise
2118 static BOOLEAN
SecureBootSetup(VOID
) {
2120 BOOLEAN Success
= FALSE
;
2122 if (secure_mode() && ShimLoaded()) {
2123 Status
= security_policy_install();
2124 if (Status
== EFI_SUCCESS
) {
2127 Print(L
"Failed to install MOK Secure Boot extensions");
2132 } // VOID SecureBootSetup()
2134 // Remove our own Secure Boot extensions....
2135 // Returns TRUE on success, FALSE otherwise
2136 static BOOLEAN
SecureBootUninstall(VOID
) {
2138 BOOLEAN Success
= TRUE
;
2140 if (secure_mode()) {
2141 Status
= security_policy_uninstall();
2142 if (Status
!= EFI_SUCCESS
) {
2144 BeginTextScreen(L
"Secure Boot Policy Failure");
2145 Print(L
"Failed to uninstall MOK Secure Boot extensions; forcing a reboot.");
2147 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);
2151 } // VOID SecureBootUninstall
2153 // Sets the global configuration filename; will be CONFIG_FILE_NAME unless the
2154 // "-c" command-line option is set, in which case that takes precedence.
2155 // If an error is encountered, leaves the value alone (it should be set to
2156 // CONFIG_FILE_NAME when GlobalConfig is initialized).
2157 static VOID
SetConfigFilename(EFI_HANDLE ImageHandle
) {
2158 EFI_LOADED_IMAGE
*Info
;
2159 CHAR16
*Options
, *FileName
, *SubString
;
2162 Status
= refit_call3_wrapper(BS
->HandleProtocol
, ImageHandle
, &LoadedImageProtocol
, (VOID
**) &Info
);
2163 if ((Status
== EFI_SUCCESS
) && (Info
->LoadOptionsSize
> 0)) {
2164 Options
= (CHAR16
*) Info
->LoadOptions
;
2165 SubString
= MyStrStr(Options
, L
" -c ");
2167 FileName
= StrDuplicate(&SubString
[4]);
2169 LimitStringLength(FileName
, 256);
2172 if (FileExists(SelfDir
, FileName
)) {
2173 GlobalConfig
.ConfigFilename
= FileName
;
2175 Print(L
"Specified configuration file (%s) doesn't exist; using\n'refind.conf' default\n", FileName
);
2176 MyFreePool(FileName
);
2180 } // VOID SetConfigFilename()
2187 efi_main (EFI_HANDLE ImageHandle
, EFI_SYSTEM_TABLE
*SystemTable
)
2190 BOOLEAN MainLoopRunning
= TRUE
;
2191 BOOLEAN MokProtocol
;
2192 REFIT_MENU_ENTRY
*ChosenEntry
;
2194 CHAR16
*SelectionName
= NULL
;
2198 InitializeLib(ImageHandle
, SystemTable
);
2199 Status
= InitRefitLib(ImageHandle
);
2200 if (EFI_ERROR(Status
))
2203 // read configuration
2204 CopyMem(GlobalConfig
.ScanFor
, "ieom ", NUM_SCAN_OPTIONS
);
2205 FindLegacyBootType();
2206 if (GlobalConfig
.LegacyType
== LEGACY_TYPE_MAC
)
2207 CopyMem(GlobalConfig
.ScanFor
, "ihebocm ", NUM_SCAN_OPTIONS
);
2208 SetConfigFilename(ImageHandle
);
2209 MokProtocol
= SecureBootSetup();
2211 ScanVolumes(); // Do before ReadConfig() because it needs SelfVolume->VolName
2212 ReadConfig(GlobalConfig
.ConfigFilename
);
2214 if (GlobalConfig
.SpoofOSXVersion
&& GlobalConfig
.SpoofOSXVersion
[0] != L
'\0')
2218 WarnIfLegacyProblems();
2219 MainMenu
.TimeoutSeconds
= GlobalConfig
.Timeout
;
2221 // disable EFI watchdog timer
2222 refit_call4_wrapper(BS
->SetWatchdogTimer
, 0x0000, 0x0000, 0x0000, NULL
);
2224 // further bootstrap (now with config available)
2225 ScanForBootloaders();
2229 if (GlobalConfig
.ScanDelay
> 0) {
2234 if (GlobalConfig
.ScanDelay
> 1)
2235 egDisplayMessage(L
"Pausing before disk scan; please wait....", &BGColor
);
2236 for (i
= 0; i
< GlobalConfig
.ScanDelay
; i
++)
2237 refit_call1_wrapper(BS
->Stall
, 1000000);
2238 RescanAll(GlobalConfig
.ScanDelay
> 1);
2241 if (GlobalConfig
.DefaultSelection
)
2242 SelectionName
= StrDuplicate(GlobalConfig
.DefaultSelection
);
2244 while (MainLoopRunning
) {
2245 MenuExit
= RunMainMenu(&MainMenu
, &SelectionName
, &ChosenEntry
);
2247 // The Escape key triggers a re-scan operation....
2248 if (MenuExit
== MENU_EXIT_ESCAPE
) {
2254 switch (ChosenEntry
->Tag
) {
2256 case TAG_REBOOT
: // Reboot
2258 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);
2259 MainLoopRunning
= FALSE
; // just in case we get this far
2262 case TAG_SHUTDOWN
: // Shut Down
2264 refit_call4_wrapper(RT
->ResetSystem
, EfiResetShutdown
, EFI_SUCCESS
, 0, NULL
);
2265 MainLoopRunning
= FALSE
; // just in case we get this far
2268 case TAG_ABOUT
: // About rEFInd
2272 case TAG_LOADER
: // Boot OS via .EFI loader
2273 StartLoader((LOADER_ENTRY
*)ChosenEntry
, SelectionName
);
2276 case TAG_LEGACY
: // Boot legacy OS
2277 StartLegacy((LEGACY_ENTRY
*)ChosenEntry
, SelectionName
);
2280 case TAG_LEGACY_UEFI
: // Boot a legacy OS on a non-Mac
2281 StartLegacyUEFI((LEGACY_ENTRY
*)ChosenEntry
, SelectionName
);
2284 case TAG_TOOL
: // Start a EFI tool
2285 StartTool((LOADER_ENTRY
*)ChosenEntry
);
2288 case TAG_EXIT
: // Terminate rEFInd
2289 if ((MokProtocol
) && !SecureBootUninstall()) {
2290 MainLoopRunning
= FALSE
; // just in case we get this far
2292 BeginTextScreen(L
" ");
2297 case TAG_FIRMWARE
: // Reboot into firmware's user interface
2298 RebootIntoFirmware();
2301 case TAG_CSR_ROTATE
:
2308 // If we end up here, things have gone wrong. Try to reboot, and if that
2309 // fails, go into an endless loop.
2310 refit_call4_wrapper(RT
->ResetSystem
, EfiResetCold
, EFI_SUCCESS
, 0, NULL
);