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