]> code.delx.au - refind/blob - refind/lib.c
Protection against loading invalid EFI drivers; bug fix for using
[refind] / refind / lib.c
1 /*
2 * refit/lib.c
3 * General library functions
4 *
5 * Copyright (c) 2006-2009 Christoph Pfisterer
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * * Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the
18 * distribution.
19 *
20 * * Neither the name of Christoph Pfisterer nor the names of the
21 * contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 */
36 /*
37 * Modifications copyright (c) 2012-2013 Roderick W. Smith
38 *
39 * Modifications distributed under the terms of the GNU General Public
40 * License (GPL) version 3 (GPLv3), a copy of which must be distributed
41 * with this source code or binaries made from it.
42 *
43 */
44
45 #include "global.h"
46 #include "lib.h"
47 #include "icns.h"
48 #include "screen.h"
49 #include "../include/refit_call_wrapper.h"
50 #include "../include/RemovableMedia.h"
51 //#include "../include/UsbMass.h"
52
53 #ifdef __MAKEWITH_GNUEFI
54 #define EfiReallocatePool ReallocatePool
55 #else
56 #define LibLocateHandle gBS->LocateHandleBuffer
57 #define DevicePathProtocol gEfiDevicePathProtocolGuid
58 #define BlockIoProtocol gEfiBlockIoProtocolGuid
59 #define LibFileSystemInfo EfiLibFileSystemInfo
60 #define LibOpenRoot EfiLibOpenRoot
61 EFI_DEVICE_PATH EndDevicePath[] = {
62 {END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, {END_DEVICE_PATH_LENGTH, 0}}
63 };
64
65 //#define EndDevicePath DevicePath
66 #endif
67
68 // "Magic" signatures for various filesystems
69 #define FAT_MAGIC 0xAA55
70 #define EXT2_SUPER_MAGIC 0xEF53
71 #define HFSPLUS_MAGIC1 0x2B48
72 #define HFSPLUS_MAGIC2 0x5848
73 #define REISERFS_SUPER_MAGIC_STRING "ReIsErFs"
74 #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs"
75 #define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs"
76 #define BTRFS_SIGNATURE "_BHRfS_M"
77
78 // variables
79
80 EFI_HANDLE SelfImageHandle;
81 EFI_LOADED_IMAGE *SelfLoadedImage;
82 EFI_FILE *SelfRootDir;
83 EFI_FILE *SelfDir;
84 CHAR16 *SelfDirPath;
85
86 REFIT_VOLUME *SelfVolume = NULL;
87 REFIT_VOLUME **Volumes = NULL;
88 UINTN VolumesCount = 0;
89
90 // Maximum size for disk sectors
91 #define SECTOR_SIZE 4096
92
93 // Number of bytes to read from a partition to determine its filesystem type
94 // and identify its boot loader, and hence probable BIOS-mode OS installation
95 #define SAMPLE_SIZE 69632 /* 68 KiB -- ReiserFS superblock begins at 64 KiB */
96
97
98 // functions
99
100 static EFI_STATUS FinishInitRefitLib(VOID);
101
102 static VOID UninitVolumes(VOID);
103
104 //
105 // self recognition stuff
106 //
107
108 // Converts forward slashes to backslashes, removes duplicate slashes, and
109 // removes slashes from both the start and end of the pathname.
110 // Necessary because some (buggy?) EFI implementations produce "\/" strings
111 // in pathnames, because some user inputs can produce duplicate directory
112 // separators, and because we want consistent start and end slashes for
113 // directory comparisons. A special case: If the PathName refers to root,
114 // return "/", since some firmware implementations flake out if this
115 // isn't present.
116 VOID CleanUpPathNameSlashes(IN OUT CHAR16 *PathName) {
117 CHAR16 *NewName;
118 UINTN i, Length, FinalChar = 0;
119 BOOLEAN LastWasSlash = FALSE;
120
121 Length = StrLen(PathName);
122 NewName = AllocateZeroPool(sizeof(CHAR16) * (Length + 2));
123 if (NewName != NULL) {
124 for (i = 0; i < StrLen(PathName); i++) {
125 if ((PathName[i] == L'/') || (PathName[i] == L'\\')) {
126 if ((!LastWasSlash) && (FinalChar != 0))
127 NewName[FinalChar++] = L'\\';
128 LastWasSlash = TRUE;
129 } else {
130 NewName[FinalChar++] = PathName[i];
131 LastWasSlash = FALSE;
132 } // if/else
133 } // for
134 NewName[FinalChar] = 0;
135 if ((FinalChar > 0) && (NewName[FinalChar - 1] == L'\\'))
136 NewName[--FinalChar] = 0;
137 if (FinalChar == 0) {
138 NewName[0] = L'\\';
139 NewName[1] = 0;
140 }
141 // Copy the transformed name back....
142 StrCpy(PathName, NewName);
143 FreePool(NewName);
144 } // if allocation OK
145 } // CleanUpPathNameSlashes()
146
147 // Splits an EFI device path into device and filename components. For instance, if InString is
148 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)/\bzImage-3.5.1.efi,
149 // this function will truncate that input to
150 // PciRoot(0x0)/Pci(0x1f,0x2)/Ata(Secondary,Master,0x0)/HD(2,GPT,8314ae90-ada3-48e9-9c3b-09a88f80d921,0x96028,0xfa000)
151 // and return bzImage-3.5.1.efi as its return value.
152 // It does this by searching for the last ")" character in InString, copying everything
153 // after that string (after some cleanup) as the return value, and truncating the original
154 // input value.
155 // If InString contains no ")" character, this function leaves the original input string
156 // unmodified and also returns that string. If InString is NULL, this function returns NULL.
157 static CHAR16* SplitDeviceString(IN OUT CHAR16 *InString) {
158 INTN i;
159 CHAR16 *FileName = NULL;
160 BOOLEAN Found = FALSE;
161
162 if (InString != NULL) {
163 i = StrLen(InString) - 1;
164 while ((i >= 0) && (!Found)) {
165 if (InString[i] == L')') {
166 Found = TRUE;
167 FileName = StrDuplicate(&InString[i + 1]);
168 CleanUpPathNameSlashes(FileName);
169 InString[i + 1] = '\0';
170 } // if
171 i--;
172 } // while
173 if (FileName == NULL)
174 FileName = StrDuplicate(InString);
175 } // if
176 return FileName;
177 } // static CHAR16* SplitDeviceString()
178
179 EFI_STATUS InitRefitLib(IN EFI_HANDLE ImageHandle)
180 {
181 EFI_STATUS Status;
182 CHAR16 *DevicePathAsString, *Temp;
183
184 SelfImageHandle = ImageHandle;
185 Status = refit_call3_wrapper(BS->HandleProtocol, SelfImageHandle, &LoadedImageProtocol, (VOID **) &SelfLoadedImage);
186 if (CheckFatalError(Status, L"while getting a LoadedImageProtocol handle"))
187 return EFI_LOAD_ERROR;
188
189 // find the current directory
190 DevicePathAsString = DevicePathToStr(SelfLoadedImage->FilePath);
191 CleanUpPathNameSlashes(DevicePathAsString);
192 MyFreePool(SelfDirPath);
193 Temp = FindPath(DevicePathAsString);
194 SelfDirPath = SplitDeviceString(Temp);
195 MyFreePool(DevicePathAsString);
196 MyFreePool(Temp);
197
198 return FinishInitRefitLib();
199 }
200
201 // called before running external programs to close open file handles
202 VOID UninitRefitLib(VOID)
203 {
204 UninitVolumes();
205
206 if (SelfDir != NULL) {
207 refit_call1_wrapper(SelfDir->Close, SelfDir);
208 SelfDir = NULL;
209 }
210
211 if (SelfRootDir != NULL) {
212 refit_call1_wrapper(SelfRootDir->Close, SelfRootDir);
213 SelfRootDir = NULL;
214 }
215 }
216
217 // called after running external programs to re-open file handles
218 EFI_STATUS ReinitRefitLib(VOID)
219 {
220 ReinitVolumes();
221
222 if ((ST->Hdr.Revision >> 16) == 1) {
223 // Below two lines were in rEFIt, but seem to cause system crashes or
224 // reboots when launching OSes after returning from programs on most
225 // systems. OTOH, my Mac Mini produces errors about "(re)opening our
226 // installation volume" (see the next function) when returning from
227 // programs when these two lines are removed, and it often crashes
228 // when returning from a program or when launching a second program
229 // with these lines removed. Therefore, the preceding if() statement
230 // executes these lines only on EFIs with a major version number of 1
231 // (which Macs have) and not with 2 (which UEFI PCs have). My selection
232 // of hardware on which to test is limited, though, so this may be the
233 // wrong test, or there may be a better way to fix this problem.
234 // TODO: Figure out cause of above weirdness and fix it more
235 // reliably!
236 if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
237 SelfRootDir = SelfVolume->RootDir;
238 } // if
239
240 return FinishInitRefitLib();
241 }
242
243 static EFI_STATUS FinishInitRefitLib(VOID)
244 {
245 EFI_STATUS Status;
246
247 if (SelfRootDir == NULL) {
248 SelfRootDir = LibOpenRoot(SelfLoadedImage->DeviceHandle);
249 if (SelfRootDir == NULL) {
250 CheckError(EFI_LOAD_ERROR, L"while (re)opening our installation volume");
251 return EFI_LOAD_ERROR;
252 }
253 }
254
255 Status = refit_call5_wrapper(SelfRootDir->Open, SelfRootDir, &SelfDir, SelfDirPath, EFI_FILE_MODE_READ, 0);
256 if (CheckFatalError(Status, L"while opening our installation directory"))
257 return EFI_LOAD_ERROR;
258
259 return EFI_SUCCESS;
260 }
261
262 //
263 // list functions
264 //
265
266 VOID CreateList(OUT VOID ***ListPtr, OUT UINTN *ElementCount, IN UINTN InitialElementCount)
267 {
268 UINTN AllocateCount;
269
270 *ElementCount = InitialElementCount;
271 if (*ElementCount > 0) {
272 AllocateCount = (*ElementCount + 7) & ~7; // next multiple of 8
273 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
274 } else {
275 *ListPtr = NULL;
276 }
277 }
278
279 VOID AddListElement(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount, IN VOID *NewElement)
280 {
281 UINTN AllocateCount;
282
283 if ((*ElementCount & 7) == 0) {
284 AllocateCount = *ElementCount + 8;
285 if (*ElementCount == 0)
286 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
287 else
288 *ListPtr = EfiReallocatePool(*ListPtr, sizeof(VOID *) * (*ElementCount), sizeof(VOID *) * AllocateCount);
289 }
290 (*ListPtr)[*ElementCount] = NewElement;
291 (*ElementCount)++;
292 } /* VOID AddListElement() */
293
294 VOID FreeList(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount)
295 {
296 UINTN i;
297
298 if ((*ElementCount > 0) && (**ListPtr != NULL)) {
299 for (i = 0; i < *ElementCount; i++) {
300 // TODO: call a user-provided routine for each element here
301 MyFreePool((*ListPtr)[i]);
302 }
303 MyFreePool(*ListPtr);
304 }
305 } // VOID FreeList()
306
307 //
308 // firmware device path discovery
309 //
310
311 static UINT8 LegacyLoaderMediaPathData[] = {
312 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
313 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
314 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
315 };
316 static EFI_DEVICE_PATH *LegacyLoaderMediaPath = (EFI_DEVICE_PATH *)LegacyLoaderMediaPathData;
317
318 VOID ExtractLegacyLoaderPaths(EFI_DEVICE_PATH **PathList, UINTN MaxPaths, EFI_DEVICE_PATH **HardcodedPathList)
319 {
320 EFI_STATUS Status;
321 UINTN HandleCount = 0;
322 UINTN HandleIndex, HardcodedIndex;
323 EFI_HANDLE *Handles;
324 EFI_HANDLE Handle;
325 UINTN PathCount = 0;
326 UINTN PathIndex;
327 EFI_LOADED_IMAGE *LoadedImage;
328 EFI_DEVICE_PATH *DevicePath;
329 BOOLEAN Seen;
330
331 MaxPaths--; // leave space for the terminating NULL pointer
332
333 // get all LoadedImage handles
334 Status = LibLocateHandle(ByProtocol, &LoadedImageProtocol, NULL, &HandleCount, &Handles);
335 if (CheckError(Status, L"while listing LoadedImage handles")) {
336 if (HardcodedPathList) {
337 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
338 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
339 }
340 PathList[PathCount] = NULL;
341 return;
342 }
343 for (HandleIndex = 0; HandleIndex < HandleCount && PathCount < MaxPaths; HandleIndex++) {
344 Handle = Handles[HandleIndex];
345
346 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &LoadedImageProtocol, (VOID **) &LoadedImage);
347 if (EFI_ERROR(Status))
348 continue; // This can only happen if the firmware scewed up, ignore it.
349
350 Status = refit_call3_wrapper(BS->HandleProtocol, LoadedImage->DeviceHandle, &DevicePathProtocol, (VOID **) &DevicePath);
351 if (EFI_ERROR(Status))
352 continue; // This happens, ignore it.
353
354 // Only grab memory range nodes
355 if (DevicePathType(DevicePath) != HARDWARE_DEVICE_PATH || DevicePathSubType(DevicePath) != HW_MEMMAP_DP)
356 continue;
357
358 // Check if we have this device path in the list already
359 // WARNING: This assumes the first node in the device path is unique!
360 Seen = FALSE;
361 for (PathIndex = 0; PathIndex < PathCount; PathIndex++) {
362 if (DevicePathNodeLength(DevicePath) != DevicePathNodeLength(PathList[PathIndex]))
363 continue;
364 if (CompareMem(DevicePath, PathList[PathIndex], DevicePathNodeLength(DevicePath)) == 0) {
365 Seen = TRUE;
366 break;
367 }
368 }
369 if (Seen)
370 continue;
371
372 PathList[PathCount++] = AppendDevicePath(DevicePath, LegacyLoaderMediaPath);
373 }
374 MyFreePool(Handles);
375
376 if (HardcodedPathList) {
377 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
378 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
379 }
380 PathList[PathCount] = NULL;
381 }
382
383 //
384 // volume functions
385 //
386
387 // Return a pointer to a string containing a filesystem type name. If the
388 // filesystem type is unknown, a blank (but non-null) string is returned.
389 // The returned variable is a constant that should NOT be freed.
390 static CHAR16 *FSTypeName(IN UINT32 TypeCode) {
391 CHAR16 *retval = NULL;
392
393 switch (TypeCode) {
394 case FS_TYPE_FAT:
395 retval = L" FAT";
396 break;
397 case FS_TYPE_HFSPLUS:
398 retval = L" HFS+";
399 break;
400 case FS_TYPE_EXT2:
401 retval = L" ext2";
402 break;
403 case FS_TYPE_EXT3:
404 retval = L" ext3";
405 break;
406 case FS_TYPE_EXT4:
407 retval = L" ext4";
408 break;
409 case FS_TYPE_REISERFS:
410 retval = L" ReiserFS";
411 break;
412 case FS_TYPE_BTRFS:
413 retval = L" Btrfs";
414 break;
415 case FS_TYPE_ISO9660:
416 retval = L" ISO-9660";
417 break;
418 default:
419 retval = L"";
420 break;
421 } // switch
422 return retval;
423 } // CHAR16 *FSTypeName()
424
425 // Identify the filesystem type, if possible. Expects a Buffer containing
426 // the first few (normally 4096) bytes of the filesystem, and outputs a
427 // code representing the identified filesystem type.
428 static UINT32 IdentifyFilesystemType(IN UINT8 *Buffer, IN UINTN BufferSize) {
429 UINT32 FoundType = FS_TYPE_UNKNOWN;
430 UINT32 *Ext2Incompat, *Ext2Compat;
431 UINT16 *Magic16;
432 char *MagicString;
433
434 if (Buffer != NULL) {
435
436 if (BufferSize >= 512) {
437 Magic16 = (UINT16*) (Buffer + 510);
438 if (*Magic16 == FAT_MAGIC)
439 return FS_TYPE_FAT;
440 } // search for FAT magic
441
442 if (BufferSize >= (1024 + 100)) {
443 Magic16 = (UINT16*) (Buffer + 1024 + 56);
444 if (*Magic16 == EXT2_SUPER_MAGIC) { // ext2/3/4
445 Ext2Compat = (UINT32*) (Buffer + 1024 + 92);
446 Ext2Incompat = (UINT32*) (Buffer + 1024 + 96);
447 if ((*Ext2Incompat & 0x0040) || (*Ext2Incompat & 0x0200)) { // check for extents or flex_bg
448 return FS_TYPE_EXT4;
449 } else if (*Ext2Compat & 0x0004) { // check for journal
450 return FS_TYPE_EXT3;
451 } else { // none of these features; presume it's ext2...
452 return FS_TYPE_EXT2;
453 }
454 }
455 } // search for ext2/3/4 magic
456
457 if (BufferSize >= (65536 + 62)) {
458 MagicString = (char*) (Buffer + 65536 + 52);
459 if ((CompareMem(MagicString, REISERFS_SUPER_MAGIC_STRING, 8) == 0) ||
460 (CompareMem(MagicString, REISER2FS_SUPER_MAGIC_STRING, 9) == 0) ||
461 (CompareMem(MagicString, REISER2FS_JR_SUPER_MAGIC_STRING, 9) == 0)) {
462 return FS_TYPE_REISERFS;
463 } // if
464 } // search for ReiserFS magic
465
466 if (BufferSize >= (65536 + 64 + 8)) {
467 MagicString = (char*) (Buffer + 65536 + 64);
468 if (CompareMem(MagicString, BTRFS_SIGNATURE, 8) == 0)
469 return FS_TYPE_BTRFS;
470 } // search for Btrfs magic
471
472 if (BufferSize >= (1024 + 2)) {
473 Magic16 = (UINT16*) (Buffer + 1024);
474 if ((*Magic16 == HFSPLUS_MAGIC1) || (*Magic16 == HFSPLUS_MAGIC2)) {
475 return FS_TYPE_HFSPLUS;
476 }
477 } // search for HFS+ magic
478 } // if (Buffer != NULL)
479
480 return FoundType;
481 } // UINT32 IdentifyFilesystemType()
482
483 static VOID ScanVolumeBootcode(REFIT_VOLUME *Volume, BOOLEAN *Bootable)
484 {
485 EFI_STATUS Status;
486 UINT8 Buffer[SAMPLE_SIZE];
487 UINTN i;
488 MBR_PARTITION_INFO *MbrTable;
489 BOOLEAN MbrTableFound;
490
491 Volume->HasBootCode = FALSE;
492 Volume->OSIconName = NULL;
493 Volume->OSName = NULL;
494 *Bootable = FALSE;
495
496 if (Volume->BlockIO == NULL)
497 return;
498 if (Volume->BlockIO->Media->BlockSize > SAMPLE_SIZE)
499 return; // our buffer is too small...
500
501 // look at the boot sector (this is used for both hard disks and El Torito images!)
502 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
503 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
504 Volume->BlockIOOffset, SAMPLE_SIZE, Buffer);
505 if (!EFI_ERROR(Status)) {
506
507 Volume->FSType = IdentifyFilesystemType(Buffer, SAMPLE_SIZE);
508 if (*((UINT16 *)(Buffer + 510)) == 0xaa55 && Buffer[0] != 0) {
509 *Bootable = TRUE;
510 Volume->HasBootCode = TRUE;
511 }
512
513 // detect specific boot codes
514 if (CompareMem(Buffer + 2, "LILO", 4) == 0 ||
515 CompareMem(Buffer + 6, "LILO", 4) == 0 ||
516 CompareMem(Buffer + 3, "SYSLINUX", 8) == 0 ||
517 FindMem(Buffer, SECTOR_SIZE, "ISOLINUX", 8) >= 0) {
518 Volume->HasBootCode = TRUE;
519 Volume->OSIconName = L"linux";
520 Volume->OSName = L"Linux";
521
522 } else if (FindMem(Buffer, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
523 Volume->HasBootCode = TRUE;
524 Volume->OSIconName = L"grub,linux";
525 Volume->OSName = L"Linux";
526
527 // // Below doesn't produce a bootable entry, so commented out for the moment....
528 // // GRUB in BIOS boot partition:
529 // } else if (FindMem(Buffer, 512, "Geom\0Read\0 Error", 16) >= 0) {
530 // Volume->HasBootCode = TRUE;
531 // Volume->OSIconName = L"grub,linux";
532 // Volume->OSName = L"Linux";
533 // Volume->VolName = L"BIOS Boot Partition";
534 // *Bootable = TRUE;
535
536 } else if ((*((UINT32 *)(Buffer + 502)) == 0 &&
537 *((UINT32 *)(Buffer + 506)) == 50000 &&
538 *((UINT16 *)(Buffer + 510)) == 0xaa55) ||
539 FindMem(Buffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
540 Volume->HasBootCode = TRUE;
541 Volume->OSIconName = L"freebsd";
542 Volume->OSName = L"FreeBSD";
543
544 } else if (FindMem(Buffer, 512, "!Loading", 8) >= 0 ||
545 FindMem(Buffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
546 Volume->HasBootCode = TRUE;
547 Volume->OSIconName = L"openbsd";
548 Volume->OSName = L"OpenBSD";
549
550 } else if (FindMem(Buffer, 512, "Not a bootxx image", 18) >= 0 ||
551 *((UINT32 *)(Buffer + 1028)) == 0x7886b6d1) {
552 Volume->HasBootCode = TRUE;
553 Volume->OSIconName = L"netbsd";
554 Volume->OSName = L"NetBSD";
555
556 } else if (FindMem(Buffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
557 Volume->HasBootCode = TRUE;
558 Volume->OSIconName = L"win";
559 Volume->OSName = L"Windows";
560
561 } else if (FindMem(Buffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
562 Volume->HasBootCode = TRUE;
563 Volume->OSIconName = L"winvista,win";
564 Volume->OSName = L"Windows";
565
566 } else if (FindMem(Buffer, 512, "CPUBOOT SYS", 11) >= 0 ||
567 FindMem(Buffer, 512, "KERNEL SYS", 11) >= 0) {
568 Volume->HasBootCode = TRUE;
569 Volume->OSIconName = L"freedos";
570 Volume->OSName = L"FreeDOS";
571
572 } else if (FindMem(Buffer, 512, "OS2LDR", 6) >= 0 ||
573 FindMem(Buffer, 512, "OS2BOOT", 7) >= 0) {
574 Volume->HasBootCode = TRUE;
575 Volume->OSIconName = L"ecomstation";
576 Volume->OSName = L"eComStation";
577
578 } else if (FindMem(Buffer, 512, "Be Boot Loader", 14) >= 0) {
579 Volume->HasBootCode = TRUE;
580 Volume->OSIconName = L"beos";
581 Volume->OSName = L"BeOS";
582
583 } else if (FindMem(Buffer, 512, "yT Boot Loader", 14) >= 0) {
584 Volume->HasBootCode = TRUE;
585 Volume->OSIconName = L"zeta,beos";
586 Volume->OSName = L"ZETA";
587
588 } else if (FindMem(Buffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
589 FindMem(Buffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
590 Volume->HasBootCode = TRUE;
591 Volume->OSIconName = L"haiku,beos";
592 Volume->OSName = L"Haiku";
593
594 }
595
596 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
597 // need to fix AddLegacyEntry in main.c.
598
599 #if REFIT_DEBUG > 0
600 Print(L" Result of bootcode detection: %s %s (%s)\n",
601 Volume->HasBootCode ? L"bootable" : L"non-bootable",
602 Volume->OSName, Volume->OSIconName);
603 #endif
604
605 // dummy FAT boot sector (created by OS X's newfs_msdos)
606 if (FindMem(Buffer, 512, "Non-system disk", 15) >= 0)
607 Volume->HasBootCode = FALSE;
608
609 // dummy FAT boot sector (created by Linux's mkdosfs)
610 if (FindMem(Buffer, 512, "This is not a bootable disk", 27) >= 0)
611 Volume->HasBootCode = FALSE;
612
613 // dummy FAT boot sector (created by Windows)
614 if (FindMem(Buffer, 512, "Press any key to restart", 24) >= 0)
615 Volume->HasBootCode = FALSE;
616
617 // check for MBR partition table
618 if (*((UINT16 *)(Buffer + 510)) == 0xaa55) {
619 MbrTableFound = FALSE;
620 MbrTable = (MBR_PARTITION_INFO *)(Buffer + 446);
621 for (i = 0; i < 4; i++)
622 if (MbrTable[i].StartLBA && MbrTable[i].Size)
623 MbrTableFound = TRUE;
624 for (i = 0; i < 4; i++)
625 if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
626 MbrTableFound = FALSE;
627 if (MbrTableFound) {
628 Volume->MbrPartitionTable = AllocatePool(4 * 16);
629 CopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
630 }
631 }
632
633 } else {
634 #if REFIT_DEBUG > 0
635 CheckError(Status, L"while reading boot sector");
636 #endif
637 }
638 } /* VOID ScanVolumeBootcode() */
639
640 // Set default volume badge icon based on /.VolumeBadge.{icns|png} file or disk kind
641 static VOID SetVolumeBadgeIcon(IN OUT REFIT_VOLUME *Volume)
642 {
643 if (Volume->VolBadgeImage == NULL) {
644 Volume->VolBadgeImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeBadge", 128);
645 }
646
647 if (Volume->VolBadgeImage == NULL) {
648 switch (Volume->DiskKind) {
649 case DISK_KIND_INTERNAL:
650 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
651 break;
652 case DISK_KIND_EXTERNAL:
653 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
654 break;
655 case DISK_KIND_OPTICAL:
656 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
657 break;
658 } // switch()
659 }
660 } // VOID SetVolumeBadgeIcon()
661
662 // Return a string representing the input size in IEEE-1541 units.
663 // The calling function is responsible for freeing the allocated memory.
664 static CHAR16 *SizeInIEEEUnits(UINT64 SizeInBytes) {
665 UINT64 SizeInIeee;
666 UINTN Index = 0, NumPrefixes;
667 CHAR16 *Units, *Prefixes = L" KMGTPEZ";
668 CHAR16 *TheValue;
669
670 TheValue = AllocateZeroPool(sizeof(CHAR16) * 256);
671 if (TheValue != NULL) {
672 NumPrefixes = StrLen(Prefixes);
673 SizeInIeee = SizeInBytes;
674 while ((SizeInIeee > 1024) && (Index < (NumPrefixes - 1))) {
675 Index++;
676 SizeInIeee /= 1024;
677 } // while
678 if (Prefixes[Index] == ' ') {
679 Units = StrDuplicate(L"-byte");
680 } else {
681 Units = StrDuplicate(L" iB");
682 Units[1] = Prefixes[Index];
683 } // if/else
684 SPrint(TheValue, 255, L"%ld%s", SizeInIeee, Units);
685 } // if
686 return TheValue;
687 } // CHAR16 *SizeInSIUnits()
688
689 // Return a name for the volume. Ideally this should be the label for the
690 // filesystem it contains, but this function falls back to describing the
691 // filesystem by size (200 MiB, etc.) and/or type (ext2, HFS+, etc.), if
692 // this information can be extracted.
693 // The calling function is responsible for freeing the memory allocated
694 // for the name string.
695 static CHAR16 *GetVolumeName(IN REFIT_VOLUME *Volume) {
696 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr;
697 CHAR16 *FoundName = NULL;
698 CHAR16 *SISize, *TypeName;
699
700 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
701 if (FileSystemInfoPtr != NULL) { // we have filesystem information (size, label)....
702 if ((FileSystemInfoPtr->VolumeLabel != NULL) && (StrLen(FileSystemInfoPtr->VolumeLabel) > 0)) {
703 FoundName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
704 }
705
706 // Special case: rEFInd HFS+ driver always returns label of "HFS+ volume", so wipe
707 // this so that we can build a new name that includes the size....
708 if ((FoundName != NULL) && (StrCmp(FoundName, L"HFS+ volume") == 0) && (Volume->FSType == FS_TYPE_HFSPLUS)) {
709 MyFreePool(FoundName);
710 FoundName = NULL;
711 } // if rEFInd HFS+ driver suspected
712
713 if (FoundName == NULL) { // filesystem has no name, so use fs type and size
714 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
715 if (FoundName != NULL) {
716 SISize = SizeInIEEEUnits(FileSystemInfoPtr->VolumeSize);
717 SPrint(FoundName, 255, L"%s%s volume", SISize, FSTypeName(Volume->FSType));
718 MyFreePool(SISize);
719 } // if allocated memory OK
720 } // if (FoundName == NULL)
721
722 FreePool(FileSystemInfoPtr);
723
724 } else { // fs driver not returning info; fall back on our own information....
725 FoundName = AllocateZeroPool(sizeof(CHAR16) * 256);
726 if (FoundName != NULL) {
727 TypeName = FSTypeName(Volume->FSType); // NOTE: Don't free TypeName; function returns constant
728 if (StrLen(TypeName) > 0)
729 SPrint(FoundName, 255, L"%s volume", FSTypeName(Volume->FSType));
730 else
731 SPrint(FoundName, 255, L"unknown volume");
732 } // if allocated memory OK
733 } // if
734
735 // TODO: Above could be improved/extended, in case filesystem name is not found,
736 // such as:
737 // - use partition label
738 // - use or add disk/partition number (e.g., "(hd0,2)")
739
740 // Desperate fallback name....
741 if (FoundName == NULL) {
742 FoundName = StrDuplicate(L"unknown volume");
743 }
744 return FoundName;
745 } // static CHAR16 *GetVolumeName()
746
747 VOID ScanVolume(REFIT_VOLUME *Volume)
748 {
749 EFI_STATUS Status;
750 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
751 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
752 EFI_HANDLE WholeDiskHandle;
753 UINTN PartialLength;
754 BOOLEAN Bootable;
755
756 // get device path
757 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
758 #if REFIT_DEBUG > 0
759 if (Volume->DevicePath != NULL) {
760 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
761 #if REFIT_DEBUG >= 2
762 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
763 #endif
764 }
765 #endif
766
767 Volume->DiskKind = DISK_KIND_INTERNAL; // default
768
769 // get block i/o
770 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
771 if (EFI_ERROR(Status)) {
772 Volume->BlockIO = NULL;
773 Print(L"Warning: Can't get BlockIO protocol.\n");
774 } else {
775 if (Volume->BlockIO->Media->BlockSize == 2048)
776 Volume->DiskKind = DISK_KIND_OPTICAL;
777 }
778
779 // scan for bootcode and MBR table
780 Bootable = FALSE;
781 ScanVolumeBootcode(Volume, &Bootable);
782
783 // detect device type
784 DevicePath = Volume->DevicePath;
785 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
786 NextDevicePath = NextDevicePathNode(DevicePath);
787
788 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
789 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
790 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
791 DevicePathSubType(DevicePath) == MSG_1394_DP ||
792 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
793 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
794 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
795 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
796 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
797 Bootable = TRUE;
798 }
799
800 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
801 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
802 // TODO: also check for Boot Camp GUID
803 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
804 }
805
806 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
807 // make a device path for the whole device
808 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
809 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
810 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
811 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
812
813 // get the handle for that path
814 RemainingDevicePath = DiskDevicePath;
815 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
816 FreePool(DiskDevicePath);
817
818 if (!EFI_ERROR(Status)) {
819 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
820
821 // get the device path for later
822 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
823 if (!EFI_ERROR(Status)) {
824 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
825 }
826
827 // look at the BlockIO protocol
828 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
829 if (!EFI_ERROR(Status)) {
830
831 // check the media block size
832 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
833 Volume->DiskKind = DISK_KIND_OPTICAL;
834
835 } else {
836 Volume->WholeDiskBlockIO = NULL;
837 //CheckError(Status, L"from HandleProtocol");
838 }
839 } //else
840 // CheckError(Status, L"from LocateDevicePath");
841 }
842
843 DevicePath = NextDevicePath;
844 } // while
845
846 if (!Bootable) {
847 #if REFIT_DEBUG > 0
848 if (Volume->HasBootCode)
849 Print(L" Volume considered non-bootable, but boot code is present\n");
850 #endif
851 Volume->HasBootCode = FALSE;
852 }
853
854 // open the root directory of the volume
855 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
856 if (Volume->RootDir == NULL) {
857 Volume->IsReadable = FALSE;
858 return;
859 } else {
860 Volume->IsReadable = TRUE;
861 }
862
863 Volume->VolName = GetVolumeName(Volume);
864
865 // Set volume icon based on .VolumeBadge icon or disk kind
866 SetVolumeBadgeIcon(Volume);
867
868 // get custom volume icons if present
869 if (!Volume->VolIconImage)
870 Volume->VolIconImage = egLoadIconAnyType(Volume->RootDir, L"", L".VolumeIcon", 128);
871 } // ScanVolume()
872
873 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
874 {
875 EFI_STATUS Status;
876 REFIT_VOLUME *Volume;
877 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
878 UINTN i;
879 UINTN LogicalPartitionIndex = 4;
880 UINT8 SectorBuffer[512];
881 BOOLEAN Bootable;
882 MBR_PARTITION_INFO *EMbrTable;
883
884 ExtBase = MbrEntry->StartLBA;
885
886 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
887 // read current EMBR
888 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
889 WholeDiskVolume->BlockIO,
890 WholeDiskVolume->BlockIO->Media->MediaId,
891 ExtCurrent, 512, SectorBuffer);
892 if (EFI_ERROR(Status))
893 break;
894 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
895 break;
896 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
897
898 // scan logical partitions in this EMBR
899 NextExtCurrent = 0;
900 for (i = 0; i < 4; i++) {
901 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
902 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
903 break;
904 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
905 // set next ExtCurrent
906 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
907 break;
908 } else {
909
910 // found a logical partition
911 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
912 Volume->DiskKind = WholeDiskVolume->DiskKind;
913 Volume->IsMbrPartition = TRUE;
914 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
915 Volume->VolName = AllocateZeroPool(256 * sizeof(UINT16));
916 SPrint(Volume->VolName, 255, L"Partition %d", Volume->MbrPartitionIndex + 1);
917 Volume->BlockIO = WholeDiskVolume->BlockIO;
918 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
919 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
920
921 Bootable = FALSE;
922 ScanVolumeBootcode(Volume, &Bootable);
923 if (!Bootable)
924 Volume->HasBootCode = FALSE;
925
926 SetVolumeBadgeIcon(Volume);
927
928 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
929
930 }
931 }
932 }
933 } /* VOID ScanExtendedPartition() */
934
935 VOID ScanVolumes(VOID)
936 {
937 EFI_STATUS Status;
938 EFI_HANDLE *Handles;
939 REFIT_VOLUME *Volume, *WholeDiskVolume;
940 MBR_PARTITION_INFO *MbrTable;
941 UINTN HandleCount = 0;
942 UINTN HandleIndex;
943 UINTN VolumeIndex, VolumeIndex2;
944 UINTN PartitionIndex;
945 UINTN SectorSum, i, VolNumber = 0;
946 UINT8 *SectorBuffer1, *SectorBuffer2;
947
948 MyFreePool(Volumes);
949 Volumes = NULL;
950 VolumesCount = 0;
951
952 // get all filesystem handles
953 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
954 // was: &FileSystemProtocol
955 if (Status == EFI_NOT_FOUND) {
956 return; // no filesystems. strange, but true...
957 }
958 if (CheckError(Status, L"while listing all file systems"))
959 return;
960
961 // first pass: collect information about all handles
962 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
963 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
964 Volume->DeviceHandle = Handles[HandleIndex];
965 ScanVolume(Volume);
966 if (Volume->IsReadable)
967 Volume->VolNumber = VolNumber++;
968 else
969 Volume->VolNumber = VOL_UNREADABLE;
970
971 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
972
973 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
974 SelfVolume = Volume;
975 }
976 MyFreePool(Handles);
977
978 if (SelfVolume == NULL)
979 Print(L"WARNING: SelfVolume not found");
980
981 // second pass: relate partitions and whole disk devices
982 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
983 Volume = Volumes[VolumeIndex];
984 // check MBR partition table for extended partitions
985 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
986 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
987 Volume->MbrPartitionTable != NULL) {
988 MbrTable = Volume->MbrPartitionTable;
989 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
990 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
991 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
992 }
993 }
994 }
995
996 // search for corresponding whole disk volume entry
997 WholeDiskVolume = NULL;
998 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
999 Volume->BlockIO != Volume->WholeDiskBlockIO) {
1000 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
1001 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
1002 Volumes[VolumeIndex2]->BlockIOOffset == 0)
1003 WholeDiskVolume = Volumes[VolumeIndex2];
1004 }
1005 }
1006
1007 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
1008 // check if this volume is one of the partitions in the table
1009 MbrTable = WholeDiskVolume->MbrPartitionTable;
1010 SectorBuffer1 = AllocatePool(512);
1011 SectorBuffer2 = AllocatePool(512);
1012 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
1013 // check size
1014 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
1015 continue;
1016
1017 // compare boot sector read through offset vs. directly
1018 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
1019 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
1020 Volume->BlockIOOffset, 512, SectorBuffer1);
1021 if (EFI_ERROR(Status))
1022 break;
1023 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
1024 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
1025 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
1026 if (EFI_ERROR(Status))
1027 break;
1028 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
1029 continue;
1030 SectorSum = 0;
1031 for (i = 0; i < 512; i++)
1032 SectorSum += SectorBuffer1[i];
1033 if (SectorSum < 1000)
1034 continue;
1035
1036 // TODO: mark entry as non-bootable if it is an extended partition
1037
1038 // now we're reasonably sure the association is correct...
1039 Volume->IsMbrPartition = TRUE;
1040 Volume->MbrPartitionIndex = PartitionIndex;
1041 if (Volume->VolName == NULL) {
1042 Volume->VolName = AllocateZeroPool(sizeof(CHAR16) * 256);
1043 SPrint(Volume->VolName, 255, L"Partition %d", PartitionIndex + 1);
1044 }
1045 break;
1046 }
1047
1048 MyFreePool(SectorBuffer1);
1049 MyFreePool(SectorBuffer2);
1050 }
1051
1052 } // for
1053 } /* VOID ScanVolumes() */
1054
1055 static VOID UninitVolumes(VOID)
1056 {
1057 REFIT_VOLUME *Volume;
1058 UINTN VolumeIndex;
1059
1060 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1061 Volume = Volumes[VolumeIndex];
1062
1063 if (Volume->RootDir != NULL) {
1064 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
1065 Volume->RootDir = NULL;
1066 }
1067
1068 Volume->DeviceHandle = NULL;
1069 Volume->BlockIO = NULL;
1070 Volume->WholeDiskBlockIO = NULL;
1071 }
1072 }
1073
1074 VOID ReinitVolumes(VOID)
1075 {
1076 EFI_STATUS Status;
1077 REFIT_VOLUME *Volume;
1078 UINTN VolumeIndex;
1079 EFI_DEVICE_PATH *RemainingDevicePath;
1080 EFI_HANDLE DeviceHandle, WholeDiskHandle;
1081
1082 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
1083 Volume = Volumes[VolumeIndex];
1084
1085 if (Volume->DevicePath != NULL) {
1086 // get the handle for that path
1087 RemainingDevicePath = Volume->DevicePath;
1088 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
1089
1090 if (!EFI_ERROR(Status)) {
1091 Volume->DeviceHandle = DeviceHandle;
1092
1093 // get the root directory
1094 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
1095
1096 } else
1097 CheckError(Status, L"from LocateDevicePath");
1098 }
1099
1100 if (Volume->WholeDiskDevicePath != NULL) {
1101 // get the handle for that path
1102 RemainingDevicePath = Volume->WholeDiskDevicePath;
1103 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
1104
1105 if (!EFI_ERROR(Status)) {
1106 // get the BlockIO protocol
1107 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
1108 if (EFI_ERROR(Status)) {
1109 Volume->WholeDiskBlockIO = NULL;
1110 CheckError(Status, L"from HandleProtocol");
1111 }
1112 } else
1113 CheckError(Status, L"from LocateDevicePath");
1114 }
1115 }
1116 }
1117
1118 //
1119 // file and dir functions
1120 //
1121
1122 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
1123 {
1124 EFI_STATUS Status;
1125 EFI_FILE_HANDLE TestFile;
1126
1127 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
1128 if (Status == EFI_SUCCESS) {
1129 refit_call1_wrapper(TestFile->Close, TestFile);
1130 return TRUE;
1131 }
1132 return FALSE;
1133 }
1134
1135 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
1136 {
1137 EFI_STATUS Status;
1138 VOID *Buffer;
1139 UINTN LastBufferSize, BufferSize;
1140 INTN IterCount;
1141
1142 for (;;) {
1143
1144 // free pointer from last call
1145 if (*DirEntry != NULL) {
1146 FreePool(*DirEntry);
1147 *DirEntry = NULL;
1148 }
1149
1150 // read next directory entry
1151 LastBufferSize = BufferSize = 256;
1152 Buffer = AllocatePool(BufferSize);
1153 for (IterCount = 0; ; IterCount++) {
1154 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
1155 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
1156 break;
1157 if (BufferSize <= LastBufferSize) {
1158 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
1159 BufferSize = LastBufferSize * 2;
1160 #if REFIT_DEBUG > 0
1161 } else {
1162 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
1163 #endif
1164 }
1165 Buffer = EfiReallocatePool(Buffer, LastBufferSize, BufferSize);
1166 LastBufferSize = BufferSize;
1167 }
1168 if (EFI_ERROR(Status)) {
1169 MyFreePool(Buffer);
1170 Buffer = NULL;
1171 break;
1172 }
1173
1174 // check for end of listing
1175 if (BufferSize == 0) { // end of directory listing
1176 MyFreePool(Buffer);
1177 Buffer = NULL;
1178 break;
1179 }
1180
1181 // entry is ready to be returned
1182 *DirEntry = (EFI_FILE_INFO *)Buffer;
1183
1184 // filter results
1185 if (FilterMode == 1) { // only return directories
1186 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
1187 break;
1188 } else if (FilterMode == 2) { // only return files
1189 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
1190 break;
1191 } else // no filter or unknown filter -> return everything
1192 break;
1193
1194 }
1195 return Status;
1196 }
1197
1198 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
1199 {
1200 if (RelativePath == NULL) {
1201 DirIter->LastStatus = EFI_SUCCESS;
1202 DirIter->DirHandle = BaseDir;
1203 DirIter->CloseDirHandle = FALSE;
1204 } else {
1205 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
1206 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
1207 }
1208 DirIter->LastFileInfo = NULL;
1209 }
1210
1211 #ifndef __MAKEWITH_GNUEFI
1212 EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL;
1213
1214 static EFI_STATUS
1215 InitializeUnicodeCollationProtocol (VOID)
1216 {
1217 EFI_STATUS Status;
1218
1219 if (mUnicodeCollation != NULL) {
1220 return EFI_SUCCESS;
1221 }
1222
1223 //
1224 // BUGBUG: Proper impelmentation is to locate all Unicode Collation Protocol
1225 // instances first and then select one which support English language.
1226 // Current implementation just pick the first instance.
1227 //
1228 Status = gBS->LocateProtocol (
1229 &gEfiUnicodeCollation2ProtocolGuid,
1230 NULL,
1231 (VOID **) &mUnicodeCollation
1232 );
1233 if (EFI_ERROR(Status)) {
1234 Status = gBS->LocateProtocol (
1235 &gEfiUnicodeCollationProtocolGuid,
1236 NULL,
1237 (VOID **) &mUnicodeCollation
1238 );
1239
1240 }
1241 return Status;
1242 }
1243
1244 static BOOLEAN
1245 MetaiMatch (IN CHAR16 *String, IN CHAR16 *Pattern)
1246 {
1247 if (!mUnicodeCollation) {
1248 InitializeUnicodeCollationProtocol();
1249 }
1250 if (mUnicodeCollation)
1251 return mUnicodeCollation->MetaiMatch (mUnicodeCollation, String, Pattern);
1252 return FALSE; // Shouldn't happen
1253 }
1254
1255 static VOID StrLwr (IN OUT CHAR16 *Str) {
1256 if (!mUnicodeCollation) {
1257 InitializeUnicodeCollationProtocol();
1258 }
1259 if (mUnicodeCollation)
1260 mUnicodeCollation->StrLwr (mUnicodeCollation, Str);
1261 }
1262
1263 #endif
1264
1265 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
1266 OUT EFI_FILE_INFO **DirEntry)
1267 {
1268 BOOLEAN KeepGoing = TRUE;
1269 UINTN i;
1270 CHAR16 *OnePattern;
1271
1272 if (DirIter->LastFileInfo != NULL) {
1273 FreePool(DirIter->LastFileInfo);
1274 DirIter->LastFileInfo = NULL;
1275 }
1276
1277 if (EFI_ERROR(DirIter->LastStatus))
1278 return FALSE; // stop iteration
1279
1280 do {
1281 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
1282 if (EFI_ERROR(DirIter->LastStatus))
1283 return FALSE;
1284 if (DirIter->LastFileInfo == NULL) // end of listing
1285 return FALSE;
1286 if (FilePattern != NULL) {
1287 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
1288 KeepGoing = FALSE;
1289 i = 0;
1290 while (KeepGoing && (OnePattern = FindCommaDelimited(FilePattern, i++)) != NULL) {
1291 if (MetaiMatch(DirIter->LastFileInfo->FileName, OnePattern))
1292 KeepGoing = FALSE;
1293 } // while
1294 // else continue loop
1295 } else
1296 break;
1297 } while (KeepGoing && FilePattern);
1298
1299 *DirEntry = DirIter->LastFileInfo;
1300 return TRUE;
1301 }
1302
1303 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
1304 {
1305 if (DirIter->LastFileInfo != NULL) {
1306 FreePool(DirIter->LastFileInfo);
1307 DirIter->LastFileInfo = NULL;
1308 }
1309 if (DirIter->CloseDirHandle)
1310 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
1311 return DirIter->LastStatus;
1312 }
1313
1314 //
1315 // file name manipulation
1316 //
1317
1318 // Returns the filename portion (minus path name) of the
1319 // specified file
1320 CHAR16 * Basename(IN CHAR16 *Path)
1321 {
1322 CHAR16 *FileName;
1323 UINTN i;
1324
1325 FileName = Path;
1326
1327 if (Path != NULL) {
1328 for (i = StrLen(Path); i > 0; i--) {
1329 if (Path[i-1] == '\\' || Path[i-1] == '/') {
1330 FileName = Path + i;
1331 break;
1332 }
1333 }
1334 }
1335
1336 return FileName;
1337 }
1338
1339 // Remove the .efi extension from FileName -- for instance, if FileName is
1340 // "fred.efi", returns "fred". If the filename contains no .efi extension,
1341 // returns a copy of the original input.
1342 CHAR16 * StripEfiExtension(CHAR16 *FileName) {
1343 UINTN Length;
1344 CHAR16 *Copy = NULL;
1345
1346 if ((FileName != NULL) && ((Copy = StrDuplicate(FileName)) != NULL)) {
1347 Length = StrLen(Copy);
1348 // Note: Do StriCmp() twice to work around Gigabyte Hybrid EFI case-sensitivity bug....
1349 if ((Length >= 4) && ((StriCmp(&Copy[Length - 4], L".efi") == 0) || (StriCmp(&Copy[Length - 4], L".EFI") == 0))) {
1350 Copy[Length - 4] = 0;
1351 } // if
1352 } // if
1353 return Copy;
1354 } // CHAR16 * StripExtension()
1355
1356 //
1357 // memory string search
1358 //
1359
1360 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
1361 {
1362 UINT8 *BufferPtr;
1363 UINTN Offset;
1364
1365 BufferPtr = Buffer;
1366 BufferLength -= SearchStringLength;
1367 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
1368 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
1369 return (INTN)Offset;
1370 }
1371
1372 return -1;
1373 }
1374
1375 // Performs a case-insensitive search of BigStr for SmallStr.
1376 // Returns TRUE if found, FALSE if not.
1377 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
1378 CHAR16 *SmallCopy, *BigCopy;
1379 BOOLEAN Found = FALSE;
1380 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
1381
1382 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1383 SmallCopy = StrDuplicate(SmallStr);
1384 BigCopy = StrDuplicate(BigStr);
1385 StrLwr(SmallCopy);
1386 StrLwr(BigCopy);
1387 SmallLen = StrLen(SmallCopy);
1388 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1389 while ((!Found) && (StartPoint < NumCompares)) {
1390 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1391 } // while
1392 MyFreePool(SmallCopy);
1393 MyFreePool(BigCopy);
1394 } // if
1395
1396 return (Found);
1397 } // BOOLEAN StriSubCmp()
1398
1399 // Merges two strings, creating a new one and returning a pointer to it.
1400 // If AddChar != 0, the specified character is placed between the two original
1401 // strings (unless the first string is NULL or empty). The original input
1402 // string *First is de-allocated and replaced by the new merged string.
1403 // This is similar to StrCat, but safer and more flexible because
1404 // MergeStrings allocates memory that's the correct size for the
1405 // new merged string, so it can take a NULL *First and it cleans
1406 // up the old memory. It should *NOT* be used with a constant
1407 // *First, though....
1408 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1409 UINTN Length1 = 0, Length2 = 0;
1410 CHAR16* NewString;
1411
1412 if (*First != NULL)
1413 Length1 = StrLen(*First);
1414 if (Second != NULL)
1415 Length2 = StrLen(Second);
1416 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1417 if (NewString != NULL) {
1418 if ((*First != NULL) && (StrLen(*First) == 0)) {
1419 MyFreePool(*First);
1420 *First = NULL;
1421 }
1422 NewString[0] = L'\0';
1423 if (*First != NULL) {
1424 StrCat(NewString, *First);
1425 if (AddChar) {
1426 NewString[Length1] = AddChar;
1427 NewString[Length1 + 1] = '\0';
1428 } // if (AddChar)
1429 } // if (*First != NULL)
1430 if (Second != NULL)
1431 StrCat(NewString, Second);
1432 MyFreePool(*First);
1433 *First = NewString;
1434 } else {
1435 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1436 } // if/else
1437 } // static CHAR16* MergeStrings()
1438
1439 // Takes an input pathname (*Path) and returns the part of the filename from
1440 // the final dot onwards, converted to lowercase. If the filename includes
1441 // no dots, or if the input is NULL, returns an empty (but allocated) string.
1442 // The calling function is responsible for freeing the memory associated with
1443 // the return value.
1444 CHAR16 *FindExtension(IN CHAR16 *Path) {
1445 CHAR16 *Extension;
1446 BOOLEAN Found = FALSE, FoundSlash = FALSE;
1447 INTN i;
1448
1449 Extension = AllocateZeroPool(sizeof(CHAR16));
1450 if (Path) {
1451 i = StrLen(Path);
1452 while ((!Found) && (!FoundSlash) && (i >= 0)) {
1453 if (Path[i] == L'.')
1454 Found = TRUE;
1455 else if ((Path[i] == L'/') || (Path[i] == L'\\'))
1456 FoundSlash = TRUE;
1457 if (!Found)
1458 i--;
1459 } // while
1460 if (Found) {
1461 MergeStrings(&Extension, &Path[i], 0);
1462 StrLwr(Extension);
1463 } // if (Found)
1464 } // if
1465 return (Extension);
1466 } // CHAR16 *FindExtension
1467
1468 // Takes an input pathname (*Path) and locates the final directory component
1469 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1470 // function returns the string 'foo'.
1471 // Assumes the pathname is separated with backslashes.
1472 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1473 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1474 CHAR16 *Found = NULL;
1475
1476 if (Path == NULL)
1477 return NULL;
1478
1479 PathLength = StrLen(Path);
1480 // Find start & end of target element
1481 for (i = 0; i < PathLength; i++) {
1482 if (Path[i] == '\\') {
1483 StartOfElement = EndOfElement;
1484 EndOfElement = i;
1485 } // if
1486 } // for
1487 // Extract the target element
1488 if (EndOfElement > 0) {
1489 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1490 StartOfElement++;
1491 } // while
1492 EndOfElement--;
1493 if (EndOfElement >= StartOfElement) {
1494 CopyLength = EndOfElement - StartOfElement + 1;
1495 Found = StrDuplicate(&Path[StartOfElement]);
1496 if (Found != NULL)
1497 Found[CopyLength] = 0;
1498 } // if (EndOfElement >= StartOfElement)
1499 } // if (EndOfElement > 0)
1500 return (Found);
1501 } // CHAR16 *FindLastDirName
1502
1503 // Returns the directory portion of a pathname. For instance,
1504 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1505 // string 'EFI\foo'. The calling function is responsible for
1506 // freeing the returned string's memory.
1507 CHAR16 *FindPath(IN CHAR16* FullPath) {
1508 UINTN i, LastBackslash = 0;
1509 CHAR16 *PathOnly = NULL;
1510
1511 if (FullPath != NULL) {
1512 for (i = 0; i < StrLen(FullPath); i++) {
1513 if (FullPath[i] == '\\')
1514 LastBackslash = i;
1515 } // for
1516 PathOnly = StrDuplicate(FullPath);
1517 PathOnly[LastBackslash] = 0;
1518 } // if
1519 return (PathOnly);
1520 }
1521
1522 // Takes an input loadpath, splits it into disk and filename components, finds a matching
1523 // DeviceVolume, and returns that and the filename (*loader).
1524 VOID FindVolumeAndFilename(IN EFI_DEVICE_PATH *loadpath, OUT REFIT_VOLUME **DeviceVolume, OUT CHAR16 **loader) {
1525 CHAR16 *DeviceString, *VolumeDeviceString, *Temp;
1526 UINTN i = 0;
1527 BOOLEAN Found = FALSE;
1528
1529 MyFreePool(*loader);
1530 MyFreePool(*DeviceVolume);
1531 *DeviceVolume = NULL;
1532 DeviceString = DevicePathToStr(loadpath);
1533 *loader = SplitDeviceString(DeviceString);
1534
1535 while ((i < VolumesCount) && (!Found)) {
1536 VolumeDeviceString = DevicePathToStr(Volumes[i]->DevicePath);
1537 Temp = SplitDeviceString(VolumeDeviceString);
1538 if (StriCmp(DeviceString, VolumeDeviceString) == 0) {
1539 Found = TRUE;
1540 *DeviceVolume = Volumes[i];
1541 }
1542 MyFreePool(Temp);
1543 MyFreePool(VolumeDeviceString);
1544 i++;
1545 } // while
1546
1547 MyFreePool(DeviceString);
1548 } // VOID FindVolumeAndFilename()
1549
1550 // Splits a volume/filename string (e.g., "fs0:\EFI\BOOT") into separate
1551 // volume and filename components (e.g., "fs0" and "\EFI\BOOT"), returning
1552 // the filename component in the original *Path variable and the split-off
1553 // volume component in the *VolName variable.
1554 // Returns TRUE if both components are found, FALSE otherwise.
1555 BOOLEAN SplitVolumeAndFilename(IN OUT CHAR16 **Path, OUT CHAR16 **VolName) {
1556 UINTN i = 0, Length;
1557 CHAR16 *Filename;
1558
1559 if (*Path == NULL)
1560 return FALSE;
1561
1562 if (*VolName != NULL) {
1563 MyFreePool(*VolName);
1564 *VolName = NULL;
1565 }
1566
1567 Length = StrLen(*Path);
1568 while ((i < Length) && ((*Path)[i] != L':')) {
1569 i++;
1570 } // while
1571
1572 if (i < Length) {
1573 Filename = StrDuplicate((*Path) + i + 1);
1574 (*Path)[i] = 0;
1575 *VolName = *Path;
1576 *Path = Filename;
1577 return TRUE;
1578 } else {
1579 return FALSE;
1580 }
1581 } // BOOLEAN SplitVolumeAndFilename()
1582
1583 // Returns all the digits in the input string, including intervening
1584 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1585 // this function returns "3.3.4-7". If InString contains no digits,
1586 // the return value is NULL.
1587 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1588 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1589 CHAR16 *Found = NULL;
1590
1591 if (InString == NULL)
1592 return NULL;
1593
1594 InLength = StartOfElement = StrLen(InString);
1595 // Find start & end of target element
1596 for (i = 0; i < InLength; i++) {
1597 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1598 if (StartOfElement > i)
1599 StartOfElement = i;
1600 if (EndOfElement < i)
1601 EndOfElement = i;
1602 } // if
1603 } // for
1604 // Extract the target element
1605 if (EndOfElement > 0) {
1606 if (EndOfElement >= StartOfElement) {
1607 CopyLength = EndOfElement - StartOfElement + 1;
1608 Found = StrDuplicate(&InString[StartOfElement]);
1609 if (Found != NULL)
1610 Found[CopyLength] = 0;
1611 } // if (EndOfElement >= StartOfElement)
1612 } // if (EndOfElement > 0)
1613 return (Found);
1614 } // CHAR16 *FindNumbers()
1615
1616 // Find the #Index element (numbered from 0) in a comma-delimited string
1617 // of elements.
1618 // Returns the found element, or NULL if Index is out of range or InString
1619 // is NULL. Note that the calling function is responsible for freeing the
1620 // memory associated with the returned string pointer.
1621 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1622 UINTN StartPos = 0, CurPos = 0;
1623 BOOLEAN Found = FALSE;
1624 CHAR16 *FoundString = NULL;
1625
1626 if (InString != NULL) {
1627 // After while() loop, StartPos marks start of item #Index
1628 while ((Index > 0) && (CurPos < StrLen(InString))) {
1629 if (InString[CurPos] == L',') {
1630 Index--;
1631 StartPos = CurPos + 1;
1632 } // if
1633 CurPos++;
1634 } // while
1635 // After while() loop, CurPos is one past the end of the element
1636 while ((CurPos < StrLen(InString)) && (!Found)) {
1637 if (InString[CurPos] == L',')
1638 Found = TRUE;
1639 else
1640 CurPos++;
1641 } // while
1642 if (Index == 0)
1643 FoundString = StrDuplicate(&InString[StartPos]);
1644 if (FoundString != NULL)
1645 FoundString[CurPos - StartPos] = 0;
1646 } // if
1647 return (FoundString);
1648 } // CHAR16 *FindCommaDelimited()
1649
1650 // Returns TRUE if SmallString is an element in the comma-delimited List,
1651 // FALSE otherwise. Performs comparison case-insensitively (except on
1652 // buggy EFIs with case-sensitive StriCmp() functions).
1653 BOOLEAN IsIn(IN CHAR16 *SmallString, IN CHAR16 *List) {
1654 UINTN i = 0;
1655 BOOLEAN Found = FALSE;
1656 CHAR16 *OneElement;
1657
1658 if (SmallString && List) {
1659 while (!Found && (OneElement = FindCommaDelimited(List, i++))) {
1660 if (StriCmp(OneElement, SmallString) == 0)
1661 Found = TRUE;
1662 } // while
1663 } // if
1664 return Found;
1665 } // BOOLEAN IsIn()
1666
1667 // Implement FreePool the way it should have been done to begin with, so that
1668 // it doesn't throw an ASSERT message if fed a NULL pointer....
1669 VOID MyFreePool(IN VOID *Pointer) {
1670 if (Pointer != NULL)
1671 FreePool(Pointer);
1672 }
1673
1674 static EFI_GUID AppleRemovableMediaGuid = APPLE_REMOVABLE_MEDIA_PROTOCOL_GUID;
1675
1676 // Eject all removable media.
1677 // Returns TRUE if any media were ejected, FALSE otherwise.
1678 BOOLEAN EjectMedia(VOID) {
1679 EFI_STATUS Status;
1680 UINTN HandleIndex, HandleCount = 0, Ejected = 0;
1681 EFI_HANDLE *Handles, Handle;
1682 APPLE_REMOVABLE_MEDIA_PROTOCOL *Ejectable;
1683
1684 Status = LibLocateHandle(ByProtocol, &AppleRemovableMediaGuid, NULL, &HandleCount, &Handles);
1685 if (EFI_ERROR(Status) || HandleCount == 0)
1686 return (FALSE); // probably not an Apple system
1687
1688 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1689 Handle = Handles[HandleIndex];
1690 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &AppleRemovableMediaGuid, (VOID **) &Ejectable);
1691 if (EFI_ERROR(Status))
1692 continue;
1693 Status = refit_call1_wrapper(Ejectable->Eject, Ejectable);
1694 if (!EFI_ERROR(Status))
1695 Ejected++;
1696 }
1697 MyFreePool(Handles);
1698 return (Ejected > 0);
1699 } // VOID EjectMedia()
1700
1701
1702 // Return the GUID as a string, suitable for display to the user. Note that the calling
1703 // function is responsible for freeing the allocated memory.
1704 CHAR16 * GuidAsString(EFI_GUID *GuidData) {
1705 CHAR16 *TheString;
1706
1707 TheString = AllocateZeroPool(42 * sizeof(CHAR16));
1708 if (TheString != 0) {
1709 SPrint (TheString, 82, L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1710 (UINTN)GuidData->Data1, (UINTN)GuidData->Data2, (UINTN)GuidData->Data3,
1711 (UINTN)GuidData->Data4[0], (UINTN)GuidData->Data4[1], (UINTN)GuidData->Data4[2],
1712 (UINTN)GuidData->Data4[3], (UINTN)GuidData->Data4[4], (UINTN)GuidData->Data4[5],
1713 (UINTN)GuidData->Data4[6], (UINTN)GuidData->Data4[7]);
1714 }
1715 return TheString;
1716 } // GuidAsString(EFI_GUID *GuidData)